https://wiki.archlinux.org/api.php?action=feedcontributions&user=Malcontent&feedformat=atomArchWiki - User contributions [en]2024-03-29T08:16:03ZUser contributionsMediaWiki 1.41.0https://wiki.archlinux.org/index.php?title=QEMU_(Espa%C3%B1ol)&diff=796062QEMU (Español)2024-01-04T20:54:27Z<p>Malcontent: Better Spanish docs</p>
<hr />
<div>[[Category:Emulation (Español)]]<br />
[[Category:Hypervisors (Español)]]<br />
[[de:QEMU]]<br />
[[en:QEMU]]<br />
[[fr:QEMU]]<br />
[[ja:QEMU]]<br />
[[zh-hans:QEMU]]<br />
{{Bad translation (Español)|No updates since 2017-01-12, English page has seen major changes since.}}<br />
{{TranslationStatus (Español)|QEMU|2017-01-12|463282}}<br />
{{Related articles start (Español)}}<br />
{{Related|:Category:Hypervisors}}<br />
{{Related|Libvirt}}<br />
{{Related articles end}}<br />
<br />
De acuerdo con [https://wiki.qemu.org/Main_Page la wiki de QEMU], "QEMU es un emulador genérico y de código abierto de máquinas virtuales."<br />
<br />
Cuando se utiliza como un emulador de máquina, QEMU puede correr sistemas operativos y programas hechos para una máquina en particular (por ej. una placa ARM) en una máquina diferente (e.j. tu PC x86). Usando la traducción dinámica, se consigue un rendimiento muy bueno.<br />
<br />
QEMU puede usar hipervisores como [[Xen]] o [[KVM]] para utilizar las extensiones del procesador para la virtualización. Cuando se utiliza como virtualizador, QEMU alcanza un performance cercano a el rendimiento nativo ejecutando el código de invitado directamente en el CPU host.<br />
<br />
== Instalación ==<br />
<br />
[[Help:Reading (Español)#Instalación de paquetes|Instale]] el paquete {{Pkg|qemu-desktop}} (ó {{Pkg|qemu-base}} para la versión sin GUI) y los paquetes opcionales para tus necesidades:<br />
<br />
* {{Pkg|qemu-emulators-full}} - Soporte extra para arquitecturas<br />
* {{Pkg|qemu-block-gluster}} - Soporte para bloque glusterfs <br />
* {{Pkg|qemu-block-iscsi}} - Soporte para bloque iSCSI <br />
* {{Pkg|qemu-block-rbd}}{{Broken package link (Español)|package not found}} - Soporte para bloque RBD <br />
* {{Pkg|samba}} - SMB/ Soporte para servidor CIFS<br />
<br />
== front-ends para QEMU ==<br />
<br />
A diferencia de otros programas de virtualización como [[VirtualBox]] y [[VMware]], QEMU no proporciona una interfaz gráfica de usuario para administrar máquinas virtuales (a parte de la ventana que aparece cuando se ejecuta una máquina virtual), tampoco proporciona una forma de crear una máquina virtual persistente con valores guardados. Todos los parámetros para ejecutar una máquina virtual deben especificarse en la línea de comandos en cada puesta en marcha, a menos que haga un script personalizadp para iniciar su máquina(s) virtual. Sin embargo, hay varios front-end GUI para QEMU: <br />
<br />
* {{AUR|qemu-launcher}}<br />
* {{AUR|qtemu}}<br />
* {{AUR|aqemu}}<br />
<br />
front-ends con soporte para QEMU están disponibles por [[libvirt]].<br />
<br />
== Creando un nuevo sistema virtualizado ==<br />
<br />
=== Creando una imagen de disco duro ===<br />
<br />
{{Tip (Español)|Véase la [https://en.wikibooks.org/wiki/QEMU/Images Wiki de QEMU] para más información sobre imágenes de QEMU.}}<br />
<br />
Para ejecutar QMEU necesitarás una imagen de disco duro, a menos que estés cargando un sistema en vivo desde el CD-ROM ó la red (y no para instalar un sistema operativo en una imagen de disco duro). Una imagen de disco es un archivo que almacena los contenidos del disco duro emulado.<br />
<br />
Una imagen de disco puede ser en "crudo", de manera que, literalemte, byte por byte es lo mismo que el cliente ve, y siempre utilizará toda la capacidad del disco duro del disco duro invitado en el host. Este método proporciona la menor sobrecarga de Entrada / Salida, pero puede desperdiciar una gran cantidad de espacio, ya que el espacio no utilizado por el invitado no se puede utilizar en el host. <br />
<br />
Por otra parte, la imagen de disco duro puede estar en un formato tal como el de ''qcow2'' el cuál únicamente asigna espacio a el archivo de la imagen cuando el SO invitado está escribiendo en los sectores del disco virtual. La imagen aparece como el tamaño total del sistema operativo huésped, a pesar que puede tomar hasta una cantidad muy pequeña de espacio en el sistema host. El uso de este formato en lugar de el "crudo" probablemente afecte el rendimiento. <br />
<br />
QEMU proporciona el {{ic|qemu-img}} comando para crear imagenes de disco.<br />
Por ejemplo, para crear una imagen de 4GB en formato "crudo":<br />
<br />
$ qemu-img create -f raw ''image_file'' 4G<br />
<br />
Se puede uiltizar {{ic|-f qcow2}} para crear un disco ''qcow2'' en su lugar. <br />
<br />
{{Note (Español)|También puedes simplemente crear una imagen "cruda" meidante la creación de un archivo del tamaño necesitado usando {{ic|dd}} ó {{ic|fallocate}}.}}<br />
<br />
{{Warning (Español)|Si almacenas una imágen de disco en un sistema de archivos [[Btrfs (Español)|Btrfs]], deberías considerar deshabilitar [[Btrfs (Español)#Copy-on-Write (CoW)|Copy-on-Write]] para el directorio antes de crear imágenes.}}<br />
<br />
==== Superposición de imágenes de almacenamiento ====<br />
<br />
Puede crear una imagen de almacenamiento una vez (la imagen de respaldo) y hacer que QEMU mantenga mutaciones a esta imagen en una imagen de superposición. Esto le permite volver a un estado anterior de esta imagen de almacenamiento. Puede volver a crear una nueva imagen de superposición en el momento en que desea revertir en función de la imagen de respaldo original.<br />
<br />
Para crear una imagen de superposición, ingrese el comando:<br />
<br />
$ qemu-img create -o backing_file=''img1.raw'',backing_fmt=''raw'' -f ''qcow2'' ''img1.cow''<br />
<br />
Después de eso, puede ejecutar su máquina virtual como de costumbre (ver [[#Ejecución del sistema virtualizado]]):<br />
<br />
$ qemu-system-x86_64 ''img1.cow''<br />
<br />
La imagen de respaldo se dejará intacta y se registrarán mutaciones en este almacenamiento en el archivo de imagen de superposición.<br />
<br />
Cuando cambia la ruta de acceso a la imagen de respaldo, se requiere reparación.<br />
<br />
{{Warning (Español)|La ruta del sistema de archivos absoluto de la imagen de respaldo se almacena en el archivo de imagen de superposición (binario)). Cambiar el trayecto de la imagen de respaldo requiere un esfuerzo.}}<br />
<br />
Asegúrese de que la ruta de la imagen de respaldo original sigue conduciendo a esta imagen. Si es necesario, haga un enlace simbólico en la ruta original a la nueva ruta. A continuación, emita un comando como:<br />
<br />
$ qemu-img rebase -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
A su discreción, usted puede alternativamente realizar un rebase 'inseguro' donde no se comprueba la ruta anterior a la imagen de respaldo:<br />
<br />
$ qemu-img rebase -u -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
==== Cambiar el tamaño de una imagen ====<br />
<br />
{{Warning (Español)|Cambiar el tamaño de una imagen que contiene un sistema de arranque NTFS podría hacer el sistema operativo instalado '''no arrancable'''. Para una explicación completa y solucioón alternativa mira [https://web.archive.org/web/20180319230757/http://tjworld.net/wiki/Howto/ResizeQemuDiskImages].}}<br />
<br />
El ejecutable {{ic|qemu-img}} tiene la opción {{ic|resize}}, que permite redimensionar fácilmente una imagen de disco duro. Funciona tanto para ''raw'' como para ''qcow2''. Por ejemplo, para aumentar el espacio de imagen en 10GB, ingresa:<br />
<br />
$ qemu-img resize ''disk_image'' +10G<br />
<br />
Después de ampliar la imagen de disco, debe utilizar el sistema de archivos y las herramientas de particionamiento dentro de la máquina virtual para comenzar a utilizar el nuevo espacio. Al reducir una imagen de disco, primero debe reducir los sistemas de archivos y los tamaños de partición asignados usando el sistema de archivos y las herramientas de partición dentro de la máquina virtual y luego reducir la imagen del disco en consecuencia, de lo contrario reducir la imagen del disco resultará en ¡pérdida de datos!<br />
<br />
=== Preparando el medio de instalación ===<br />
<br />
Para instalar un sistema operativo en su imagen de disco, necesita el medio de instalación (por ejemplo, disco óptico, unidad USB o imagen ISO) para el sistema operativo. El soporte de instalación no debe montarse porque QEMU accede directamente al medio.<br />
<br />
{{Tip (Español)|Si utiliza un disco óptico, es una buena idea volcar primero los medios a un archivo porque esto mejora el rendimiento y no requiere que tenga acceso directo a los dispositivos (es decir, puede ejecutar QEMU como un usuario normal sin tener Para cambiar permisos de acceso en el archivo de dispositivo del medio). Por ejemplo, si el nodo de dispositivo de CD-ROM tiene el nombre {{ic|/dev/cdrom}}, puede volcarlo a un archivo de comandos: {{bc|1=$ dd if=/dev/cdrom of=''Cd_image.iso''}}}}<br />
<br />
=== Instalando el sistema operativo ===<br />
<br />
Esta es la primera vez que necesitará iniciar el emulador. Para instalar el sistema operativo en la imagen de disco, debe adjuntar la imagen de disco y el medio de instalación a la máquina virtual y hacer que arranque desde el soporte de instalación.<br />
<br />
Por ejemplo, en invitados i386, para instalar desde un archivo ISO de arranque como CD-ROM y una imagen de disco sin formato:<br />
<br />
$ qemu-system-x86_64 -cdrom ''iso_image'' -boot order=d -drive file=''disk_image'',format=raw<br />
<br />
Consulte {{ic | qemu (1)}} para obtener más información sobre cómo cargar otros tipos de medios (como disquetes, imágenes de disco o unidades físicas) y [[#Ejecución del sistema virtualizado]] para otras opciones útiles.<br />
<br />
Una vez que el sistema operativo haya finalizado de instalar, la imagen de QEMU se puede iniciar directamente (ver [[#Ejecución del sistema virtualizado]]).<br />
<br />
{{Warning (Español)|De forma predeterminada, sólo se asignan 128 MB de memoria a la máquina. La cantidad de memoria se puede ajustar con el interruptor {{ic | -m}}, por ejemplo {{ic | -m 512M}} o {{ic | -m 2G}}.}}<br />
<br />
{{Tip (Español)|<br />
* En lugar de especificar {{ic | 1 = -boot order = x}}, algunos usuarios pueden sentirse más cómodos usando un menú de arranque: {{ic | 1 = -boot menu = on}}, al menos durante la configuración y la experimentación.<br />
* Si necesita reemplazar disquetes o CD como parte del proceso de instalación, puede usar el monitor de la máquina QEMU (presione {{ic | Ctrl + Alt + 2}} en la ventana de la máquina virtual) para quitar y conectar dispositivos de almacenamiento a un máquina virtual. Escriba {{ic | info block}} para ver los dispositivos de bloque y use el comando {{ic | change}} para intercambiar un dispositivo. Pulse {{ic | Ctrl + Alt + 1}} para volver a la máquina virtual.}}<br />
<br />
== Ejecución del sistema virtualizado ==<br />
<br />
Los binarios {{ic|qemu-system-*}} (por e.j. {{ic|qemu-system-i386}} ó {{ic|qemu-system-x86_64}}, dependiendo de la arquitectura del huésped) se usan para ejecutar el sistema virtualizado. El uso es:<br />
<br />
$ qemu-system-x86_64 ''options'' ''disk_image''<br />
<br />
Las opciones son las mismas para todos los binarios {{ic|qemu-system-*}}, mira {{ic|qemu(1)}} para más información sobre todas las opciones.<br />
<br />
Por defecto, QEMU mostrará la salida de video de la máquina virtual en una ventana. Una cosa a considerar: al hacer click dentro de la ventana de QMEU, el puntero del cursor será capturado. Para liberarlo presione {{ic|Ctrl+Alt+g}}.<br />
<br />
{{Warning (Español)|QEMU nunca debe ejecutarse como root. Si se debe iniciar en root, deberá usar la opción {{ic|-runas}} para que QEMU utilice privilegios de root.}}<br />
<br />
=== Activar KVM ===<br />
<br />
KVM debe ser soportado por su procesador y kernel, y necesariamente los [[kernel modules (Español)|módulos del kernel]] deben ser cargados. Mira [[KVM]] para más información.<br />
<br />
Para iniciar QEMU en modo KVM, adjunta {{ic|-enable-kvm}} a las opciones de inicio adicionales. Para verificar si KVM está activado para ejecutar una máquina virtual, ingresa a la wiki de QEMU [https://en.wikibooks.org/wiki/QEMU/Monitor Monitor], usando {{ic|Ctrl+Alt+Shift+2}}, e ingresando {{ic|info kvm}}. <br />
<br />
{{Note (Español)|<br />
* Si inicia su máquina virtual con una herramienta GUI y experimenta un rendimiento muy malo, debe verificar el soporte adecuado de KVM. <br />
* KVM necesita activarse en orden de iniciar adecuadamente Windows 7 y Windows 8 sin ''pantallazo azul''.<br />
}}<br />
<br />
=== Habilitar soporte IOMMU (Intel VT-d/AMD-Vi) ===<br />
<br />
Usando IOMMU (unidad de gestión de memoria de entrada y salida) se abre a las caraterísticas como el paso del PCI y la protección de la memoria de dispositivos defectuosos o maliciosos, mira [[wikipedia:Input-output memory management unit#Advantages]] y [https://www.quora.com/Memory-Management-computer-programming/Could-you-explain-IOMMU-in-plain-English Memory Management (computer programming): Could you explain IOMMU in plain English?].<br />
<br />
Para habilitar IOMMU:<br />
#Asegure que AMD-Vi/Intel VT-d es soportado por el CPU y es habilitado en la configuración de BIOS.<br />
#Agregue {{ic|1=intel_iommu=on}} si tienes un procesador Intel ó {{ic|1=amd_iommu=on}} si tienes un procesador AMD en los parámetros del kernel ([[kernel parameters]])<br />
#Reinicie y asegure que IOMMU está habilitado verificando {{ic|dmesg}} para {{ic|DMAR}}: {{ic|[0.000000] DMAR: IOMMU enabled}}<br />
#Añade {{ic|-device intel-iommu}} para crear el dispositivo IOMMU:<br />
<br />
$ qemu-system-x86_64 '''-enable-kvm -machine q35 -device intel-iommu''' -cpu host ..<br />
<br />
== Mover datos entre el host y el Sistema Operativo huésped ==<br />
<br />
=== Red ===<br />
<br />
Los datos pueden compartirse entre el host y el sistema operativo huésped usando cualquier protocolo de red que pueda transferir archivos, como [[NFS]], [[SMB]], [[Wikipedia:Network Block Device|NBD]], HTTP, [[Very Secure FTP Daemon|FTP]], ó [[SSH]], siempre que haya configurado la red apropiadamente y haya habilitado los servicios apropiados. <br />
<br />
La red por defecto del modo de usuario permite al huésped acceder al sistema operativo host en la dirección IP 10.0.2.2. Todos los servidores que se estén ejecutando en el sistema operativo anfitrión, como un servidor SSH o un servidor SMB, estarán accesibles en esta dirección IP. Así que en los invitados, puede montar los directorios exportados en el host a través de [[SMB]] o [[NFS]], o puede acceder al servidor HTTP del host, etc.<br />
No será posible que el sistema operativo anfitrión acceda a los servidores que se ejecutan en el sistema operativo invitado, pero esto puede hacerse con otras configuraciones de red (consulte [[#Tap de red con QEMU]]).<br />
<br />
=== Servidor SMB incorporado de QEMU ===<br />
<br />
La documentación de QEMU dice que tiene un servidor SMB "incorporado", pero en realidad acaba de iniciar [[Samba]] con un archivo {{ic | smb.conf}} generado automáticamente ubicado en {{ic|/tmp/qemu- Smb.''Pid''-0/smb.conf}} y lo hace accesible para el invitado en una dirección IP diferente (10.0.2.4 por defecto). Esto sólo funciona para la red de usuarios, y esto no es necesariamente muy útil ya que el invitado también puede acceder al servicio normal [[Samba]] en el host si ha configurado acciones en él.<br />
<br />
Para habilitar esta característica, inicie QEMU con un comando como:<br />
<br />
$ qemu-system-x86_64 -nic user,id=nic0,smb=''shared_dir_path'' ''disk_image''<br />
<br />
donde {{ic|''shared_dir_path''}} es un directorio que quieres compartir entre huésped y el host.<br />
<br />
Luego, en el invitado, podrá acceder al directorio compartido del host 10.0.2.4 con el nombre de recurso "qemu". Por ejemplo, en el Explorador de Windows iría a {{ic | \\ 10.0.2.4 \ qemu}}.<br />
<br />
{{Note (Español)|<br />
* Si estás usando opciones de compartir varias veces como {{ic|1=-net user, smb='' shared_dir_path1 '' -net user, smb='' shared_dir_path2 ''}} ó {{ic | 1 = -net user , Smb = '' shared_dir_path1 '', smb = '' shared_dir_path2 ''}} entonces solo compartirá el último definido.<br />
* Si no puede acceder a la carpeta compartida y el sistema invitado es Windows, compruebe que está habilitado el protocolo [http://ecross.mvps.org/howto/enable-netbios-over-tcp-ip-with-windows.htm NetBIOS ]{{Dead link (Español)|2023|05|06|status=domain name not resolved}} Y que un cortafuegos no bloquea los puertos [https://technet.microsoft.com/en-us/library/cc940063.aspx] utilizados por el protocolo NetBIOS.<br />
}}<br />
<br />
=== Montaje de una partición dentro de una imagen de disco raw ===<br />
<br />
Cuando la máquina virtual no se está ejecutando, es posible montar las particiones que están dentro de un archivo de imagen de disco sin formato configurándolas como dispositivos de bucle invertido. Esto no funciona con imágenes de disco en formatos especiales, como qcow2, aunque se pueden montar usando {{ic|qemu-nbd}}.<br />
<br />
{{Warning (Español)| Debe asegurarse de desmontar las particiones antes de ejecutar la máquina virtual de nuevo. De lo contrario, es muy probable que ocurra la corrupción de datos.}}<br />
<br />
==== Con la especificación manual del desplazamiento de bytes ====<br />
<br />
Una forma de montar una partición de imagen de disco es montar la imagen de disco en un cierto desplazamiento usando un comando como el siguiente:<br />
<br />
$ mount -o loop, offset = 32256 ''disk_image'' ''mountpoint''<br />
<br />
La opción {{ic|1 = offset = 32256}} se pasa realmente al programa {{ic|losetup}} para configurar un dispositivo de bucle invertido que empieza en el desplazamiento de byte 32256 del archivo y continúa hasta el final. A continuación, se monta este dispositivo de bucle invertido. También puede utilizar la opción {{ic|sizelimit}} para especificar el tamaño exacto de la partición, pero esto normalmente no es necesario.<br />
<br />
Dependiendo de la imagen del disco, la partición necesaria no se puede iniciar en el desplazamiento 32256. Ejecute {{ic|fdisk -l '' disk_image ''}} para ver las particiones de la imagen. Fdisk da las compensaciones de inicio y fin en sectores de 512 bytes, así que multiplique por 512 para obtener el desplazamiento correcto para pasar a {{ic|mount}}.<br />
<br />
==== Con las particiones autodetecting del módulo de bucle (loop) ====<br />
<br />
El controlador de bucle de Linux realmente admite particiones en dispositivos de bucle invertido, pero está desactivado de forma predeterminada. Para habilitarlo, haga lo siguiente:<br />
<br />
* Deshacerse de todos los dispositivos de bucle invertido (desmontar todas las imágenes montadas, etc.).<br />
* [[Kernel modules (Español)#Manejo manual de módulos|Descargar]] el módulo del kernel {{ic|loop}} y cargarlo con el conjunto de parámetros {{ic|1 = max_part = 15}}. Además, el número máximo de dispositivos de bucle puede controlarse con el parámetro {{ic | max_loop}}.<br />
<br />
{{Tip (Español)|Puede poner una entrada en {{ic|/etc/modprobe.d}} para cargar el módulo de bucle con {{ic|1=max_part=15}} cada vez, o puede poner {{ic|1 = loop.max_part = 15}} en la línea de comandos del kernel, dependiendo de si tiene o no el módulo {{ic|loop.ko}} integrado en su kernel.}}<br />
<br />
Configure su imagen como un dispositivo de bucle invertido:<br />
<br />
$ losetup -f -P ''disk_image''<br />
<br />
Entonces, si el dispositivo creado fue {{ic|/dev/loop0}}, se habrán creado automáticamente dispositivos adicionales {{ic|/dev/loop0pX}}, donde X es el número de la partición. Estos dispositivos de loopback de partición se pueden montar directamente. Por ejemplo:<br />
<br />
$ mount /dev/loop0p1 ''punto de montaje''<br />
<br />
Para montar la imagen de disco con '' udisksctl '', vea [[Udisks#Mount loop devices]].<br />
<br />
==== Con kpartx ====<br />
<br />
'' 'Kpartx' '' del paquete {{Pkg|multipath-tools}} puede leer una tabla de particiones en un dispositivo y crear un nuevo dispositivo para cada partición. Por ejemplo:<br />
# Kpartx -a '' disk_image ''<br />
<br />
Esto configurará el dispositivo de bucle invertido y creará los dispositivos de partición necesarios en {{ic|/dev/mapper/}}.<br />
<br />
=== Montar una partición dentro de una imagen qcow2 ===<br />
<br />
Puede montar una partición dentro de una imagen qcow2 usando {{ic|qemu-nbd}}. Mira [https://en.wikibooks.org/wiki/QEMU/Images#Mounting_an_image_on_the_host Wikibooks].<br />
<br />
=== Utilizar cualquier partición real como la única partición primaria de una imagen de disco duro ===<br />
<br />
A veces, puede que desee utilizar una de las particiones del sistema desde dentro de QEMU. El uso de una partición sin procesar para una máquina virtual mejorará el rendimiento, ya que las operaciones de lectura y escritura no pasan por la capa del sistema de archivos del host físico. Esta partición también proporciona una forma de compartir datos entre el host y el invitado.<br />
<br />
En Arch Linux, los archivos de dispositivo para las particiones sin procesar son, por defecto, propiedad de '' root '' y del grupo '' disk ''. Si desea que un usuario no root pueda leer y escribir en una partición en bruto, debe cambiar el propietario del archivo de dispositivo de la partición para ese usuario.<br />
<br />
{{Warning (Español)|<br />
* Aunque es posible, no se recomienda permitir que las máquinas virtuales alteren los datos críticos en el sistema host, como la partición raíz.<br />
* No debe montar un sistema de archivos en una partición de lectura-escritura en el host y el invitado al mismo tiempo. De lo contrario, se producirá corrupción de datos.<br />
}}<br />
<br />
Después de hacerlo, puede adjuntar la partición a una máquina virtual QEMU como un disco virtual.<br />
<br />
Sin embargo, las cosas son un poco más complicadas si desea tener la máquina virtual ''completa'' contenida en una partición. En ese caso, no habría ningún archivo de imagen de disco para arrancar realmente la máquina virtual, ya que no se puede instalar un cargador de arranque en una partición que está formateada como un sistema de archivos y no como un dispositivo particionado con un MBR. Una máquina virtual de este tipo se puede iniciar especificando el kernel y el initramfs manualmente o simulando un disco con un MBR usando RAID lineal.<br />
<br />
==== Especificar el kernel y el initrd manualmente ====<br />
<br />
QEMU es compatible con cargar [[Kernels|Linux kernels]] e [[initramfs|init ramdisks]] directamente, evitando así los cargadores de arranque como [[GRUB]]. A continuación, se puede iniciar con la partición física que contiene el sistema de archivos raíz como el disco virtual, que no parecen ser particionados. Esto se hace emitiendo un comando similar al siguiente:<br />
<br />
{{Note (Español)| En este ejemplo, se trata de las imágenes del '''host''' que se están utilizando, no del invitado. Si desea utilizar las imágenes del huésped, monte {{ic|/dev/sda3}} de sólo lectura (para proteger el sistema de archivos del host) y especifique {{ic|/full/path/to/images}} ó usar algún truco kexec en el invitado para recargar el kernel del invitado (extiende el tiempo de arranque).}}<br />
<br />
$ Qemu-system-i386 -kernel /boot/vmlinuz-linux -initrd /boot/initramfs-linux.img -append root=/dev/sda/dev/sda3<br />
<br />
En el ejemplo anterior, la partición física que se utiliza para el sistema de archivos raíz del huésped es {{ic|/dev/sda3}} en el host, pero aparece como {{ic|/dev/sda}} en el invitado.<br />
<br />
Por supuesto, puede especificar cualquier kernel e initrd que desee, y no sólo los que vienen con Arch Linux.<br />
<br />
Cuando hay varios [[kernel parameters]] que se pasan a la opción {{ic|-append}}, necesitan ser citados usando comillas simples o dobles. Por ejemplo:<br />
<br />
$ ... -append 'root=/dev/sda1 console=ttyS0'<br />
<br />
==== Simular disco virtual con MBR usando RAID lineal ====<br />
<br />
Una forma más complicada de tener una máquina virtual usar una partición física, mientras que mantener esa partición formateada como un sistema de archivos y no sólo tener la partición invitado la partición como si fuera un disco, es simular un MBR para que pueda Arranque utilizando un gestor de arranque tal como GRUB.<br />
<br />
Puede hacerlo utilizando el RAID del software en modo lineal (necesita el controlador de kernel {{ic|linear.ko}}) y un dispositivo de loopback: el truco consiste en añadir previamente un registro maestro de arranque (MBR) Real que desea incrustar en una imagen de disco RAEM QEMU.<br />
<br />
Suponga que tiene una partición simple {{ic|/|hdaN}} con algún sistema de archivos en la que desea formar parte de una imagen de disco QEMU. En primer lugar, crear un pequeño archivo para mantener el MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=32<br />
<br />
Aquí, se crea un archivo de 16 KB (32 * 512 bytes). Es importante no hacerlo demasiado pequeño (incluso si el MBR sólo necesita un bloque de 512 bytes), ya que cuanto menor sea, menor será el tamaño del chasis del dispositivo RAID de software, lo que podría tener un impacto En el rendimiento. A continuación, configura un dispositivo de bucle invertido en el archivo MBR:<br />
<br />
# losetup -f ''/path/to/mbr''<br />
<br />
Supongamos que el dispositivo resultante es {{ic|/dev/loop0}}, porque ya no habríamos estado usando otros bucle. El siguiente paso es crear la imagen de disco "fusionada" MBR + {{ic|/dev/hda''N''}} utilizando RAID de software:<br />
<br />
# modprobe lineal<br />
<br />
# mdadm --build --verbose /dev/md0 --chunk=16 --level=linear --raid-devices=2 /dev/loop0/dev/hda''N''<br />
<br />
El resultante {{ic|/dev/md0}} es lo que utilizará como una imagen de disco cruda QEMU (no olvide establecer los permisos para que el emulador pueda acceder a él). El último paso (y algo complicado) es configurar la configuración del disco (geometría del disco y tabla de particiones) para que el punto de inicio de la partición primaria en el MBR coincida con el de {{ic|/dev/hda''N''}}} Dentro {{ic|/dev/md0}} (un desplazamiento de exactamente 16 * 512 = 16384 bytes en este ejemplo). Hacer esto usando {{ic|fdisk}} en la máquina host, no en el emulador: la rutina de detección de disco crudo predeterminada de QEMU a menudo da lugar a offsets redondeados no kilobyte (como 31.5 KB, como en la sección anterior) que No puede ser administrado por el código RAID de software. Por lo tanto, desde el anfitrión:<br />
<br />
$ fdisk /dev/md0<br />
<br />
Pulse {{ic|X}} para entrar en el menú de expertos. Establezca el número de sectores por pista para que el tamaño de un cilindro coincida con el tamaño de su archivo MBR. Para dos cabezas y un tamaño de sector de 512, el número de sectores por pista debe ser 16, por lo que obtenemos cilindros de tamaño 2x16x512 = 16k.<br />
<br />
Ahora, presione {{ic|R}} para regresar al menú principal.<br />
<br />
Presione {{ic|P}} y compruebe que el tamaño del cilindro es ahora 16k.<br />
<br />
Ahora, cree una única partición primaria correspondiente a {{ic|/dev/hda''N''}}. Debe comenzar en el cilindro 2 y terminar en el extremo del disco (tenga en cuenta que el número de cilindros ahora difiere de lo que era cuando se introdujo fdisk.<br />
<br />
Finalmente, escribe el resultado al archivo: ya está. Ahora tiene una partición que puede montar directamente desde su host, así como parte de una imagen de disco QEMU:<br />
<br />
$ Qemu-system-i386 -hdc /dev/md0 ''[...]''<br />
<br />
Por supuesto, puede configurar con seguridad cualquier cargador de arranque en esta imagen de disco utilizando QEMU, siempre que la partición original {{ic|/dev/hda''N''}} contenga las herramientas necesarias.<br />
<br />
== Redes ==<br />
<br />
El rendimiento de la red virtual debería ser mejor con los dispositivos de derivación (tap) y puentes que con la red en modo de usuario o vde porque los dispositivos de derivación y los puentes se implementan en el kernel.<br />
<br />
Además, el rendimiento de la red se puede mejorar asignando a las máquinas virtuales un dispositivo de red [https://wiki.libvirt.org/page/Virtio virtio] en lugar de la emulación predeterminada de una NIC e1000. Consulte [[#Instalación de controladores virtio]] para obtener más información.<br />
<br />
=== Advertencia de dirección a nivel de enlace ===<br />
<br />
Al asignar el argumento {{ic|-net nic}} a QEMU, asignará por defecto a una máquina virtual una interfaz de red con la dirección de enlace {{ic|52:54:00:12:34:56}}. Sin embargo, cuando se utiliza la creación de redes puenteadas con varias máquinas virtuales, es esencial que cada máquina virtual tenga una dirección única de nivel de enlace (MAC) en el lado de la máquina virtual del dispositivo de derivación. De lo contrario, el puente no funcionará correctamente, ya que recibirá paquetes de varias fuentes que tienen la misma dirección de nivel de enlace. Este problema se produce incluso si los propios dispositivos de derivación tienen direcciones de nivel de enlace únicas porque la dirección de nivel de enlace de origen no se vuelve a escribir a medida que los paquetes pasan a través del dispositivo de derivación.<br />
<br />
Asegúrese de que cada máquina virtual tiene una dirección única de nivel de enlace, pero siempre debe comenzar con {{ic|52:54:}}. Utilice la opción siguiente, reemplazar ''X'' por un dígito hexadecimal arbitrario:<br />
<br />
$ qemu-system-i386 -net nic,macaddr=52:54:''XX:XX:XX:XX'' -net vde ''disk_image''<br />
<br />
Generar direcciones únicas de nivel de enlace se puede realizar de varias maneras:<br />
<br />
<ol><br />
<li>Especificar manualmente la dirección única de nivel de enlace para cada NIC. El beneficio es que el servidor DHCP asignará la misma dirección IP cada vez que se ejecute la máquina virtual, pero es inutilizable para un gran número de máquinas virtuales.<br />
</li><br />
<li>Generar dirección de nivel de enlace aleatoria cada vez que se ejecuta la máquina virtual. Prácticamente cero probabilidad de colisiones, pero la desventaja es que el servidor DHCP asignará una dirección IP diferente cada vez. Puede utilizar el siguiente comando en una secuencia de comandos para generar una dirección de nivel de enlace aleatoria en una variable {{ic|macaddr}}:<br />
<br />
{{bc|1=<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
qemu-system-i386 -net nic,macaddr="$macaddr" -net vde ''disk_image''<br />
}}<br />
<br />
</li><br />
<li>Utilice el siguiente script {{ic|qemu-mac-hasher.py}} para generar la dirección de nivel de enlace desde el nombre de la máquina virtual mediante una función de hash. Dado que los nombres de las máquinas virtuales son únicos, este método combina los beneficios de los métodos antes mencionados: genera la misma dirección de nivel de enlace cada vez que se ejecuta el script, aunque preserva la probabilidad prácticamente nula de colisiones.<br />
<br />
{{hc|qemu-mac-hasher.py|<nowiki><br />
#!/usr/bin/env python<br />
<br />
import sys<br />
import zlib<br />
<br />
if len(sys.argv) != 2:<br />
print("usage: %s <VM Name>" % sys.argv[0])<br />
sys.exit(1)<br />
<br />
crc = zlib.crc32(sys.argv[1].encode("utf-8")) & 0xffffffff<br />
crc = str(hex(crc))[2:]<br />
print("52:54:%s%s:%s%s:%s%s:%s%s" % tuple(crc))<br />
</nowiki>}}<br />
<br />
En un script, puede utilizar por ejemplo:<br />
<br />
vm_name="''VM Name''"<br />
qemu-system-i386 -name "$vm_name" -net nic,macaddr=$(qemu-mac-hasher.py "$vm_name") -net vde ''disk_image''<br />
</li><br />
</ol><br />
<br />
=== Redes en modo de usuario ===<br />
<br />
De forma predeterminada, sin ningún argumento {{ic|-netdev}}, QEMU utilizará la red en modo usuario con un servidor DHCP incorporado. A sus máquinas virtuales se les asignará una dirección IP cuando ejecuten su cliente DHCP, y podrán acceder a la red del host físico a través de la mascarada de IP realizada por QEMU.<br />
<br />
{{Warning (Español)| Esto sólo funciona con los protocolos TCP y UDP, por lo que ICMP, incluido {{ic|ping}}, no funcionará. No utilice {{ic|ping}} para probar la conectividad de red.}}<br />
<br />
Esta configuración predeterminada permite que sus máquinas virtuales accedan fácilmente a Internet, siempre que el host esté conectado a él, pero las máquinas virtuales no estarán directamente visibles en la red externa ni las máquinas virtuales podrán comunicarse entre sí si empieza Más de uno simultáneamente.<br />
<br />
La red de usuario en modo QEMU puede ofrecer más capacidades, como servidores TFTP o SMB incorporados, redirigir los puertos del host al huésped (por ejemplo, para permitir conexiones SSH al invitado) o conectar invitados a las VLAN para que puedan hablar entre sí. Consulte la documentación de QEMU en el indicador {{ic|-net user}} para obtener más detalles.<br />
<br />
Sin embargo, la conexión en red en modo usuario tiene limitaciones tanto en la utilidad como en el rendimiento. Las configuraciones de red más avanzadas requieren el uso de dispositivos de derivación u otros métodos.<br />
<br />
=== Tap de red con QEMU ===<br />
<br />
Los [[wikipedia:TUN/TAP|dispositivos tap]] Son una característica del kernel de Linux que le permite crear interfaces de red virtuales que aparecen como interfaces de red reales. Los paquetes enviados a una interfaz de derivación se entregan a un programa de espacio de usuario, tal como QEMU, que se ha enlazado a la interfaz.<br />
<br />
QEMU puede utilizar la red de derivación para una máquina virtual de modo que los paquetes enviados a la interfaz de derivación se envíen a la máquina virtual y aparezcan como procedentes de una interfaz de red (normalmente una interfaz Ethernet) en la máquina virtual. Por el contrario, todo lo que la máquina virtual envía a través de su interfaz de red aparecerá en la interfaz de tap.<br />
<br />
Los dispositivos de toque son soportados por los controladores de puente de Linux, por lo que es posible conectar entre sí los dispositivos entre sí y posiblemente con otras interfaces de host como {{ic|eth0}}. Esto es deseable si desea que sus máquinas virtuales puedan hablar entre sí, o si desea que otras máquinas en su LAN puedan hablar con las máquinas virtuales.<br />
<br />
{{Warning (Español)|Si conectas el dispositivo de toque y alguna interfaz de host, como {{ic|eth0}}, las máquinas virtuales aparecerán directamente en la red externa, lo que los exponerá a posibles ataques. Dependiendo de los recursos a los que tengan acceso sus máquinas virtuales, es posible que tenga que tomar todas las [[Firewalls|precauciones]] que normalmente tomaría al asegurar una computadora para proteger sus máquinas virtuales. Si el riesgo es demasiado grande, las máquinas virtuales tienen pocos recursos o se configuran varias máquinas virtuales, una solución mejor podría ser utilizar [[#Red de host solamente]] y configurar NAT. En este caso sólo necesitará un firewall en el host en lugar de múltiples firewalls para cada huésped.}}<br />
<br />
Como se indica en la sección de conexión en red de modo de usuario, los dispositivos de derivación ofrecen un rendimiento de red más alto que el modo de usuario. Si el OS invitado admite el controlador de red virtio, el rendimiento de la red se incrementará considerablemente también. Suponiendo el uso del dispositivo tap0, que el controlador virtio se utiliza en el invitado, y que no se utilizan scripts para ayudar a iniciar / detener la creación de redes, a continuación es parte del comando qemu se debe ver:<br />
<br />
-net nic, model=virtio -net tap, ifname=tap0, script=no, downscript=no<br />
<br />
Pero si ya está utilizando un dispositivo de tap con virtio controlador de red, uno puede incluso aumentar el rendimiento de la red mediante la activación de vhost, como:<br />
<br />
-net nic, model=virtio -net tap, ifname=tap0, script=no, downscript=no, vhost=on<br />
<br />
Ver http://www.linux-kvm.com/content/how-maximize-virtio-net-performance-vhost-net para obtener más información.<br />
<br />
==== Red de host solamente ====<br />
<br />
Si al puente se le da una dirección IP y se permite el tráfico destinado a ello, pero no hay una interfaz real (por ejemplo, {{ic|eth0}}) conectada al puente, las máquinas virtuales podrán hablar entre sí y la Sistema anfitrión. Sin embargo, no podrán hablar con nada en la red externa, siempre y cuando no configure IP enmascarada en el host físico. Esta configuración se llama '' red de host solamente '' por otro software de virtualización como [[VirtualBox]].<br />
<br />
{{Tip (Español)|<br />
* Si desea configurar IP masquerading, ej. NAT para máquinas virtuales, consulte la página [[Internet sharing#Enable NAT]].<br />
* Es posible que desee tener un servidor DHCP que se ejecute en la interfaz de puente para dar servicio a la red virtual. Por ejemplo, para usar la subred {{ic|172.20.0.1/16}} con [[dnsmasq]] como servidor DHCP:<br />
# ip addr add 172.20.0.1/16 dev br0<br />
# ip link set br0 up<br />
# dnsmasq --interface&#61;br0 --bind-interfaces --dhcp-range&#61;172.20.0.2,172.20.255.254<br />
}}<br />
<br />
==== Red interna ====<br />
<br />
Si no le da al puente una dirección IP y agrega una regla [[iptables]] para eliminar todo el tráfico al puente en la cadena INPUT, las máquinas virtuales podrán hablar entre sí, pero no con el host físico ó la red exterior. Esta configuración se llama "red interna" por otro software de virtualización como [[VirtualBox]]. Deberá asignar direcciones IP estáticas a las máquinas virtuales o ejecutar un servidor DHCP en una de ellas.<br />
<br />
De forma predeterminada, iptables eliminaría los paquetes de la red de bridge. Es posible que necesite utilizar dicha regla iptables para permitir paquetes en una red puenteada:<br />
<br />
# iptables -I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Redes puenteadas usando qemu-bridge-helper ====<br />
<br />
{{Note (Español)| Este método está disponible desde QEMU 1.1, consulte https://wiki.qemu.org/Features/HelperNetworking.}}<br />
<br />
Este método no requiere una secuencia de comandos de inicio y acepta fácilmente múltiples tomas y puentes múltiples. Utiliza el binario {{ic|/usr/lib/qemu/qemu-bridge-helper}}, que permite crear dispositivos de derivación en un puente existente.<br />
<br />
{{Tip (Español)|Véase [[Network bridge]] para obtener información sobre cómo crear un puente.}}<br />
<br />
En primer lugar, cree un archivo de configuración que contenga los nombres de todos los puentes que QEMU utilizará:<br />
<br />
{{hc|/etc/qemu/bridge.conf|<br />
allow ''bridge0''<br />
allow ''bridge1''<br />
...}}<br />
<br />
Ahora inicie la VM. El uso más básico sería:<br />
<br />
$ qemu-system-i386 -net nic -net bridge,br=''bridge0'' ''[...]''<br />
<br />
Con múltiples taps, el uso más básico requiere especificar la VLAN para todos los NIC adicionales:<br />
<br />
$ qemu-system-i386 -net nic -net bridge,br=''bridge0'' -net nic,vlan=1 -net bridge,vlan=1,br=''bridge1'' ''[...]''<br />
<br />
==== Creación manual del puente ====<br />
<br />
{{Tip (Español)|Desde QEMU 1.1, el [https://wiki.qemu.org/Features/HelperNetworking puente de red ayudante] puede establecer tun / tap up para usted sin necesidad de secuencias de comandos adicionales. Consulte [[#Redes puenteadas usando qemu-bridge-helper]].}}<br />
<br />
A continuación se describe cómo conectar una máquina virtual con una interfaz de host como {{ic | eth0}}, que es probablemente la configuración más común. Esta configuración hace que parezca que la máquina virtual está ubicada directamente en la red externa, en el mismo segmento Ethernet que la máquina host física.<br />
<br />
Vamos a reemplazar el adaptador Ethernet normal con un adaptador de puente y enlazar el adaptador Ethernet normal a él.<br />
<br />
* Instale {{Pkg|bridge-utils}}, que proporciona {{ic|brctl}} para manipular puentes.<br />
<br />
* Habilitar el reenvío IPv4:<br />
<br />
# sysctl net.ipv4.ip_forward=1<br />
<br />
Para hacer el cambio permanente, cambie {{ic|1=net.ipv4.ip_forward = 0}} a {{ic|1=net.ipv4.ip_forward = 1}} en {{ic|/etc/sysctl.d/99-sysctl.conf}}.<br />
<br />
* Cargue el módulo {{ic|tun}} y configurelo para cargarlo en el arranque. Véase [[Kernel modules (Español)]] para más detalles.<br />
<br />
* Ahora cree el puente. Ver [[Bridge with netctl]] para más detalles. Recuerde nombrar su puente como {{ic|br0}}, o modifique lo scripts a continuación del nombre del puente.<br />
<br />
* Cree el script que QEMU utiliza para abrir el adaptador de toma con los permisos {{ic|root:kvm}} 750:<br />
{{hc|/etc/qemu-ifup|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifup"<br />
echo "Bringing up $1 for bridged mode..."<br />
sudo /usr/bin/ip link set $1 up promisc on<br />
echo "Adding $1 to br0..."<br />
sudo /usr/bin/brctl addif br0 $1<br />
sleep 2<br />
</nowiki>}}<br />
<br />
* Cree el guión que QEMU utiliza para derribar el adaptador de toma en {{ic|/etc/qemu-ifdown}} con los permisos {{ic|root:kvm}} 750:<br />
{{hc|/etc/qemu-ifdown|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifdown"<br />
sudo /usr/bin/ip link set $1 down<br />
sudo /usr/bin/brctl delif br0 $1<br />
sudo /usr/bin/ip link delete dev $1<br />
</nowiki>}}<br />
<br />
* Use {{ic|visudo}} para añadir lo siguiente a el archivo {{ic|sudoers}}:<br />
{{bc|<nowiki><br />
Cmnd_Alias QEMU=/usr/bin/ip,/usr/bin/modprobe,/usr/bin/brctl<br />
%kvm ALL=NOPASSWD: QEMU<br />
</nowiki>}}<br />
<br />
* Se inicia QEMU con el siguiente script {{ic|run-qemu}}:<br />
{{hc|run-qemu|<nowiki><br />
#!/bin/bash<br />
USERID=$(whoami)<br />
<br />
# Get name of newly created TAP device; see https://bbs.archlinux.org/viewtopic.php?pid=1285079#p1285079<br />
precreationg=$(/usr/bin/ip tuntap list | /usr/bin/cut -d: -f1 | /usr/bin/sort)<br />
sudo /usr/bin/ip tuntap add user $USERID mode tap<br />
postcreation=$(/usr/bin/ip tuntap list | /usr/bin/cut -d: -f1 | /usr/bin/sort)<br />
IFACE=$(comm -13 <(echo "$precreationg") <(echo "$postcreation"))<br />
<br />
# This line creates a random MAC address. The downside is the DHCP server will assign a different IP address each time<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
# Instead, uncomment and edit this line to set a static MAC address. The benefit is that the DHCP server will assign the same IP address.<br />
# macaddr='52:54:be:36:42:a9'<br />
<br />
qemu-system-i386 -net nic,macaddr=$macaddr -net tap,ifname="$IFACE" $*<br />
<br />
sudo ip link set dev $IFACE down &> /dev/null<br />
sudo ip tuntap del $IFACE mode tap &> /dev/null<br />
</nowiki>}}<br />
<br />
Para ejecutar una VM, haz algo como esto:<br />
<br />
$ run-qemu -hda ''myvm.img'' -m 512 -vga std<br />
<br />
* Se recomienda, por motivos de rendimiento y seguridad, deshabilitar el firewall [http://ebtables.netfilter.org/documentation/bridge-nf.html en el puente]:<br />
{{hc|/etc/sysctl.d/10-disable-firewall-on-bridge.conf|<nowiki><br />
net.bridge.bridge-nf-call-ip6tables = 0<br />
net.bridge.bridge-nf-call-iptables = 0<br />
net.bridge.bridge-nf-call-arptables = 0<br />
</nowiki>}}<br />
Ejecute {{ic|sysctl -p /etc/sysctl.d/10-disable-firewall-on-bridge.conf}} para aplicar los cambios inmediatamente.<br />
<br />
Ver [https://wiki.libvirt.org/page/Networking#Creating_network_initscripts libvirt wiki] y [https://bugzilla.redhat.com/show_bug.cgi?id=512206 Fedora bug 512206]. Si obtiene errores de sysctl durante el inicio de archivos no existentes, haga que el módulo {{ic|bridge}} se cargue al arrancar. Véase [[Kernel module (Español)#systemd]].<br />
<br />
Como alternativa, puede configurar [[iptables]] para permitir que todo el tráfico se reenvíe a través del puente mediante la adición de una regla como esta:<br />
<br />
-I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Compartición de red entre dispositivo físico y un dispositivo de toque a través de iptables ====<br />
<br />
La conexión en puente funciona bien entre una interfaz cableada (por ejemplo, eth0), y es fácil de configurar. Sin embargo, si el host se conecta a la red a través de un dispositivo inalámbrico, el puente no es posible.<br />
<br />
Consulte [[Network bridge#Wireless interface on a bridge]] como referencia.<br />
<br />
Una forma de superar esto es configurar un dispositivo de derivación con una IP estática, haciendo que linux maneje automáticamente el enrutamiento para ella y, a continuación, reenvíe el tráfico entre la interfaz de derivación y el dispositivo conectado a la red a través de las reglas de iptables.<br />
<br />
Consulte [[Internet sharing]] como referencia.<br />
<br />
Allí puede encontrar lo que se necesita para compartir la red entre dispositivos, incluidos los de tap y tun. Lo siguiente sólo indica algunas de las configuraciones de host requeridas. Como se indica en la referencia anterior, el cliente debe configurarse para una IP estática, utilizando la IP asignada a la interfaz de derivación como puerta de enlace. La advertencia es que los servidores DNS del cliente pueden necesitar ser editados manualmente si cambian al cambiar de un dispositivo host conectado a la red a otro.<br />
<br />
Para permitir el reenvío de IP en cada inicio, es necesario agregar las siguientes líneas al archivo de configuración de sysctl dentro de /etc/sysctl.d:<br />
<br />
net.ipv4.ip_forward = 1<br />
net.ipv6.conf.default.forwarding = 1<br />
net.ipv6.conf.all.forwarding = 1<br />
<br />
Las reglas de iptables pueden verse así:<br />
<br />
# Forwarding from/to outside<br />
iptables -A FORWARD -i ${INT} -o ${EXT_0} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_1} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_2} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_0} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_1} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_2} -o ${INT} -j ACCEPT<br />
# NAT/Masquerade (network address translation)<br />
iptables -t nat -A POSTROUTING -o ${EXT_0} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_1} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_2} -j MASQUERADE<br />
<br />
El anterior supone que hay 3 dispositivos conectados a la red compartiendo tráfico con un dispositivo interno, donde por ejemplo:<br />
<br />
INT=tap0<br />
EXT_0=eth0<br />
EXT_1=wlan0<br />
EXT_2=tun0<br />
<br />
El anterior muestra un reenvío que permitiría compartir conexiones cableadas e inalámbricas con el dispositivo de derivación (tap).<br />
<br />
Las reglas de reenvío que se muestran son apátridas y para el reenvío puro. Se podría pensar en restringir el tráfico específico, poniendo un cortafuegos en el lugar para proteger al huésped y otros. Sin embargo, esto reduciría el rendimiento de la red, mientras que un simple puente no incluye nada de eso.<br />
<br />
Bonus: Si la conexión es cableada o inalámbrica, si se conecta a través de VPN a un sitio remoto con un dispositivo tun, suponiendo que el dispositivo tun abierto para esa conexión es tun0, y las reglas iptables anteriores se aplican, entonces la conexión remota se obtiene también Compartido con el huésped. Esto evita la necesidad de que el invitado también abra una conexión VPN. Una vez más, como la red de invitados debe ser estática, entonces si la conexión del host de forma remota de esta manera, uno probablemente tendrá que editar los servidores DNS en el invitado.<br />
<br />
=== Trabajo en red con VDE2 ===<br />
<br />
==== ¿Qué es VDE? ====<br />
<br />
VDE significa Virtual Distributed Ethernet. Comenzó como una mejora del interruptor [[User-mode Linux|uml]] _. Es una caja de herramientas para administrar redes virtuales.<br />
<br />
La idea es crear interruptores virtuales, que son básicamente sockets, y "conectar" tanto máquinas físicas como máquinas virtuales en ellas. La configuración que mostramos aquí es bastante simple; Sin embargo, VDE es mucho más potente que esto, puede conectar conmutadores virtuales juntos, ejecutarlos en diferentes hosts y supervisar el tráfico en los switches. Usted está invitado a leer [https://web.archive.org/web/20190821040940/http://wiki.virtualsquare.org/wiki/index.php/Main_Page la documentación del proyecto].<br />
<br />
La ventaja de este método es que no tienes que agregar privilegios de sudo a tus usuarios. No se debe permitir que los usuarios regulares ejecuten modprobe.<br />
<br />
==== Basics ====<br />
<br />
El soporte de VDE puede ser [[pacman|instalado]] a través del paquete {{Pkg|vde2}} en los [[repositorios oficiales]].<br />
<br />
En nuestra configuración, usamos tun/tap para crear una interfaz virtual en el host. Cargue el módulo {{ic|tun}} (véase [[kernel modules (Español)]] para obtener más detalles):<br />
<br />
# modprobe tun<br />
<br />
Ahora crea el conmutador virtual:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
<br />
Esta línea crea el switch, crea {{ic|tap0}}, lo "enchufa" y permite a los usuarios del grupo {{ic|users}} usarlo.<br />
<br />
La interfaz está conectada pero no está configurada todavía. Para configurarlo, ejecute este comando:<br />
<br />
# ip addr add 192.168.100.254/24 dev tap0<br />
<br />
Ahora, sólo tiene que ejecutar KVM con estas opciones {{ic|-net}} como usuario normal:<br />
<br />
$ qemu-system-i386 -net nic -net vde -hda ''[...]''<br />
<br />
Configure la red para su invitado como lo haría en una red física.<br />
<br />
{{Tip (Español)|Es posible que desee configurar NAT en dispositivo de toque para acceder a Internet desde la máquina virtual. Consulte [[Internet sharing#Enable NAT]] para obtener más información.}}<br />
<br />
==== Startup scripts ====<br />
<br />
Ejemplo de script principal que inicia VDE:<br />
<br />
{{hc|/etc/systemd/scripts/qemu-network-env|<nowiki><br />
#!/bin/sh<br />
# Preparación del entorno de red QEMU/VDE<br />
<br />
# La configuración IP del dispositivo de derivación que se utilizará para<br />
# La red de la máquina virtual:<br />
<br />
TAP_DEV=tap0<br />
TAP_IP=192.168.100.254<br />
TAP_MASK=24<br />
TAP_NETWORK=192.168.100.0<br />
<br />
# Host interface<br />
NIC=eth0<br />
<br />
case "$1" in<br />
start)<br />
echo -n "Starting VDE network for QEMU: "<br />
<br />
# If you want tun kernel module to be loaded by script uncomment here<br />
#modprobe tun 2>/dev/null<br />
## Wait for the module to be loaded<br />
#while ! lsmod | grep -q "^tun"; do echo "Waiting for tun device"; sleep 1; done<br />
<br />
# Start tap switch<br />
vde_switch -tap "$TAP_DEV" -daemon -mod 660 -group users<br />
<br />
# Bring tap interface up<br />
ip address add "$TAP_IP"/"$TAP_MASK" dev "$TAP_DEV"<br />
ip link set "$TAP_DEV" up<br />
<br />
# Start IP Forwarding<br />
echo "1" > /proc/sys/net/ipv4/ip_forward<br />
iptables -t nat -A POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
;;<br />
stop)<br />
echo -n "Stopping VDE network for QEMU: "<br />
# Delete the NAT rules<br />
iptables -t nat -D POSTROUTING "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
<br />
# Bring tap interface down<br />
ip link set "$TAP_DEV" down<br />
<br />
# Kill VDE switch<br />
pgrep -f vde_switch | xargs kill -TERM<br />
;;<br />
restart|reload)<br />
$0 stop<br />
sleep 1<br />
$0 start<br />
;;<br />
*)<br />
echo "Usage: $0 {start|stop|restart|reload}"<br />
exit 1<br />
esac<br />
exit 0<br />
</nowiki>}}<br />
<br />
Ejemplo de servicio systemd utilizando el script anterior:<br />
<br />
{{hc|/etc/systemd/system/qemu-network-env.service|<nowiki><br />
[Unit]<br />
Description=Manage VDE Switch<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/etc/systemd/scripts/qemu-network-env start<br />
ExecStop=/etc/systemd/scripts/qemu-network-env stop<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
Cambiar permisos de {{ic|qemu-network-env}} para ser ejecutable<br />
<br />
# chmod u+x /etc/systemd/scripts/qemu-network-env<br />
<br />
Puede iniciar {{ic|qemu-network-env.service}} como de costumbre.<br />
<br />
==== Método alternativo ====<br />
<br />
Si el método anterior no funciona o no quiere meterse con las configuraciones del kernel, TUN, dnsmasq e iptables, puede hacer lo siguiente para obtener el mismo resultado.<br />
<br />
# vde_switch -daemon -mod 660 -group users<br />
# slirpvde --dhcp --daemon<br />
<br />
A continuación, para iniciar la VM con una conexión a la red del host:<br />
<br />
$ qemu-system-i386 -net nic,macaddr=52:54:00:00:EE:03 -net vde ''disk_image''<br />
<br />
=== Puente VDE2 ===<br />
<br />
Basado en [https://selamatpagicikgu.wordpress.com/2011/06/08/quickhowto-qemu-networking-using-vde-tuntap-and-bridge/ quickhowto: qemu networking using vde, tun/tap, and bridge] gráfico. Cualquier máquina virtual conectada a vde está expuesta externamente. Por ejemplo, cada máquina virtual puede recibir la configuración DHCP directamente desde su enrutador ADSL.<br />
<br />
==== Conceptos básicos ====<br />
<br />
Recuerde que necesita el módulo {{ic|tun}} y el paquete {{Pkg|bridge-utils}}.<br />
<br />
Cree el dispositivo vde2/tap:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
# ip link set tap0 up<br />
<br />
Cree el puente:<br />
<br />
# brctl addbr br0<br />
<br />
Agregue dispositivos:<br />
<br />
# brctl addif br0 eth0<br />
# brctl addif br0 tap0<br />
<br />
Y configure la interfaz del puente:<br />
<br />
# dhcpcd br0<br />
<br />
==== Startup scripts ====<br />
<br />
Todos los dispositivos deben estar configurados. Y sólo el puente necesita una dirección IP. Para dispositivos físicos en el puente (por ejemplo, {{ic|eth0}}), esto puede hacerse con [[netctl]] utilizando un perfil Ethernet personalizado con:<br />
<br />
{{hc|/etc/netctl/ethernet-noip|<nowiki><br />
Description='A more versatile static Ethernet connection'<br />
Interface=eth0<br />
Connection=ethernet<br />
IP=no<br />
</nowiki>}}<br />
<br />
El siguiente servicio systemd personalizado puede utilizarse para crear y activar una interfaz de toma VDE2 para su uso en el grupo de usuarios {{ic|users}}.<br />
<br />
{{hc|/etc/systemd/system/vde2@.service|<nowiki><br />
[Unit]<br />
Description=Network Connectivity for %i<br />
Wants=network.target<br />
Before=network.target<br />
<br />
[Service]<br />
Type=oneshot<br />
RemainAfterExit=yes<br />
ExecStart=/usr/bin/vde_switch -tap %i -daemon -mod 660 -group users<br />
ExecStart=/usr/bin/ip link set dev %i up<br />
ExecStop=/usr/bin/ip addr flush dev %i<br />
ExecStop=/usr/bin/ip link set dev %i down<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
Y, por último, puede crear el puente interfaz con netctl.<br />
<br />
== Gráficos ==<br />
<br />
QEMU puede utilizar las siguientes salidas gráficas diferentes: {{ic|std}}, {{ic|qxl}}, {{ic|vmware}}, {{ic|virtio}}, {{ic|cirrus}} y {{ic|none}}.<br />
<br />
=== std ===<br />
<br />
Con {{ic|-vga std}} puede obtener una resolución de hasta 2560 x 1600 píxeles sin necesidad de controladores invitados. Este es el valor predeterminado desde QEMU 2.2.<br />
<br />
=== qxl ===<br />
<br />
QXL Es un controlador de gráficos paravirtual con soporte 2D. Para usarlo, pase la opción {{ic|-vga qxl}} e instale los controladores en el invitado. Es posible que desee utilizar SPICE para mejorar el rendimiento gráfico al utilizar QXL.<br />
<br />
En los invitados de Linux, los módulos del kernel {{ic|qxl}} y {{ic|bochs_drm}} deben ser inicializados para poder tener un rendimiento decente.<br />
<br />
==== SPICE ====<br />
<br />
El proyecto [https://www.spice-space.org/ SPICE] tiene como objetivo proporcionar una solución completa de código abierto para el acceso remoto a máquinas virtuales de una manera transparente.<br />
<br />
SPICE sólo se puede utilizar cuando se utiliza QXL como la salida gráfica.<br />
<br />
El siguiente es un ejemplo de arranque con SPICE como protocolo de escritorio remoto:<br />
<br />
$ qemu-system-i386 -vga qxl -spice port=5930,disable-ticketing -chardev spicevm <br />
<br />
Conéctese al invitado utilizando un cliente SPICE. En este momento se recomienda {{Pkg|spice-gtk}}, sin embargo otros [https://www.spice-space.org/download.html clientes], incluyendo otras plataformas, están disponibles:<br />
<br />
$ spicy -h 127.0.0.1 -p 5930<br />
<br />
El uso de [[wikipedia:Unix_socket|Unix sockets]] en lugar de los puertos TCP no implica el uso de pila de red en el sistema host, por lo que es [https://unix.stackexchange.com/questions/91774/performance-of-unix- Sockets-vs-tcp-ports según se informa] mejor para el rendimiento. Ejemplo:<br />
$ qemu-system-x86_64 -vga qxl -device virtio-serial-pci -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent -spice unix,addr=/tmp/vm_spice.socket,disable-ticketing<br />
$ spicy --uri="spice+unix:///tmp/vm_spice.socket"<br />
<br />
Para una mejor compatibilidad con varios monitores, compartir el portapapeles, etc., los paquetes siguientes deben estar instalados en el invitado:<br />
* {{Pkg|spice-vdagent}}: Spice agent xorg cliente que permite copiar y pegar entre el cliente y X-session y más<br />
* {{Pkg|xf86-video-qxl}} {{AUR|xf86-video-qxl-git}}: Xorg X11 qxl controlador de vídeo<br />
* Para otros sistemas operativos, mire la sección Guest de la página [https://www.spice-space.org/download.html SPICE-Space download].<br />
<br />
=== vmware ===<br />
<br />
Aunque tiene pocos errores, tiene mejor rendimiento que std y cirrus. Instale los controladores de VMware {{Pkg|xf86-video-vmware}} y {{Pkg|xf86-input-vmmouse}} para los invitados de Arch Linux.<br />
<br />
=== virtio ===<br />
<br />
{{ic|virtio-vga}} / {{ic|virtio-gpu}} Es un controlador de gráficos 3D paravirtual basado en [https://virgil3d.github.io/ virgl]. Actualmente un trabajo en curso, que sólo admite a invitados Linux (>= 4.4) con {{Pkg|mesa}} (>= 11.2) compilados con la opción {{ic|1=--with-gallium-drivers=virgl}}.<br />
<br />
Para activar la aceleración 3D en el sistema invitado, seleccione vga con {{ic|-vga virtio}} y habilitar el contexto opengl en el dispositivo de visualización con {{ic|1=-display sdl,gl=on}} ó {{ic|1=-display gtk,gl=on}} Para la salida de pantalla sdl y gtk respectivamente. La configuración correcta se puede confirmar mirando el registro del kernel en el invitado:<br />
<br />
{{hc|# dmesg {{!}} grep drm |<br />
[drm] pci: virtio-vga detected<br />
[drm] virgl 3d acceleration enabled<br />
}}<br />
<br />
A partir de septiembre de 2016, el soporte para el protocolo de especias está en desarrollo y se puede probar la instalación de la versión de desarrollo de {{Pkg|spice}} (>= 0.13.2) y la recompilación de qemu.<br />
<br />
Para más información visite [https://web.archive.org/web/20171216170334/https://www.kraxel.org/blog/tag/virgl/ blog de kraxel].<br />
<br />
=== cirrus ===<br />
<br />
El adaptador gráfico cirrus fue el predeterminado [https://wiki.qemu.org/ChangeLog/2.2#VGA before 2.2]. [Https://www.kraxel.org/blog/2014/10/qemu-using-cirrus-considered-harmful/ no debería] utilizarse en sistemas modernos.<br />
<br />
=== none ===<br />
<br />
Esto es como un PC que no tiene tarjeta VGA en absoluto. Ni siquiera podrías acceder a ella con la opción {{ic|-vnc}}. Además, esto es diferente de la opción {{ic|-nographic}} que permite a QEMU emular una tarjeta VGA, pero deshabilita la visualización SDL.<br />
<br />
=== vnc ===<br />
<br />
Dado que usó la opción {{ic|-nographic}}, puede agregar la opción {{ic|-vnc display}} para que QEMU escuche en {{ic|display}} y redirigir la pantalla VGA a la sesión VNC . Hay un ejemplo de esto en las configuraciones de ejemplo de la sección [[#Inicio de las máquinas virtuales QEMU en el arranque]].<br />
<br />
$ qemu-system-i386 -vga std -nographic -vnc :0<br />
$ gvncviewer :0<br />
<br />
Al usar VNC, puede experimentar problemas de teclado descritos (en detalles gory) [https://www.berrange.com/posts/2010/07/04/more-than-you-or-i-ever-wanted-to-know-about-virtual-keyboard-handling/ aquí]. La solución es "no" usar la opción {{ic|-k}} en QEMU y usar {{ic|gvncviewer}} de {{Pkg|gtk-vnc}}. Ver también [https://www.mail-archive.com/libvir-list@redhat.com/msg13340.html este] mensaje publicado en la lista de correo de libvirt.<br />
<br />
== Audio ==<br />
<br />
=== Host ===<br />
<br />
El controlador de audio utilizado por QEMU se establece con la variable de entorno {{ic|QEMU_AUDIO_DRV}}:<br />
<br />
$ export QEMU_AUDIO_DRV=pa<br />
<br />
Ejecute el siguiente comando para obtener las opciones de configuración de QEMU relacionadas con PulseAudio:<br />
<br />
$ qemu-system-x86_64 -audio-help | awk '/Name: pa/' RS=<br />
<br />
Las opciones listadas se pueden exportar como variables de entorno, por ejemplo:<br />
<br />
{{bc|1=<br />
$ export QEMU_PA_SINK=alsa_output.pci-0000_04_01.0.analog-stereo.monitor<br />
$ export QEMU_PA_SOURCE=input<br />
}}<br />
<br />
=== Invitado ===<br />
<br />
Para obtener la lista de los controladores de audio de emulación compatibles:<br />
<br />
$ qemu-system-x86_64 -soundhw help<br />
<br />
Para usar (ej. {{ic|hda}}) para el invitado utilice el comando {{ic|-soundhw hda}} con QEMU.<br />
<br />
{{Note (Español)| Los controladores emulados con tarjeta gráfica de vídeo para la máquina invitada también pueden causar un problema con la calidad del sonido. Pruebe uno por uno para que funcione. Puede listar las opciones posibles con {{ic|qemu-system-x86_64 -h | grep vga}}.}}<br />
<br />
=== VirtIO sound ===<br />
<br />
VirtIO sound está disponible desde la versión 8.2.0 de QEMU. El uso es:<br />
<br />
-device virtio-sound-pci,audiodev=my_audiodev -audiodev alsa,id=my_audiodev<br />
<br />
Para más información, consulte la [https://qemu-project.gitlab.io/qemu/system/devices/virtio-snd.html documentación de QEMU].<br />
<br />
== Instalación de controladores virtio ==<br />
<br />
QEMU ofrece a los clientes la posibilidad de utilizar dispositivos bloqueados y de red paravirtualizados utilizando los controladores [https://wiki.libvirt.org/page/Virtio virtio], que proporcionan un mejor rendimiento y menores gastos generales.<br />
<br />
Un dispositivo virtio bloque requiere la opción {{ic|-drive}} en lugar del simple {{ic|-hd *}} más {{ic|1=if=virtio}}:<br />
<br />
$ qemu-system-i386 -boot order=c -drive file=''disk_image'',if=virtio<br />
<br />
{{Note (Español)|{{Ic|1=-boot order=c}} es absolutamente necesario cuando se desea arrancar desde él. No hay detección automática como con {{Ic|-hd*}}.}}<br />
<br />
* Casi de la misma manera para la red:<br />
<br />
$ qemu-system-i386 -net nic,model=virtio<br />
<br />
{{Note (Español)| Esto sólo funcionará si la máquina invitada tiene controladores para dispositivos virtio. Linux lo hace, y los controladores necesarios están incluidos en Arch Linux, pero no hay garantía de que los dispositivos virtio funcionen con otros sistemas operativos.}}<br />
<br />
=== Preparando a Arch Linux como invitado ===<br />
<br />
Para utilizar los dispositivos virtio después de instalar un invitado de Arch Linux, se deben cargar en el invitado los siguientes módulos: {{Ic|virtio}}, {{Ic|virtio_pci}}, {{Ic|virtio_blk}}, {{Ic|Virtio_net}}, y {{Ic|virtio_ring}}. Para los huéspedes de 32 bits, no es necesario el módulo "virtio" específico.<br />
<br />
Si desea arrancar desde un disco virtio, el disco ramd inicial debe contener los módulos necesarios. De forma predeterminada, esto es manejado por el gancho {{ic|autodetect}} de [[mkinitcpio]]. De lo contrario, utilice la matriz {{ic|MODULES}} en {{ic|/etc/mkinitcpio.conf}} para incluir los módulos necesarios y reconstruir el disco ramd inicial.<br />
<br />
{{hc|/etc/mkinitcpio.conf|2=<br />
MODULES="virtio virtio_blk virtio_pci virtio_net"}}<br />
<br />
Los discos Virtio se reconocen con el prefijo {{ic|'''v'''}} (ej. {{ic|'''v''' da}}, {{ic|'''v''' db}}, etc.); Por lo tanto, los cambios deben realizarse al menos en {{ic|/etc/fstab}} y {{ic|/boot/grub/grub.cfg}} al arrancar desde un disco virtio.<br />
<br />
{{Note (Español)|Cuando se hace referencia a discos por [[UUID]] en {{ic|/etc/fstab}} y bootloader, no hay nada que hacer.}}<br />
<br />
Se puede encontrar más información sobre la paravirtualización con KVM [https://www.linux-kvm.org/page/Boot_from_virtio_block_device aquí].<br />
<br />
También puede instalar {{Pkg|qemu-guest-agent}} para implementar la compatibilidad con los comandos QMP que mejorarán las capacidades de administración del hipervisor. Después de instalar el paquete, puedes habilitar e iniciar el {{ic|qemu-ga.service}}.<br />
<br />
=== Preparar un invitado de Windows ===<br />
<br />
{{Note (Español)|1=La única forma (fiable) de actualizar un cliente de Windows 8.1 a Windows 10 parece que es elegir temporalmente cpu core2duo, nx para la instalación [https://ubuntuforums.org/showthread.php?t=2289210]. Después de la instalación, puede volver a otros ajustes de la CPU (8/8/2015).}}<br />
<br />
==== Bloquear controladores de dispositivo ====<br />
<br />
===== Nueva instalación de Windows =====<br />
<br />
Windows no viene con los controladores virtio. Por lo tanto, tendrá que cargarlos durante la instalación. Hay básicamente dos maneras de hacer esto: vía disco blando o vía archivos de ISO. Ambas imágenes se pueden descargar desde el repositorio [https://fedoraproject.org/wiki/Windows_Virtio_Drivers Fedora].<br />
<br />
La opción del disquete es difícil porque necesitará presionar F6 (Shift-F6 en Windows más reciente) al inicio de la alimentación del QEMU. Esto es difícil ya que necesitas tiempo para conectar tu ventana de consola VNC. Puede intentar agregar un retardo a la secuencia de arranque. Consulte {{ic|man qemu-system}} para obtener más detalles sobre la aplicación de un retardo en el arranque.<br />
<br />
La opción ISO para cargar los controladores es la forma preferida, pero está disponible sólo en Windows Vista y Windows Server 2008 y versiones posteriores. El procedimiento consiste en cargar la imagen con controladores virtio en un dispositivo de cdrom adicional junto con el dispositivo de disco principal y el instalador de Windows:<br />
<br />
$ qemu-system-i386 ... \<br />
-drive file=''/path/to/primary/disk.img'',index=0,media=disk,if=virtio \<br />
-drive file=''/path/to/installer.iso'',index=2,media=cdrom \<br />
-drive file=''/path/to/virtio.iso'',index=3,media=cdrom \<br />
...<br />
<br />
Durante la instalación, el instalador de Windows le pedirá su clave de producto y realizará algunas comprobaciones adicionales. Cuando llegue a la "¿Dónde desea instalar Windows?" Pantalla, dará una advertencia de que no se encuentran discos. Siga las instrucciones de ejemplo siguientes (basadas en Windows Server 2012 R2 con Actualización).<br />
<br />
* Seleccione la opción {{ic|Load Drivers}}.<br />
* Desactive la casilla de "Ocultar los controladores que no son compatibles con el hardware de este equipo".<br />
* Haga clic en el botón Examinar y abra el CDROM para la virtio iso, normalmente llamada "virtio-win-XX".<br />
* Ahora vaya a {{ic|E:\viostor\[your-os]\amd64}}, seleccione y pulse OK.<br />
* Click Next<br />
<br />
Ahora debería ver sus discos virtio listados aquí, listos para ser seleccionados, formateados e instalados.<br />
<br />
===== Cambiar la máquina virtual existente de Windows para utilizar virtio =====<br />
<br />
Modificar un invitado de Windows existente para arrancar desde disco virtio es un poco difícil.<br />
<br />
Puede descargar el controlador de disco virtio desde el [https://fedoraproject.org/wiki/Windows_Virtio_Drivers repositorio de Fedora].<br />
<br />
Ahora necesita crear una nueva imagen de disco, que llene la fuerza de Windows para buscar el controlador. Por ejemplo:<br />
<br />
$ qemu-img create -f qcow2 ''fake.qcow2'' 1G<br />
<br />
Ejecute el invitado original de Windows (con el disco de inicio todavía en modo IDE) con el disco falso (en modo virtio) y un CD-ROM con el controlador.<br />
<br />
$ qemu-system-i386 -m 512 -vga std -drive file=''windows_disk_image'',if=ide -drive file=''fake.qcow2'',if=virtio -cdrom virtio-win-0.1-81.iso<br />
<br />
Windows detectará el disco falso y tratará de encontrar un controlador para ello. Si falla, vaya al '' Administrador de dispositivos '', busque la unidad SCSI con un icono de signo de exclamación (debe estar abierto), haga clic en '' Actualizar controlador '' y seleccione el CD-ROM virtual. No olvide seleccionar la casilla de verificación que dice que debe buscar directorios recursivamente.<br />
<br />
Cuando la instalación se realiza correctamente, puede apagar la máquina virtual y volver a iniciarla, ahora con el disco de arranque conectado en modo virtio:<br />
<br />
$ qemu-system-i386 -m 512 -vga std -drive file=''windows_disk_image'',if=virtio<br />
<br />
{{Note (Español)|Si encuentra la pantalla azul de Death, asegúrese de no olvidar el parámetro {{ic|-m}} y de que no arranca con virtio en lugar de ide para la unidad del sistema antes de instalar los controladores.}}<br />
<br />
==== Controladores de red ====<br />
<br />
La instalación de los controladores de red virtio es un poco más fácil, simplemente agregue el argumento {{ic|-net}} como se explicó anteriormente.<br />
<br />
$ qemu-system-i386 -m 512 -vga std -drive file=''windows_disk_image'',if=virtio -net nic,model=virtio -cdrom virtio-win-0.1-74.iso<br />
<br />
Windows detectará el adaptador de red y tratará de encontrar un controlador para ello. Si falla, vaya al ''Administrador de dispositivos'', localice el adaptador de red con un icono de signo de exclamación (debe estar abierto), haga clic en ''Actualizar controlador'' y seleccione el CD-ROM virtual. No olvide seleccionar la casilla de verificación que dice que debe buscar directorios recursivamente.<br />
<br />
=== Preparación de FreeBSD como invitado ===<br />
<br />
Instale el puerto {{ic|emulators/virtio-kmod}} si está utilizando FreeBSD 8.3 o posterior hasta 10.0-CURRENT donde están incluidos en el kernel. Después de la instalación, añada lo siguiente a su archivo {{ic|/boot/loader.conf}}:<br />
<br />
{{bc|<nowiki><br />
virtio_loader="YES"<br />
virtio_pci_load="YES"<br />
virtio_blk_load="YES"<br />
if_vtnet_load="YES"<br />
virtio_balloon_load="YES"<br />
</nowiki>}}<br />
<br />
A continuación, modifique su {{ic|/etc/fstab}} haciendo lo siguiente:<br />
<br />
{{bc|<nowiki><br />
sed -i bak "s/ada/vtbd/g" /etc/fstab<br />
</nowiki>}}<br />
<br />
Y verificar que {{ic|/etc/fstab}} es consistente. Si algo sale mal, sólo arranque en un CD de rescate y copie {{ic|/etc/fstab.bak}} de vuelta a {{ic|/etc/fstab}}.<br />
<br />
== Consejos y trucos ==<br />
<br />
=== Inicio de las máquinas virtuales QEMU en el arranque ===<br />
<br />
==== Con libvirt ====<br />
<br />
Si se configura una máquina virtual con [[libvirt]], se puede configurar a través de la interfaz gráfica de usuario de virt-manager para iniciar en el arranque de host, accediendo a las Opciones de arranque de la máquina virtual y seleccionando "Inicio de la máquina virtual en el arranque del host".<br />
<br />
==== Script personalizado ====<br />
<br />
Para ejecutar QEMU VMs al arrancar, puede usar las siguientes unidades systemd y config.<br />
<br />
{{hc|/etc/systemd/system/qemu@.service|<nowiki><br />
[Unit]<br />
Description=QEMU virtual machine<br />
<br />
[Service]<br />
Environment="type=system-x86_64" "haltcmd=kill -INT $MAINPID"<br />
EnvironmentFile=/etc/conf.d/qemu.d/%i<br />
ExecStart=/usr/bin/env qemu-${type} -name %i -nographic $args<br />
ExecStop=/bin/sh -c ${haltcmd}<br />
TimeoutStopSec=30<br />
KillMode=none<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
{{Note (Español)|De acuerdo con {{ic|systemd.service (5)}} y {{ic|systemd.kill (5)}} man, es necesario utilizar {{ic|1=KillMode=none}} opción. De lo contrario, el proceso qemu principal se eliminará inmediatamente después de que se cierre el comando {{ic|ExecStop}} (simplemente hace eco de una cadena) y su sistema de búsqueda no podrá apagarse correctamente.}}<br />
<br />
A continuación, cree archivos de configuración por-VM, denominados {{ic|/etc/conf.d/qemu.d/''vm_name''}}, con las siguientes variables establecidas:<br />
<br />
; type<br />
: QEMU binary to call. If specified, will be prepended with {{ic|/usr/bin/qemu-}} and that binary will be used to start the VM. I.e. you can boot e.g. {{ic|qemu-system-arm}} images with {{ic|1=type="system-arm"}}.<br />
; args<br />
: QEMU command line to start with. Will always be prepended with {{ic|-name ${vm} -nographic}}.<br />
; haltcmd<br />
: Command to shut down a VM safely. I am using {{ic|-monitor telnet:..}} and power off my VMs via ACPI by sending {{ic|system_powerdown}} to monitor. You can use SSH or some other ways.<br />
<br />
Ejemplo de configuración:<br />
<br />
{{hc|/etc/conf.d/qemu.d/one|<nowiki><br />
type="system-x86_64"<br />
<br />
args="-enable-kvm -m 512 -hda /dev/mapper/vg0-vm1 -net nic,macaddr=DE:AD:BE:EF:E0:00 \<br />
-net tap,ifname=tap0 -serial telnet:localhost:7000,server,nowait,nodelay \<br />
-monitor telnet:localhost:7100,server,nowait,nodelay -vnc :0"<br />
<br />
haltcmd="echo 'system_powerdown' | nc localhost 7100" # or netcat/ncat<br />
<br />
# You can use other ways to shut down your VM correctly<br />
#haltcmd="ssh powermanager@vm1 sudo poweroff"<br />
</nowiki>}}<br />
<br />
{{hc|/etc/conf.d/qemu.d/two|<nowiki><br />
args="-enable-kvm -m 512 -hda /srv/kvm/vm2.img -net nic,macaddr=DE:AD:BE:EF:E0:01 \<br />
-net tap,ifname=tap1 -serial telnet:localhost:7001,server,nowait,nodelay \<br />
-monitor telnet:localhost:7101,server,nowait,nodelay -vnc :1"<br />
<br />
haltcmd="echo 'system_powerdown' | nc localhost 7101"<br />
</nowiki>}}<br />
<br />
Para establecer qué máquinas virtuales se iniciarán al arrancar, habilite la unidad de [[systemd]] {{ic|qemu@''vm_name''.service}}.<br />
<br />
=== Integración del ratón ===<br />
<br />
Para evitar que el ratón sea agarrado al hacer clic en la ventana del sistema operativo invitado, agregue la opción {{ic|-usbdevice tablet}}. Esto significa que QEMU puede reportar la posición del ratón sin tener que agarrar el ratón. Esto también anula la emulación de ratón PS/2 cuando se activa. Por ejemplo:<br />
<br />
$ qemu-system-i386 -hda ''disk_image'' -m 512 -vga std -usbdevice tablet<br />
<br />
If that does not work, try the tip at [[#El cursor del ratón está nervioso o errático]].<br />
<br />
=== Dispositivo USB del host de paso ===<br />
<br />
Para acceder al dispositivo físico USB conectado al host desde la VM, puede utilizar la opción: {{ic|-usbdevice host:''vendor_id'':''product_id''}}.<br />
<br />
Puedes encontrar {{ic|vendor_id}} y {{ic|product_id}} de tu dispositivo con el comando {{ic|lsusb}}.<br />
<br />
Puesto que el chipset I440FX por defecto emulado por qemu cuentan con un solo controlador UHCI (USB 1), la opción {{ic|-usbdevice}} intentará conectar su dispositivo físico a él. En algunos casos esto puede causar problemas con los dispositivos más nuevos. Una posible solución es emular el chipset [https://wiki.qemu.org/Features/Q35 ICH9], que ofrece un controlador EHCI que soporta hasta 12 dispositivos, usando la opción {{ic|1=-machine type=q35}}.<br />
<br />
Una solución menos invasiva es emular un controlador EHCI (USB 2) o XHCI (USB 3) con la opción {{ic | 1 = -device usb-ehci, id = ehci}} o {{ic|1=-device nec -usb-xhci, id=xhci}} respectivamente y luego adjuntar su dispositivo físico con la opción {{ic|1=-device usb-host,..}} como sigue:<br />
<br />
-device usb-host,bus='''controller_id'''.0,vendorid=0x'''vendor_id''',productid=0x'''product_id'''<br />
<br />
También puede agregar la configuración {{ic|1=..., port =''<n>''}} a la opción anterior para especificar en qué puerto físico del controlador virtual que desea conectar su dispositivo, útil en El caso que desea agregar varios dispositivos usb a la VM.<br />
<br />
{{Note (Español)|Si encuentra errores de permisos al ejecutar QEMU, consulte [[udev#About udev rules]] para obtener información sobre cómo establecer permisos del dispositivo.}}<br />
<br />
=== Habilitar KSM ===<br />
<br />
Kernel Samepage Merging (KSM) es una característica del kernel de Linux que permite que una aplicación se registre con el kernel para que sus páginas se combinen con otros procesos que también se registren para que sus páginas se fusionen. El mecanismo KSM permite a las máquinas virtuales invitadas compartir páginas entre sí. En un entorno donde muchos de los sistemas operativos invitados son similares, esto puede resultar en ahorros significativos de memoria.<br />
<br />
Para activar KSM, simplemente ejecute:<br />
<br />
# echo 1 > /sys/kernel/mm/ksm/run<br />
<br />
Para hacerlo permanente, puede utilizar [[Systemd#systemd-tmpfiles - temporary files|archivos temporales de systemd]]:<br />
<br />
{{hc|/etc/tmpfiles.d/ksm.conf|<br />
w /sys/kernel/mm/ksm/run - - - - 1<br />
}}<br />
<br />
Si KSM está en ejecución y hay páginas que se van a fusionar (es decir, al menos dos máquinas virtuales similares se están ejecutando), entonces {{ic|/sys/kernel/mm/ksm/pages_shared}} debería ser distinto de cero. Consulte https://docs.kernel.org/vm/ksm.html{{Dead link (Español)|2022|09|22|status=404}} para obtener más información.<br />
<br />
{{Tip (Español)|Una manera fácil de ver lo bien que KSM está realizando es simplemente imprimir el contenido de todos los archivos de ese directorio: {{bc|$ grep./Sys/kernel/mm/ksm/*}}}}<br />
<br />
=== Multi-monitor support ===<br />
<br />
El controlador QXL de Linux soporta cuatro cabezas (pantallas virtuales) de forma predeterminada. Esto se puede cambiar a través del parámetro kernel {{ic | 1 = qxl.heads = N}}.<br />
<br />
El tamaño de memoria VGA predeterminado para los dispositivos QXL es de 16M (el tamaño de la VRAM es de 64M). Esto no es suficiente si desea habilitar dos monitores 1920x1200 ya que requiere 2 × 1920 × 4 (profundidad de color) × 1200 = 17.6 MiB memoria VGA. Esto se puede cambiar reemplazando {{ic|-vga qxl}} por {{ic|1=-vga none -device qxl-vga, vgamem_mb=32}}. Si alguna vez incrementas vgamem_mb más allá de 64M, también debes aumentar la opción {{ic|vram_size_mb}}.<br />
<br />
=== Copiar y pegar ===<br />
<br />
Para poder copiar y pegar entre el host y el invitado, debe habilitar el canal de comunicación del agente de especias. Requiere agregar un dispositivo virtio-serial al huésped, y abrir un puerto para el vdagent de la especia. También es necesario instalar el spice vdagent en invitado ({{Pkg|spice-vdagent}} para invitados de Arch, [https://www.spice-space.org/download.html Herramientas para invitados de Windows] para invitados de Windows). Asegúrese de que el agente se está ejecutando (y para el futuro, se iniciará automáticamente).<br />
<br />
Inicie QEMU con las siguientes opciones:<br />
<br />
$ qemu-system-i386 -vga qxl -spice port=5930,disable-ticketing -device virtio-serial-pci -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
La opción {{ic|-device virtio-serial-pci}} añade el dispositivo virtio-serial, {{ic|1=-device virtserialport, chardev=spicechannel0, nombre=com.redhat.spice.0}} abre un puerto Para spice vdagent en ese dispositivo y {{ic|1=-chardev spicevmc, id=spicechannel0, nombre=vdagent}} añade un spicevmc chardev para ese puerto.<br />
<br />
Es importante que la opción {{ic|1=chardev=}} del dispositivo {{ic|virtserialport}} coincida con la opción {{ic|1=id=}} dada a la opción {{ic | chardev}} ({{Ic|spicechannel0}} en este ejemplo). También es importante que el nombre del puerto sea {{ic|com.redhat.spice.0}}, ya que es el espacio de nombres donde vdagent está buscando en el invitado. Y finalmente, especifique {{ic|1=name=vdagent}} para que spice sepa para qué sirve este canal.<br />
<br />
=== Notas específicas de Windows ===<br />
<br />
QEMU puede ejecutar cualquier versión de Windows desde Windows 95 a través de Windows 10.<br />
<br />
Es posible ejecutar [[Windows PE]] en QEMU.<br />
<br />
==== Inicio rápido ====<br />
<br />
{{Note (Español)|Se requiere una cuenta de administrador para cambiar la configuración de energía.}}<br />
Para invitados de Windows 8 (o posteriores), es mejor desactivar "Activar inicio rápido (recomendado)" en Opciones de energía del Panel de control, ya que hace que el invitado se bloquee durante cada arranque.<br />
<br />
El inicio rápido también puede necesitar deshabilitarse para que los cambios en la opción {{ic|-smp}} se apliquen correctamente.<br />
<br />
==== Protocolo de escritorio remoto ====<br />
<br />
Si utiliza un invitado de MS Windows, puede utilizar RDP para conectarse a su VM invitada. Si está utilizando una VLAN o no está en la misma red que el invitado, utilice:<br />
<br />
$ qemu-system-i386 -nographic -net user,hostfwd=tcp::5555-:3389<br />
<br />
A continuación, conéctese con {{Pkg|rdesktop}} ó {{Pkg|freerdp}} al invitado. Por ejemplo:<br />
<br />
$ xfreerdp -g 2048x1152 localhost:5555 -z -x lan<br />
<br />
== Solución de problemas ==<br />
<br />
=== La máquina virtual virtual corre muy lento ===<br />
<br />
Hay algunas técnicas que se pueden usar para implementar rendimiento en la máquina virtual, por ejemplo:<br />
<br />
* Use la opción {{ic|-cpu host}} para hacer que QEMU emule la CPU del host. Si no se hace esto, podría intentar emular un CPU más genérico.<br />
* Especialmente para los invitados de Windows, habilite [https://blog.wikichoon.com/2014/07/enabling-hyper-v-enlightenments-with-kvm.html Iluminaciones de Hyper-V]: {{ic|1=-Host de la CPU, hv_relaxed, hv_spinlocks=0x1fff, hv_vapic, hv_time}}.<br />
* Si la máquina host tiene varias CPUs, asigne al invitado más CPUs usando la opción {{ic|-smp}}.<br />
* Asegúrese de haber asignado a la máquina virtual suficiente memoria. De forma predeterminada, QEMU sólo asigna 128 MiB de memoria a cada máquina virtual. Utilice la opción {{ic|-m}} para asignar más memoria. Por ejemplo, {{ic|-m 1024}} ejecuta una máquina virtual con 1024 MiB de memoria.<br />
* Utilice KVM si es posible: agregue {{ic|1=-machine type=pc, accel=kvm}} al comando de arranque QEMU que utilice.<br />
* Si es compatible con los controladores del sistema operativo invitado, utilice [https://wiki.libvirt.org/page/Virtio virtio] para dispositivos de red y/o bloque. Por ejemplo:<br />
$ qemu-system-i386 -net nic, model=virtio -net tap, if=tap0, script=no-drive file=''disk_image'',media=disco, if=virtio<br />
* Utilizar dispositivos TAP en lugar de redes en modo usuario. Consulte [[#Tap de red con QEMU]].<br />
* Si el sistema operativo invitado está haciendo escritura pesada en su disco, puede beneficiarse de ciertas opciones de montaje en el sistema de archivos del host. Por ejemplo, puede montar un [[Ext4|sistema de archivos ext4]] con la opción {{ic|1=barrier=0}}. Debe leer la documentación de las opciones que cambie porque a veces las opciones de mejora de rendimiento para los sistemas de archivos tienen el costo de integridad de los datos.<br />
* Si tiene una imagen de disco sin procesar, puede deshabilitar la caché:<br />
$ qemu-system-i386 -drive file=''disk_image'', if=virtio, cache=none<br />
* Utilice el nativo Linux AIO:<br />
$ qemu-system-i386 -drive file=''disk_image'', if=virtio, aio=native<br />
* Si utiliza una imagen de disco qcow2, el rendimiento de E/S se puede mejorar considerablemente al garantizar que el caché L2 es de tamaño suficiente. La fórmula [https://blogs.igalia.com/berto/2015/12/17/improving-disk-io-performance-in-qemu-2-5-with-the-qcow2-l2-cache/] para calcular La caché L2 es: l2_cache_size = disk_size * 8 / cluster_size. Suponiendo que la imagen qcow2 se creó con el tamaño de clúster predeterminado de 64 K, esto significa que para cada 8 GB de tamaño de la imagen qcow2, 1 MB de caché L2 es mejor para el rendimiento. QEMU utiliza sólo 1 MB por defecto; Especificar una caché más grande se hace en la línea de comandos QEMU. Por ejemplo, para especificar 4 MB de caché (adecuado para un disco de 32 GB con un tamaño de clúster de 64 KB):<br />
$ qemu-system-i386 -drive file=''disk_image'',format=qcow2, l2-cache-size=4M<br />
* Si está ejecutando varias máquinas virtuales al mismo tiempo que todas tienen el mismo sistema operativo instalado, puede ahorrar memoria al habilitar [[wikipedia: Kernel_SamePage_Merging_ (KSM)|kernel de la misma página de fusión]]. Consulte [[#Habilitar KSM]].<br />
* En algunos casos, la memoria se puede recuperar de correr máquinas virtuales ejecutando un controlador de globo de memoria en el sistema operativo invitado y lanzando QEMU con la opción {{ic|-balloon virtio}}.<br />
* Es posible utilizar una capa de emulación para un controlador ICH-9 AHCI (aunque puede ser inestable). La emulación AHCI soporta [[Wikipedia: Native_Command_Queuing|NCQ]], por lo que varias peticiones de lectura o escritura pueden estar pendientes al mismo tiempo:<br />
$ qemu-system-i386 -drive id=disc, file=''disk_image'', if=none -device ich9-ahci, id=ahci -device ide-drive, drive=disk, bus=ahci.0<br />
<br />
Mira https://www.linux-kvm.org/page/Tuning_KVM para más información.<br />
<br />
=== El cursor del ratón está nervioso o errático ===<br />
<br />
Si el cursor "brinca" descontroladamente, podría ayudar ingresar este comando en la terminal antes de iniciar QEMU<br />
<br />
$ export SDL_VIDEO_X11_DGAMOUSE=0<br />
<br />
Si funciono, puedes agregarlo a tu {{ic|~/.bashrc}} archivo.<br />
<br />
=== El cursor no es visible ===<br />
<br />
Añade {{ic|-show-cursor}} a las opciones de QEMU para poder ver el cursor.<br />
<br />
Si persiste, asegurate de configurar la pantalla apropiadamente<br />
<br />
Por ejemplo: {{ic|-vga qxl}}<br />
<br />
=== No se puede mover / adjuntar el cursor ===<br />
<br />
Reemplaza {{ic|-usbdevice tablet}} con {{ic|-usb}} como opción en QEMU.<br />
<br />
=== El teclado parece roto ó las teclas de flecha no funcionan ===<br />
<br />
Probablemente notarás que algunas de tus teclas no funcionan ó "presionan" la tecla equivocada (en particular, las flechas), preferentemente, necesitas especificar la distribución de tu teclado como una opción. La distribución del teclado puede encontrarse en {{ic|/usr/share/qemu/keymaps}}.<br />
<br />
$ qemu-system-i386 -k ''keymap'' ''disk_image''<br />
<br />
=== Pantalla de invitado estirada en el tamaño de la ventana ===<br />
<br />
Para restarurar el tamaño por defecto de la ventanta, presiona {{ic|Ctrl+Alt+u}}.<br />
<br />
=== ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy ===<br />
<br />
Si un mensaje de error como este es listado en el arranque de QEMU con la opción {{ic|-enable-kvm}}:<br />
<br />
ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy<br />
failed to initialize KVM: Device or resource busy<br />
<br />
Significa que otro [[hypervisor]] está actualmente activo. No se recomienda ó no es poible correr varios hypervisores en paralelo.<br />
<br />
=== Mensaje de error libgfapi ===<br />
<br />
El mensaje de error listado en el arranque:<br />
<br />
Failed to open module: libgfapi.so.0: cannot open shared object file: No such file or directory<br />
<br />
No es un problema, sólo significa que hace falta la dependencia opcional de GlusterFS<br />
<br />
=== Kernel panic en entornos live ===<br />
<br />
Si inicia un sistema en vivo (ó bootea uno) podría encontrar esto:<br />
<br />
end Kernel panic - not syncing: VFS: Unable to mount root fs on unknown block(0,0)<br />
<br />
Ó algún otro proceso de arranque (ej. no se puede desempaquetar initramfs, no puede iniciar un servicio foo).<br />
<br />
Intente iniciar la Máquina Virtual con el {{ic|-m VALOR}} switch y un tamaño apropiado de RAM, si la RAM es muy poca probablemente encontrará problemas similares a los anteriores.<br />
<br />
== Ver también ==<br />
<br />
* [https://qemu.org Sitio web oficial de QEMU]<br />
* [https://www.linux-kvm.org Sitio web oficial de KVM]<br />
* [https://web.archive.org/web/20200514080826/https://qemu.weilnetz.de/doc/qemu-doc.html Documentación para el usuario del emulador QEMU] (en inglés)<br />
* [https://en.wikibooks.org/wiki/QEMU Wikilibro de QEMU] (en inglés)<br />
* [http://alien.slackbook.org/dokuwiki/doku.php?id=slackware:qemu Virtualización de hardware con QEMU por AlienBOB (última actualización en 2008) (en inglés)<br />
* [http://blog.falconindy.com/articles/build-a-virtual-army.html Construyendo un ejército virtual] por Falconindy (en inglés)<br />
* [https://git.qemu.org/?p=qemu.git;a=tree;f=docs Últimos documentos]<br />
* [https://qemu.weilnetz.de/ QEMU en Windows]<br />
* [[wikipedia:Qemu|Wikipedia]]<br />
* [https://wiki.debian.org/QEMU QEMU - Wiki de Debian] (en inglés)<br />
* [https://people.gnome.org/~markmc/qemu-networking.html QEMU Networking on gnome.org]{{Dead link (Español)|2022|09|22|status=404}}<br />
* [http://bsdwiki.reedmedia.net/wiki/networking_qemu_virtual_bsd_systems.html Red virtual de QEMU en sistemas BSD] (en inglés)<br />
* [https://www.gnu.org/software/hurd/hurd/running/qemu.html QEMU on gnu.org]<br />
* [https://wiki.freebsd.org/qemu QEMU en FreeBSD como host] (en inglés)</div>Malcontenthttps://wiki.archlinux.org/index.php?title=QEMU_(Espa%C3%B1ol)&diff=796061QEMU (Español)2024-01-04T20:50:31Z<p>Malcontent: Fix Spanish translation</p>
<hr />
<div>[[Category:Emulation (Español)]]<br />
[[Category:Hypervisors (Español)]]<br />
[[de:QEMU]]<br />
[[en:QEMU]]<br />
[[fr:QEMU]]<br />
[[ja:QEMU]]<br />
[[zh-hans:QEMU]]<br />
{{Bad translation (Español)|No updates since 2017-01-12, English page has seen major changes since.}}<br />
{{TranslationStatus (Español)|QEMU|2017-01-12|463282}}<br />
{{Related articles start (Español)}}<br />
{{Related|:Category:Hypervisors}}<br />
{{Related|Libvirt}}<br />
{{Related articles end}}<br />
<br />
De acuerdo con [https://wiki.qemu.org/Main_Page la wiki de QEMU], "QEMU es un emulador genérico y de código abierto de máquinas virtuales."<br />
<br />
Cuando se utiliza como un emulador de máquina, QEMU puede correr sistemas operativos y programas hechos para una máquina en particular (por ej. una placa ARM) en una máquina diferente (e.j. tu PC x86). Usando la traducción dinámica, se consigue un rendimiento muy bueno.<br />
<br />
QEMU puede usar hipervisores como [[Xen]] o [[KVM]] para utilizar las extensiones del procesador para la virtualización. Cuando se utiliza como virtualizador, QEMU alcanza un performance cercano a el rendimiento nativo ejecutando el código de invitado directamente en el CPU host.<br />
<br />
== Instalación ==<br />
<br />
[[Help:Reading (Español)#Instalación de paquetes|Instale]] el paquete {{Pkg|qemu-desktop}} (ó {{Pkg|qemu-base}} para la versión sin GUI) y los paquetes opcionales para tus necesidades:<br />
<br />
* {{Pkg|qemu-emulators-full}} - Soporte extra para arquitecturas<br />
* {{Pkg|qemu-block-gluster}} - Soporte para bloque glusterfs <br />
* {{Pkg|qemu-block-iscsi}} - Soporte para bloque iSCSI <br />
* {{Pkg|qemu-block-rbd}}{{Broken package link (Español)|package not found}} - Soporte para bloque RBD <br />
* {{Pkg|samba}} - SMB/ Soporte para servidor CIFS<br />
<br />
== front-ends para QEMU ==<br />
<br />
A diferencia de otros programas de virtualización como [[VirtualBox]] y [[VMware]], QEMU no proporciona una interfaz gráfica de usuario para administrar máquinas virtuales (a parte de la ventana que aparece cuando se ejecuta una máquina virtual), tampoco proporciona una forma de crear una máquina virtual persistente con valores guardados. Todos los parámetros para ejecutar una máquina virtual deben especificarse en la línea de comandos en cada puesta en marcha, a menos que haga un script personalizadp para iniciar su máquina(s) virtual. Sin embargo, hay varios front-end GUI para QEMU: <br />
<br />
* {{AUR|qemu-launcher}}<br />
* {{AUR|qtemu}}<br />
* {{AUR|aqemu}}<br />
<br />
front-ends con soporte para QEMU están disponibles por [[libvirt]].<br />
<br />
== Creando un nuevo sistema virtualizado ==<br />
<br />
=== Creando una imagen de disco duro ===<br />
<br />
{{Tip (Español)|Véase la [https://en.wikibooks.org/wiki/QEMU/Images Wiki de QEMU] para más información sobre imágenes de QEMU.}}<br />
<br />
Para ejecutar QMEU necesitarás una imagen de disco duro, a menos que estés cargando un sistema en vivo desde el CD-ROM ó la red (y no para instalar un sistema operativo en una imagen de disco duro). Una imagen de disco es un archivo que almacena los contenidos del disco duro emulado.<br />
<br />
Una imagen de disco puede ser en "crudo", de manera que, literalemte, byte por byte es lo mismo que el cliente ve, y siempre utilizará toda la capacidad del disco duro del disco duro invitado en el host. Este método proporciona la menor sobrecarga de Entrada / Salida, pero puede desperdiciar una gran cantidad de espacio, ya que el espacio no utilizado por el invitado no se puede utilizar en el host. <br />
<br />
Por otra parte, la imagen de disco duro puede estar en un formato tal como el de ''qcow2'' el cuál únicamente asigna espacio a el archivo de la imagen cuando el SO invitado está escribiendo en los sectores del disco virtual. La imagen aparece como el tamaño total del sistema operativo huésped, a pesar que puede tomar hasta una cantidad muy pequeña de espacio en el sistema host. El uso de este formato en lugar de el "crudo" probablemente afecte el rendimiento. <br />
<br />
QEMU proporciona el {{ic|qemu-img}} comando para crear imagenes de disco.<br />
Por ejemplo, para crear una imagen de 4GB en formato "crudo":<br />
<br />
$ qemu-img create -f raw ''image_file'' 4G<br />
<br />
Se puede uiltizar {{ic|-f qcow2}} para crear un disco ''qcow2'' en su lugar. <br />
<br />
{{Note (Español)|También puedes simplemente crear una imagen "cruda" meidante la creación de un archivo del tamaño necesitado usando {{ic|dd}} ó {{ic|fallocate}}.}}<br />
<br />
{{Warning (Español)|Si almacenas una imágen de disco en un sistema de archivos [[Btrfs (Español)|Btrfs]], deberías considerar deshabilitar [[Btrfs (Español)#Copy-on-Write (CoW)|Copy-on-Write]] para el directorio antes de crear imágenes.}}<br />
<br />
==== Superposición de imágenes de almacenamiento ====<br />
<br />
Puede crear una imagen de almacenamiento una vez (la imagen de respaldo) y hacer que QEMU mantenga mutaciones a esta imagen en una imagen de superposición. Esto le permite volver a un estado anterior de esta imagen de almacenamiento. Puede volver a crear una nueva imagen de superposición en el momento en que desea revertir en función de la imagen de respaldo original.<br />
<br />
Para crear una imagen de superposición, ingrese el comando:<br />
<br />
$ qemu-img create -o backing_file=''img1.raw'',backing_fmt=''raw'' -f ''qcow2'' ''img1.cow''<br />
<br />
Después de eso, puede ejecutar su máquina virtual como de costumbre (ver [[#Ejecución del sistema virtualizado]]):<br />
<br />
$ qemu-system-x86_64 ''img1.cow''<br />
<br />
La imagen de respaldo se dejará intacta y se registrarán mutaciones en este almacenamiento en el archivo de imagen de superposición.<br />
<br />
Cuando cambia la ruta de acceso a la imagen de respaldo, se requiere reparación.<br />
<br />
{{Warning (Español)|La ruta del sistema de archivos absoluto de la imagen de respaldo se almacena en el archivo de imagen de superposición (binario)). Cambiar el trayecto de la imagen de respaldo requiere un esfuerzo.}}<br />
<br />
Asegúrese de que la ruta de la imagen de respaldo original sigue conduciendo a esta imagen. Si es necesario, haga un enlace simbólico en la ruta original a la nueva ruta. A continuación, emita un comando como:<br />
<br />
$ qemu-img rebase -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
A su discreción, usted puede alternativamente realizar un rebase 'inseguro' donde no se comprueba la ruta anterior a la imagen de respaldo:<br />
<br />
$ qemu-img rebase -u -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
==== Cambiar el tamaño de una imagen ====<br />
<br />
{{Warning (Español)|Cambiar el tamaño de una imagen que contiene un sistema de arranque NTFS podría hacer el sistema operativo instalado '''no arrancable'''. Para una explicación completa y solucioón alternativa mira [https://web.archive.org/web/20180319230757/http://tjworld.net/wiki/Howto/ResizeQemuDiskImages].}}<br />
<br />
El ejecutable {{ic|qemu-img}} tiene la opción {{ic|resize}}, que permite redimensionar fácilmente una imagen de disco duro. Funciona tanto para ''raw'' como para ''qcow2''. Por ejemplo, para aumentar el espacio de imagen en 10GB, ingresa:<br />
<br />
$ qemu-img resize ''disk_image'' +10G<br />
<br />
Después de ampliar la imagen de disco, debe utilizar el sistema de archivos y las herramientas de particionamiento dentro de la máquina virtual para comenzar a utilizar el nuevo espacio. Al reducir una imagen de disco, primero debe reducir los sistemas de archivos y los tamaños de partición asignados usando el sistema de archivos y las herramientas de partición dentro de la máquina virtual y luego reducir la imagen del disco en consecuencia, de lo contrario reducir la imagen del disco resultará en ¡pérdida de datos!<br />
<br />
=== Preparando el medio de instalación ===<br />
<br />
Para instalar un sistema operativo en su imagen de disco, necesita el medio de instalación (por ejemplo, disco óptico, unidad USB o imagen ISO) para el sistema operativo. El soporte de instalación no debe montarse porque QEMU accede directamente al medio.<br />
<br />
{{Tip (Español)|Si utiliza un disco óptico, es una buena idea volcar primero los medios a un archivo porque esto mejora el rendimiento y no requiere que tenga acceso directo a los dispositivos (es decir, puede ejecutar QEMU como un usuario normal sin tener Para cambiar permisos de acceso en el archivo de dispositivo del medio). Por ejemplo, si el nodo de dispositivo de CD-ROM tiene el nombre {{ic|/dev/cdrom}}, puede volcarlo a un archivo de comandos: {{bc|1=$ dd if=/dev/cdrom of=''Cd_image.iso''}}}}<br />
<br />
=== Instalando el sistema operativo ===<br />
<br />
Esta es la primera vez que necesitará iniciar el emulador. Para instalar el sistema operativo en la imagen de disco, debe adjuntar la imagen de disco y el medio de instalación a la máquina virtual y hacer que arranque desde el soporte de instalación.<br />
<br />
Por ejemplo, en invitados i386, para instalar desde un archivo ISO de arranque como CD-ROM y una imagen de disco sin formato:<br />
<br />
$ qemu-system-x86_64 -cdrom ''iso_image'' -boot order=d -drive file=''disk_image'',format=raw<br />
<br />
Consulte {{ic | qemu (1)}} para obtener más información sobre cómo cargar otros tipos de medios (como disquetes, imágenes de disco o unidades físicas) y [[#Ejecución del sistema virtualizado]] para otras opciones útiles.<br />
<br />
Una vez que el sistema operativo haya finalizado de instalar, la imagen de QEMU se puede iniciar directamente (ver [[#Ejecución del sistema virtualizado]]).<br />
<br />
{{Warning (Español)|De forma predeterminada, sólo se asignan 128 MB de memoria a la máquina. La cantidad de memoria se puede ajustar con el interruptor {{ic | -m}}, por ejemplo {{ic | -m 512M}} o {{ic | -m 2G}}.}}<br />
<br />
{{Tip (Español)|<br />
* En lugar de especificar {{ic | 1 = -boot order = x}}, algunos usuarios pueden sentirse más cómodos usando un menú de arranque: {{ic | 1 = -boot menu = on}}, al menos durante la configuración y la experimentación.<br />
* Si necesita reemplazar disquetes o CD como parte del proceso de instalación, puede usar el monitor de la máquina QEMU (presione {{ic | Ctrl + Alt + 2}} en la ventana de la máquina virtual) para quitar y conectar dispositivos de almacenamiento a un máquina virtual. Escriba {{ic | info block}} para ver los dispositivos de bloque y use el comando {{ic | change}} para intercambiar un dispositivo. Pulse {{ic | Ctrl + Alt + 1}} para volver a la máquina virtual.}}<br />
<br />
== Ejecución del sistema virtualizado ==<br />
<br />
Los binarios {{ic|qemu-system-*}} (por e.j. {{ic|qemu-system-i386}} ó {{ic|qemu-system-x86_64}}, dependiendo de la arquitectura del huésped) se usan para ejecutar el sistema virtualizado. El uso es:<br />
<br />
$ qemu-system-x86_64 ''options'' ''disk_image''<br />
<br />
Las opciones son las mismas para todos los binarios {{ic|qemu-system-*}}, mira {{ic|qemu(1)}} para más información sobre todas las opciones.<br />
<br />
Por defecto, QEMU mostrará la salida de video de la máquina virtual en una ventana. Una cosa a considerar: al hacer click dentro de la ventana de QMEU, el puntero del cursor será capturado. Para liberarlo presione {{ic|Ctrl+Alt+g}}.<br />
<br />
{{Warning (Español)|QEMU nunca debe ejecutarse como root. Si se debe iniciar en root, deberá usar la opción {{ic|-runas}} para que QEMU utilice privilegios de root.}}<br />
<br />
=== Activar KVM ===<br />
<br />
KVM debe ser soportado por su procesador y kernel, y necesariamente los [[kernel modules (Español)|módulos del kernel]] deben ser cargados. Mira [[KVM]] para más información.<br />
<br />
Para iniciar QEMU en modo KVM, adjunta {{ic|-enable-kvm}} a las opciones de inicio adicionales. Para verificar si KVM está activado para ejecutar una máquina virtual, ingresa a la wiki de QEMU [https://en.wikibooks.org/wiki/QEMU/Monitor Monitor], usando {{ic|Ctrl+Alt+Shift+2}}, e ingresando {{ic|info kvm}}. <br />
<br />
{{Note (Español)|<br />
* Si inicia su máquina virtual con una herramienta GUI y experimenta un rendimiento muy malo, debe verificar el soporte adecuado de KVM. <br />
* KVM necesita activarse en orden de iniciar adecuadamente Windows 7 y Windows 8 sin ''pantallazo azul''.<br />
}}<br />
<br />
=== Habilitar soporte IOMMU (Intel VT-d/AMD-Vi) ===<br />
<br />
Usando IOMMU (unidad de gestión de memoria de entrada y salida) se abre a las caraterísticas como el paso del PCI y la protección de la memoria de dispositivos defectuosos o maliciosos, mira [[wikipedia:Input-output memory management unit#Advantages]] y [https://www.quora.com/Memory-Management-computer-programming/Could-you-explain-IOMMU-in-plain-English Memory Management (computer programming): Could you explain IOMMU in plain English?].<br />
<br />
Para habilitar IOMMU:<br />
#Asegure que AMD-Vi/Intel VT-d es soportado por el CPU y es habilitado en la configuración de BIOS.<br />
#Agregue {{ic|1=intel_iommu=on}} si tienes un procesador Intel ó {{ic|1=amd_iommu=on}} si tienes un procesador AMD en los parámetros del kernel ([[kernel parameters]])<br />
#Reinicie y asegure que IOMMU está habilitado verificando {{ic|dmesg}} para {{ic|DMAR}}: {{ic|[0.000000] DMAR: IOMMU enabled}}<br />
#Añade {{ic|-device intel-iommu}} para crear el dispositivo IOMMU:<br />
<br />
$ qemu-system-x86_64 '''-enable-kvm -machine q35 -device intel-iommu''' -cpu host ..<br />
<br />
== Mover datos entre el host y el Sistema Operativo huésped ==<br />
<br />
=== Red ===<br />
<br />
Los datos pueden compartirse entre el host y el sistema operativo huésped usando cualquier protocolo de red que pueda transferir archivos, como [[NFS]], [[SMB]], [[Wikipedia:Network Block Device|NBD]], HTTP, [[Very Secure FTP Daemon|FTP]], ó [[SSH]], siempre que haya configurado la red apropiadamente y haya habilitado los servicios apropiados. <br />
<br />
La red por defecto del modo de usuario permite al huésped acceder al sistema operativo host en la dirección IP 10.0.2.2. Todos los servidores que se estén ejecutando en el sistema operativo anfitrión, como un servidor SSH o un servidor SMB, estarán accesibles en esta dirección IP. Así que en los invitados, puede montar los directorios exportados en el host a través de [[SMB]] o [[NFS]], o puede acceder al servidor HTTP del host, etc.<br />
No será posible que el sistema operativo anfitrión acceda a los servidores que se ejecutan en el sistema operativo invitado, pero esto puede hacerse con otras configuraciones de red (consulte [[#Tap de red con QEMU]]).<br />
<br />
=== Servidor SMB incorporado de QEMU ===<br />
<br />
La documentación de QEMU dice que tiene un servidor SMB "incorporado", pero en realidad acaba de iniciar [[Samba]] con un archivo {{ic | smb.conf}} generado automáticamente ubicado en {{ic|/tmp/qemu- Smb.''Pid''-0/smb.conf}} y lo hace accesible para el invitado en una dirección IP diferente (10.0.2.4 por defecto). Esto sólo funciona para la red de usuarios, y esto no es necesariamente muy útil ya que el invitado también puede acceder al servicio normal [[Samba]] en el host si ha configurado acciones en él.<br />
<br />
Para habilitar esta característica, inicie QEMU con un comando como:<br />
<br />
$ qemu-system-x86_64 -nic user,id=nic0,smb=''shared_dir_path'' ''disk_image''<br />
<br />
donde {{ic|''shared_dir_path''}} es un directorio que quieres compartir entre huésped y el host.<br />
<br />
Luego, en el invitado, podrá acceder al directorio compartido del host 10.0.2.4 con el nombre de recurso "qemu". Por ejemplo, en el Explorador de Windows iría a {{ic | \\ 10.0.2.4 \ qemu}}.<br />
<br />
{{Note (Español)|<br />
* Si estás usando opciones de compartir varias veces como {{ic|1=-net user, smb='' shared_dir_path1 '' -net user, smb='' shared_dir_path2 ''}} ó {{ic | 1 = -net user , Smb = '' shared_dir_path1 '', smb = '' shared_dir_path2 ''}} entonces solo compartirá el último definido.<br />
* Si no puede acceder a la carpeta compartida y el sistema invitado es Windows, compruebe que está habilitado el protocolo [http://ecross.mvps.org/howto/enable-netbios-over-tcp-ip-with-windows.htm NetBIOS ]{{Dead link (Español)|2023|05|06|status=domain name not resolved}} Y que un cortafuegos no bloquea los puertos [https://technet.microsoft.com/en-us/library/cc940063.aspx] utilizados por el protocolo NetBIOS.<br />
}}<br />
<br />
=== Montaje de una partición dentro de una imagen de disco raw ===<br />
<br />
Cuando la máquina virtual no se está ejecutando, es posible montar las particiones que están dentro de un archivo de imagen de disco sin formato configurándolas como dispositivos de bucle invertido. Esto no funciona con imágenes de disco en formatos especiales, como qcow2, aunque se pueden montar usando {{ic|qemu-nbd}}.<br />
<br />
{{Warning (Español)| Debe asegurarse de desmontar las particiones antes de ejecutar la máquina virtual de nuevo. De lo contrario, es muy probable que ocurra la corrupción de datos.}}<br />
<br />
==== Con la especificación manual del desplazamiento de bytes ====<br />
<br />
Una forma de montar una partición de imagen de disco es montar la imagen de disco en un cierto desplazamiento usando un comando como el siguiente:<br />
<br />
$ mount -o loop, offset = 32256 ''disk_image'' ''mountpoint''<br />
<br />
La opción {{ic|1 = offset = 32256}} se pasa realmente al programa {{ic|losetup}} para configurar un dispositivo de bucle invertido que empieza en el desplazamiento de byte 32256 del archivo y continúa hasta el final. A continuación, se monta este dispositivo de bucle invertido. También puede utilizar la opción {{ic|sizelimit}} para especificar el tamaño exacto de la partición, pero esto normalmente no es necesario.<br />
<br />
Dependiendo de la imagen del disco, la partición necesaria no se puede iniciar en el desplazamiento 32256. Ejecute {{ic|fdisk -l '' disk_image ''}} para ver las particiones de la imagen. Fdisk da las compensaciones de inicio y fin en sectores de 512 bytes, así que multiplique por 512 para obtener el desplazamiento correcto para pasar a {{ic|mount}}.<br />
<br />
==== Con las particiones autodetecting del módulo de bucle (loop) ====<br />
<br />
El controlador de bucle de Linux realmente admite particiones en dispositivos de bucle invertido, pero está desactivado de forma predeterminada. Para habilitarlo, haga lo siguiente:<br />
<br />
* Deshacerse de todos los dispositivos de bucle invertido (desmontar todas las imágenes montadas, etc.).<br />
* [[Kernel modules (Español)#Manejo manual de módulos|Descargar]] el módulo del kernel {{ic|loop}} y cargarlo con el conjunto de parámetros {{ic|1 = max_part = 15}}. Además, el número máximo de dispositivos de bucle puede controlarse con el parámetro {{ic | max_loop}}.<br />
<br />
{{Tip (Español)|Puede poner una entrada en {{ic|/etc/modprobe.d}} para cargar el módulo de bucle con {{ic|1=max_part=15}} cada vez, o puede poner {{ic|1 = loop.max_part = 15}} en la línea de comandos del kernel, dependiendo de si tiene o no el módulo {{ic|loop.ko}} integrado en su kernel.}}<br />
<br />
Configure su imagen como un dispositivo de bucle invertido:<br />
<br />
$ losetup -f -P ''disk_image''<br />
<br />
Entonces, si el dispositivo creado fue {{ic|/dev/loop0}}, se habrán creado automáticamente dispositivos adicionales {{ic|/dev/loop0pX}}, donde X es el número de la partición. Estos dispositivos de loopback de partición se pueden montar directamente. Por ejemplo:<br />
<br />
$ mount /dev/loop0p1 ''punto de montaje''<br />
<br />
Para montar la imagen de disco con '' udisksctl '', vea [[Udisks#Mount loop devices]].<br />
<br />
==== Con kpartx ====<br />
<br />
'' 'Kpartx' '' del paquete {{Pkg|multipath-tools}} puede leer una tabla de particiones en un dispositivo y crear un nuevo dispositivo para cada partición. Por ejemplo:<br />
# Kpartx -a '' disk_image ''<br />
<br />
Esto configurará el dispositivo de bucle invertido y creará los dispositivos de partición necesarios en {{ic|/dev/mapper/}}.<br />
<br />
=== Montar una partición dentro de una imagen qcow2 ===<br />
<br />
Puede montar una partición dentro de una imagen qcow2 usando {{ic|qemu-nbd}}. Mira [https://en.wikibooks.org/wiki/QEMU/Images#Mounting_an_image_on_the_host Wikibooks].<br />
<br />
=== Utilizar cualquier partición real como la única partición primaria de una imagen de disco duro ===<br />
<br />
A veces, puede que desee utilizar una de las particiones del sistema desde dentro de QEMU. El uso de una partición sin procesar para una máquina virtual mejorará el rendimiento, ya que las operaciones de lectura y escritura no pasan por la capa del sistema de archivos del host físico. Esta partición también proporciona una forma de compartir datos entre el host y el invitado.<br />
<br />
En Arch Linux, los archivos de dispositivo para las particiones sin procesar son, por defecto, propiedad de '' root '' y del grupo '' disk ''. Si desea que un usuario no root pueda leer y escribir en una partición en bruto, debe cambiar el propietario del archivo de dispositivo de la partición para ese usuario.<br />
<br />
{{Warning (Español)|<br />
* Aunque es posible, no se recomienda permitir que las máquinas virtuales alteren los datos críticos en el sistema host, como la partición raíz.<br />
* No debe montar un sistema de archivos en una partición de lectura-escritura en el host y el invitado al mismo tiempo. De lo contrario, se producirá corrupción de datos.<br />
}}<br />
<br />
Después de hacerlo, puede adjuntar la partición a una máquina virtual QEMU como un disco virtual.<br />
<br />
Sin embargo, las cosas son un poco más complicadas si desea tener la máquina virtual ''completa'' contenida en una partición. En ese caso, no habría ningún archivo de imagen de disco para arrancar realmente la máquina virtual, ya que no se puede instalar un cargador de arranque en una partición que está formateada como un sistema de archivos y no como un dispositivo particionado con un MBR. Una máquina virtual de este tipo se puede iniciar especificando el kernel y el initramfs manualmente o simulando un disco con un MBR usando RAID lineal.<br />
<br />
==== Especificar el kernel y el initrd manualmente ====<br />
<br />
QEMU es compatible con cargar [[Kernels|Linux kernels]] e [[initramfs|init ramdisks]] directamente, evitando así los cargadores de arranque como [[GRUB]]. A continuación, se puede iniciar con la partición física que contiene el sistema de archivos raíz como el disco virtual, que no parecen ser particionados. Esto se hace emitiendo un comando similar al siguiente:<br />
<br />
{{Note (Español)| En este ejemplo, se trata de las imágenes del '''host''' que se están utilizando, no del invitado. Si desea utilizar las imágenes del huésped, monte {{ic|/dev/sda3}} de sólo lectura (para proteger el sistema de archivos del host) y especifique {{ic|/full/path/to/images}} ó usar algún truco kexec en el invitado para recargar el kernel del invitado (extiende el tiempo de arranque).}}<br />
<br />
$ Qemu-system-i386 -kernel /boot/vmlinuz-linux -initrd /boot/initramfs-linux.img -append root=/dev/sda/dev/sda3<br />
<br />
En el ejemplo anterior, la partición física que se utiliza para el sistema de archivos raíz del huésped es {{ic|/dev/sda3}} en el host, pero aparece como {{ic|/dev/sda}} en el invitado.<br />
<br />
Por supuesto, puede especificar cualquier kernel e initrd que desee, y no sólo los que vienen con Arch Linux.<br />
<br />
Cuando hay varios [[kernel parameters]] que se pasan a la opción {{ic|-append}}, necesitan ser citados usando comillas simples o dobles. Por ejemplo:<br />
<br />
$ ... -append 'root=/dev/sda1 console=ttyS0'<br />
<br />
==== Simular disco virtual con MBR usando RAID lineal ====<br />
<br />
Una forma más complicada de tener una máquina virtual usar una partición física, mientras que mantener esa partición formateada como un sistema de archivos y no sólo tener la partición invitado la partición como si fuera un disco, es simular un MBR para que pueda Arranque utilizando un gestor de arranque tal como GRUB.<br />
<br />
Puede hacerlo utilizando el RAID del software en modo lineal (necesita el controlador de kernel {{ic|linear.ko}}) y un dispositivo de loopback: el truco consiste en añadir previamente un registro maestro de arranque (MBR) Real que desea incrustar en una imagen de disco RAEM QEMU.<br />
<br />
Suponga que tiene una partición simple {{ic|/|hdaN}} con algún sistema de archivos en la que desea formar parte de una imagen de disco QEMU. En primer lugar, crear un pequeño archivo para mantener el MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=32<br />
<br />
Aquí, se crea un archivo de 16 KB (32 * 512 bytes). Es importante no hacerlo demasiado pequeño (incluso si el MBR sólo necesita un bloque de 512 bytes), ya que cuanto menor sea, menor será el tamaño del chasis del dispositivo RAID de software, lo que podría tener un impacto En el rendimiento. A continuación, configura un dispositivo de bucle invertido en el archivo MBR:<br />
<br />
# losetup -f ''/path/to/mbr''<br />
<br />
Supongamos que el dispositivo resultante es {{ic|/dev/loop0}}, porque ya no habríamos estado usando otros bucle. El siguiente paso es crear la imagen de disco "fusionada" MBR + {{ic|/dev/hda''N''}} utilizando RAID de software:<br />
<br />
# modprobe lineal<br />
<br />
# mdadm --build --verbose /dev/md0 --chunk=16 --level=linear --raid-devices=2 /dev/loop0/dev/hda''N''<br />
<br />
El resultante {{ic|/dev/md0}} es lo que utilizará como una imagen de disco cruda QEMU (no olvide establecer los permisos para que el emulador pueda acceder a él). El último paso (y algo complicado) es configurar la configuración del disco (geometría del disco y tabla de particiones) para que el punto de inicio de la partición primaria en el MBR coincida con el de {{ic|/dev/hda''N''}}} Dentro {{ic|/dev/md0}} (un desplazamiento de exactamente 16 * 512 = 16384 bytes en este ejemplo). Hacer esto usando {{ic|fdisk}} en la máquina host, no en el emulador: la rutina de detección de disco crudo predeterminada de QEMU a menudo da lugar a offsets redondeados no kilobyte (como 31.5 KB, como en la sección anterior) que No puede ser administrado por el código RAID de software. Por lo tanto, desde el anfitrión:<br />
<br />
$ fdisk /dev/md0<br />
<br />
Pulse {{ic|X}} para entrar en el menú de expertos. Establezca el número de sectores por pista para que el tamaño de un cilindro coincida con el tamaño de su archivo MBR. Para dos cabezas y un tamaño de sector de 512, el número de sectores por pista debe ser 16, por lo que obtenemos cilindros de tamaño 2x16x512 = 16k.<br />
<br />
Ahora, presione {{ic|R}} para regresar al menú principal.<br />
<br />
Presione {{ic|P}} y compruebe que el tamaño del cilindro es ahora 16k.<br />
<br />
Ahora, cree una única partición primaria correspondiente a {{ic|/dev/hda''N''}}. Debe comenzar en el cilindro 2 y terminar en el extremo del disco (tenga en cuenta que el número de cilindros ahora difiere de lo que era cuando se introdujo fdisk.<br />
<br />
Finalmente, escribe el resultado al archivo: ya está. Ahora tiene una partición que puede montar directamente desde su host, así como parte de una imagen de disco QEMU:<br />
<br />
$ Qemu-system-i386 -hdc /dev/md0 ''[...]''<br />
<br />
Por supuesto, puede configurar con seguridad cualquier cargador de arranque en esta imagen de disco utilizando QEMU, siempre que la partición original {{ic|/dev/hda''N''}} contenga las herramientas necesarias.<br />
<br />
== Redes ==<br />
<br />
El rendimiento de la red virtual debería ser mejor con los dispositivos de derivación (tap) y puentes que con la red en modo de usuario o vde porque los dispositivos de derivación y los puentes se implementan en el kernel.<br />
<br />
Además, el rendimiento de la red se puede mejorar asignando a las máquinas virtuales un dispositivo de red [https://wiki.libvirt.org/page/Virtio virtio] en lugar de la emulación predeterminada de una NIC e1000. Consulte [[#Instalación de controladores virtio]] para obtener más información.<br />
<br />
=== Advertencia de dirección a nivel de enlace ===<br />
<br />
Al asignar el argumento {{ic|-net nic}} a QEMU, asignará por defecto a una máquina virtual una interfaz de red con la dirección de enlace {{ic|52:54:00:12:34:56}}. Sin embargo, cuando se utiliza la creación de redes puenteadas con varias máquinas virtuales, es esencial que cada máquina virtual tenga una dirección única de nivel de enlace (MAC) en el lado de la máquina virtual del dispositivo de derivación. De lo contrario, el puente no funcionará correctamente, ya que recibirá paquetes de varias fuentes que tienen la misma dirección de nivel de enlace. Este problema se produce incluso si los propios dispositivos de derivación tienen direcciones de nivel de enlace únicas porque la dirección de nivel de enlace de origen no se vuelve a escribir a medida que los paquetes pasan a través del dispositivo de derivación.<br />
<br />
Asegúrese de que cada máquina virtual tiene una dirección única de nivel de enlace, pero siempre debe comenzar con {{ic|52:54:}}. Utilice la opción siguiente, reemplazar ''X'' por un dígito hexadecimal arbitrario:<br />
<br />
$ qemu-system-i386 -net nic,macaddr=52:54:''XX:XX:XX:XX'' -net vde ''disk_image''<br />
<br />
Generar direcciones únicas de nivel de enlace se puede realizar de varias maneras:<br />
<br />
<ol><br />
<li>Especificar manualmente la dirección única de nivel de enlace para cada NIC. El beneficio es que el servidor DHCP asignará la misma dirección IP cada vez que se ejecute la máquina virtual, pero es inutilizable para un gran número de máquinas virtuales.<br />
</li><br />
<li>Generar dirección de nivel de enlace aleatoria cada vez que se ejecuta la máquina virtual. Prácticamente cero probabilidad de colisiones, pero la desventaja es que el servidor DHCP asignará una dirección IP diferente cada vez. Puede utilizar el siguiente comando en una secuencia de comandos para generar una dirección de nivel de enlace aleatoria en una variable {{ic|macaddr}}:<br />
<br />
{{bc|1=<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
qemu-system-i386 -net nic,macaddr="$macaddr" -net vde ''disk_image''<br />
}}<br />
<br />
</li><br />
<li>Utilice el siguiente script {{ic|qemu-mac-hasher.py}} para generar la dirección de nivel de enlace desde el nombre de la máquina virtual mediante una función de hash. Dado que los nombres de las máquinas virtuales son únicos, este método combina los beneficios de los métodos antes mencionados: genera la misma dirección de nivel de enlace cada vez que se ejecuta el script, aunque preserva la probabilidad prácticamente nula de colisiones.<br />
<br />
{{hc|qemu-mac-hasher.py|<nowiki><br />
#!/usr/bin/env python<br />
<br />
import sys<br />
import zlib<br />
<br />
if len(sys.argv) != 2:<br />
print("usage: %s <VM Name>" % sys.argv[0])<br />
sys.exit(1)<br />
<br />
crc = zlib.crc32(sys.argv[1].encode("utf-8")) & 0xffffffff<br />
crc = str(hex(crc))[2:]<br />
print("52:54:%s%s:%s%s:%s%s:%s%s" % tuple(crc))<br />
</nowiki>}}<br />
<br />
En un script, puede utilizar por ejemplo:<br />
<br />
vm_name="''VM Name''"<br />
qemu-system-i386 -name "$vm_name" -net nic,macaddr=$(qemu-mac-hasher.py "$vm_name") -net vde ''disk_image''<br />
</li><br />
</ol><br />
<br />
=== Redes en modo de usuario ===<br />
<br />
De forma predeterminada, sin ningún argumento {{ic|-netdev}}, QEMU utilizará la red en modo usuario con un servidor DHCP incorporado. A sus máquinas virtuales se les asignará una dirección IP cuando ejecuten su cliente DHCP, y podrán acceder a la red del host físico a través de la mascarada de IP realizada por QEMU.<br />
<br />
{{Warning (Español)| Esto sólo funciona con los protocolos TCP y UDP, por lo que ICMP, incluido {{ic|ping}}, no funcionará. No utilice {{ic|ping}} para probar la conectividad de red.}}<br />
<br />
Esta configuración predeterminada permite que sus máquinas virtuales accedan fácilmente a Internet, siempre que el host esté conectado a él, pero las máquinas virtuales no estarán directamente visibles en la red externa ni las máquinas virtuales podrán comunicarse entre sí si empieza Más de uno simultáneamente.<br />
<br />
La red de usuario en modo QEMU puede ofrecer más capacidades, como servidores TFTP o SMB incorporados, redirigir los puertos del host al huésped (por ejemplo, para permitir conexiones SSH al invitado) o conectar invitados a las VLAN para que puedan hablar entre sí. Consulte la documentación de QEMU en el indicador {{ic|-net user}} para obtener más detalles.<br />
<br />
Sin embargo, la conexión en red en modo usuario tiene limitaciones tanto en la utilidad como en el rendimiento. Las configuraciones de red más avanzadas requieren el uso de dispositivos de derivación u otros métodos.<br />
<br />
=== Tap de red con QEMU ===<br />
<br />
Los [[wikipedia:TUN/TAP|dispositivos tap]] Son una característica del kernel de Linux que le permite crear interfaces de red virtuales que aparecen como interfaces de red reales. Los paquetes enviados a una interfaz de derivación se entregan a un programa de espacio de usuario, tal como QEMU, que se ha enlazado a la interfaz.<br />
<br />
QEMU puede utilizar la red de derivación para una máquina virtual de modo que los paquetes enviados a la interfaz de derivación se envíen a la máquina virtual y aparezcan como procedentes de una interfaz de red (normalmente una interfaz Ethernet) en la máquina virtual. Por el contrario, todo lo que la máquina virtual envía a través de su interfaz de red aparecerá en la interfaz de tap.<br />
<br />
Los dispositivos de toque son soportados por los controladores de puente de Linux, por lo que es posible conectar entre sí los dispositivos entre sí y posiblemente con otras interfaces de host como {{ic|eth0}}. Esto es deseable si desea que sus máquinas virtuales puedan hablar entre sí, o si desea que otras máquinas en su LAN puedan hablar con las máquinas virtuales.<br />
<br />
{{Warning (Español)|Si conectas el dispositivo de toque y alguna interfaz de host, como {{ic|eth0}}, las máquinas virtuales aparecerán directamente en la red externa, lo que los exponerá a posibles ataques. Dependiendo de los recursos a los que tengan acceso sus máquinas virtuales, es posible que tenga que tomar todas las [[Firewalls|precauciones]] que normalmente tomaría al asegurar una computadora para proteger sus máquinas virtuales. Si el riesgo es demasiado grande, las máquinas virtuales tienen pocos recursos o se configuran varias máquinas virtuales, una solución mejor podría ser utilizar [[#Red de host solamente]] y configurar NAT. En este caso sólo necesitará un firewall en el host en lugar de múltiples firewalls para cada huésped.}}<br />
<br />
Como se indica en la sección de conexión en red de modo de usuario, los dispositivos de derivación ofrecen un rendimiento de red más alto que el modo de usuario. Si el OS invitado admite el controlador de red virtio, el rendimiento de la red se incrementará considerablemente también. Suponiendo el uso del dispositivo tap0, que el controlador virtio se utiliza en el invitado, y que no se utilizan scripts para ayudar a iniciar / detener la creación de redes, a continuación es parte del comando qemu se debe ver:<br />
<br />
-net nic, model=virtio -net tap, ifname=tap0, script=no, downscript=no<br />
<br />
Pero si ya está utilizando un dispositivo de tap con virtio controlador de red, uno puede incluso aumentar el rendimiento de la red mediante la activación de vhost, como:<br />
<br />
-net nic, model=virtio -net tap, ifname=tap0, script=no, downscript=no, vhost=on<br />
<br />
Ver http://www.linux-kvm.com/content/how-maximize-virtio-net-performance-vhost-net para obtener más información.<br />
<br />
==== Red de host solamente ====<br />
<br />
Si al puente se le da una dirección IP y se permite el tráfico destinado a ello, pero no hay una interfaz real (por ejemplo, {{ic|eth0}}) conectada al puente, las máquinas virtuales podrán hablar entre sí y la Sistema anfitrión. Sin embargo, no podrán hablar con nada en la red externa, siempre y cuando no configure IP enmascarada en el host físico. Esta configuración se llama '' red de host solamente '' por otro software de virtualización como [[VirtualBox]].<br />
<br />
{{Tip (Español)|<br />
* Si desea configurar IP masquerading, ej. NAT para máquinas virtuales, consulte la página [[Internet sharing#Enable NAT]].<br />
* Es posible que desee tener un servidor DHCP que se ejecute en la interfaz de puente para dar servicio a la red virtual. Por ejemplo, para usar la subred {{ic|172.20.0.1/16}} con [[dnsmasq]] como servidor DHCP:<br />
# ip addr add 172.20.0.1/16 dev br0<br />
# ip link set br0 up<br />
# dnsmasq --interface&#61;br0 --bind-interfaces --dhcp-range&#61;172.20.0.2,172.20.255.254<br />
}}<br />
<br />
==== Red interna ====<br />
<br />
Si no le da al puente una dirección IP y agrega una regla [[iptables]] para eliminar todo el tráfico al puente en la cadena INPUT, las máquinas virtuales podrán hablar entre sí, pero no con el host físico ó la red exterior. Esta configuración se llama "red interna" por otro software de virtualización como [[VirtualBox]]. Deberá asignar direcciones IP estáticas a las máquinas virtuales o ejecutar un servidor DHCP en una de ellas.<br />
<br />
De forma predeterminada, iptables eliminaría los paquetes de la red de bridge. Es posible que necesite utilizar dicha regla iptables para permitir paquetes en una red puenteada:<br />
<br />
# iptables -I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Redes puenteadas usando qemu-bridge-helper ====<br />
<br />
{{Note (Español)| Este método está disponible desde QEMU 1.1, consulte https://wiki.qemu.org/Features/HelperNetworking.}}<br />
<br />
Este método no requiere una secuencia de comandos de inicio y acepta fácilmente múltiples tomas y puentes múltiples. Utiliza el binario {{ic|/usr/lib/qemu/qemu-bridge-helper}}, que permite crear dispositivos de derivación en un puente existente.<br />
<br />
{{Tip (Español)|Véase [[Network bridge]] para obtener información sobre cómo crear un puente.}}<br />
<br />
En primer lugar, cree un archivo de configuración que contenga los nombres de todos los puentes que QEMU utilizará:<br />
<br />
{{hc|/etc/qemu/bridge.conf|<br />
allow ''bridge0''<br />
allow ''bridge1''<br />
...}}<br />
<br />
Ahora inicie la VM. El uso más básico sería:<br />
<br />
$ qemu-system-i386 -net nic -net bridge,br=''bridge0'' ''[...]''<br />
<br />
Con múltiples taps, el uso más básico requiere especificar la VLAN para todos los NIC adicionales:<br />
<br />
$ qemu-system-i386 -net nic -net bridge,br=''bridge0'' -net nic,vlan=1 -net bridge,vlan=1,br=''bridge1'' ''[...]''<br />
<br />
==== Creación manual del puente ====<br />
<br />
{{Tip (Español)|Desde QEMU 1.1, el [https://wiki.qemu.org/Features/HelperNetworking puente de red ayudante] puede establecer tun / tap up para usted sin necesidad de secuencias de comandos adicionales. Consulte [[#Redes puenteadas usando qemu-bridge-helper]].}}<br />
<br />
A continuación se describe cómo conectar una máquina virtual con una interfaz de host como {{ic | eth0}}, que es probablemente la configuración más común. Esta configuración hace que parezca que la máquina virtual está ubicada directamente en la red externa, en el mismo segmento Ethernet que la máquina host física.<br />
<br />
Vamos a reemplazar el adaptador Ethernet normal con un adaptador de puente y enlazar el adaptador Ethernet normal a él.<br />
<br />
* Instale {{Pkg|bridge-utils}}, que proporciona {{ic|brctl}} para manipular puentes.<br />
<br />
* Habilitar el reenvío IPv4:<br />
<br />
# sysctl net.ipv4.ip_forward=1<br />
<br />
Para hacer el cambio permanente, cambie {{ic|1=net.ipv4.ip_forward = 0}} a {{ic|1=net.ipv4.ip_forward = 1}} en {{ic|/etc/sysctl.d/99-sysctl.conf}}.<br />
<br />
* Cargue el módulo {{ic|tun}} y configurelo para cargarlo en el arranque. Véase [[Kernel modules (Español)]] para más detalles.<br />
<br />
* Ahora cree el puente. Ver [[Bridge with netctl]] para más detalles. Recuerde nombrar su puente como {{ic|br0}}, o modifique lo scripts a continuación del nombre del puente.<br />
<br />
* Cree el script que QEMU utiliza para abrir el adaptador de toma con los permisos {{ic|root:kvm}} 750:<br />
{{hc|/etc/qemu-ifup|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifup"<br />
echo "Bringing up $1 for bridged mode..."<br />
sudo /usr/bin/ip link set $1 up promisc on<br />
echo "Adding $1 to br0..."<br />
sudo /usr/bin/brctl addif br0 $1<br />
sleep 2<br />
</nowiki>}}<br />
<br />
* Cree el guión que QEMU utiliza para derribar el adaptador de toma en {{ic|/etc/qemu-ifdown}} con los permisos {{ic|root:kvm}} 750:<br />
{{hc|/etc/qemu-ifdown|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifdown"<br />
sudo /usr/bin/ip link set $1 down<br />
sudo /usr/bin/brctl delif br0 $1<br />
sudo /usr/bin/ip link delete dev $1<br />
</nowiki>}}<br />
<br />
* Use {{ic|visudo}} para añadir lo siguiente a el archivo {{ic|sudoers}}:<br />
{{bc|<nowiki><br />
Cmnd_Alias QEMU=/usr/bin/ip,/usr/bin/modprobe,/usr/bin/brctl<br />
%kvm ALL=NOPASSWD: QEMU<br />
</nowiki>}}<br />
<br />
* Se inicia QEMU con el siguiente script {{ic|run-qemu}}:<br />
{{hc|run-qemu|<nowiki><br />
#!/bin/bash<br />
USERID=$(whoami)<br />
<br />
# Get name of newly created TAP device; see https://bbs.archlinux.org/viewtopic.php?pid=1285079#p1285079<br />
precreationg=$(/usr/bin/ip tuntap list | /usr/bin/cut -d: -f1 | /usr/bin/sort)<br />
sudo /usr/bin/ip tuntap add user $USERID mode tap<br />
postcreation=$(/usr/bin/ip tuntap list | /usr/bin/cut -d: -f1 | /usr/bin/sort)<br />
IFACE=$(comm -13 <(echo "$precreationg") <(echo "$postcreation"))<br />
<br />
# This line creates a random MAC address. The downside is the DHCP server will assign a different IP address each time<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
# Instead, uncomment and edit this line to set a static MAC address. The benefit is that the DHCP server will assign the same IP address.<br />
# macaddr='52:54:be:36:42:a9'<br />
<br />
qemu-system-i386 -net nic,macaddr=$macaddr -net tap,ifname="$IFACE" $*<br />
<br />
sudo ip link set dev $IFACE down &> /dev/null<br />
sudo ip tuntap del $IFACE mode tap &> /dev/null<br />
</nowiki>}}<br />
<br />
Para ejecutar una VM, haz algo como esto:<br />
<br />
$ run-qemu -hda ''myvm.img'' -m 512 -vga std<br />
<br />
* Se recomienda, por motivos de rendimiento y seguridad, deshabilitar el firewall [http://ebtables.netfilter.org/documentation/bridge-nf.html en el puente]:<br />
{{hc|/etc/sysctl.d/10-disable-firewall-on-bridge.conf|<nowiki><br />
net.bridge.bridge-nf-call-ip6tables = 0<br />
net.bridge.bridge-nf-call-iptables = 0<br />
net.bridge.bridge-nf-call-arptables = 0<br />
</nowiki>}}<br />
Ejecute {{ic|sysctl -p /etc/sysctl.d/10-disable-firewall-on-bridge.conf}} para aplicar los cambios inmediatamente.<br />
<br />
Ver [https://wiki.libvirt.org/page/Networking#Creating_network_initscripts libvirt wiki] y [https://bugzilla.redhat.com/show_bug.cgi?id=512206 Fedora bug 512206]. Si obtiene errores de sysctl durante el inicio de archivos no existentes, haga que el módulo {{ic|bridge}} se cargue al arrancar. Véase [[Kernel module (Español)#systemd]].<br />
<br />
Como alternativa, puede configurar [[iptables]] para permitir que todo el tráfico se reenvíe a través del puente mediante la adición de una regla como esta:<br />
<br />
-I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Compartición de red entre dispositivo físico y un dispositivo de toque a través de iptables ====<br />
<br />
La conexión en puente funciona bien entre una interfaz cableada (por ejemplo, eth0), y es fácil de configurar. Sin embargo, si el host se conecta a la red a través de un dispositivo inalámbrico, el puente no es posible.<br />
<br />
Consulte [[Network bridge#Wireless interface on a bridge]] como referencia.<br />
<br />
Una forma de superar esto es configurar un dispositivo de derivación con una IP estática, haciendo que linux maneje automáticamente el enrutamiento para ella y, a continuación, reenvíe el tráfico entre la interfaz de derivación y el dispositivo conectado a la red a través de las reglas de iptables.<br />
<br />
Consulte [[Internet sharing]] como referencia.<br />
<br />
Allí puede encontrar lo que se necesita para compartir la red entre dispositivos, incluidos los de tap y tun. Lo siguiente sólo indica algunas de las configuraciones de host requeridas. Como se indica en la referencia anterior, el cliente debe configurarse para una IP estática, utilizando la IP asignada a la interfaz de derivación como puerta de enlace. La advertencia es que los servidores DNS del cliente pueden necesitar ser editados manualmente si cambian al cambiar de un dispositivo host conectado a la red a otro.<br />
<br />
Para permitir el reenvío de IP en cada inicio, es necesario agregar las siguientes líneas al archivo de configuración de sysctl dentro de /etc/sysctl.d:<br />
<br />
net.ipv4.ip_forward = 1<br />
net.ipv6.conf.default.forwarding = 1<br />
net.ipv6.conf.all.forwarding = 1<br />
<br />
Las reglas de iptables pueden verse así:<br />
<br />
# Forwarding from/to outside<br />
iptables -A FORWARD -i ${INT} -o ${EXT_0} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_1} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_2} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_0} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_1} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_2} -o ${INT} -j ACCEPT<br />
# NAT/Masquerade (network address translation)<br />
iptables -t nat -A POSTROUTING -o ${EXT_0} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_1} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_2} -j MASQUERADE<br />
<br />
El anterior supone que hay 3 dispositivos conectados a la red compartiendo tráfico con un dispositivo interno, donde por ejemplo:<br />
<br />
INT=tap0<br />
EXT_0=eth0<br />
EXT_1=wlan0<br />
EXT_2=tun0<br />
<br />
El anterior muestra un reenvío que permitiría compartir conexiones cableadas e inalámbricas con el dispositivo de derivación (tap).<br />
<br />
Las reglas de reenvío que se muestran son apátridas y para el reenvío puro. Se podría pensar en restringir el tráfico específico, poniendo un cortafuegos en el lugar para proteger al huésped y otros. Sin embargo, esto reduciría el rendimiento de la red, mientras que un simple puente no incluye nada de eso.<br />
<br />
Bonus: Si la conexión es cableada o inalámbrica, si se conecta a través de VPN a un sitio remoto con un dispositivo tun, suponiendo que el dispositivo tun abierto para esa conexión es tun0, y las reglas iptables anteriores se aplican, entonces la conexión remota se obtiene también Compartido con el huésped. Esto evita la necesidad de que el invitado también abra una conexión VPN. Una vez más, como la red de invitados debe ser estática, entonces si la conexión del host de forma remota de esta manera, uno probablemente tendrá que editar los servidores DNS en el invitado.<br />
<br />
=== Trabajo en red con VDE2 ===<br />
<br />
==== ¿Qué es VDE? ====<br />
<br />
VDE significa Virtual Distributed Ethernet. Comenzó como una mejora del interruptor [[User-mode Linux|uml]] _. Es una caja de herramientas para administrar redes virtuales.<br />
<br />
La idea es crear interruptores virtuales, que son básicamente sockets, y "conectar" tanto máquinas físicas como máquinas virtuales en ellas. La configuración que mostramos aquí es bastante simple; Sin embargo, VDE es mucho más potente que esto, puede conectar conmutadores virtuales juntos, ejecutarlos en diferentes hosts y supervisar el tráfico en los switches. Usted está invitado a leer [https://web.archive.org/web/20190821040940/http://wiki.virtualsquare.org/wiki/index.php/Main_Page la documentación del proyecto].<br />
<br />
La ventaja de este método es que no tienes que agregar privilegios de sudo a tus usuarios. No se debe permitir que los usuarios regulares ejecuten modprobe.<br />
<br />
==== Basics ====<br />
<br />
El soporte de VDE puede ser [[pacman|instalado]] a través del paquete {{Pkg|vde2}} en los [[repositorios oficiales]].<br />
<br />
En nuestra configuración, usamos tun/tap para crear una interfaz virtual en el host. Cargue el módulo {{ic|tun}} (véase [[kernel modules (Español)]] para obtener más detalles):<br />
<br />
# modprobe tun<br />
<br />
Ahora crea el conmutador virtual:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
<br />
Esta línea crea el switch, crea {{ic|tap0}}, lo "enchufa" y permite a los usuarios del grupo {{ic|users}} usarlo.<br />
<br />
La interfaz está conectada pero no está configurada todavía. Para configurarlo, ejecute este comando:<br />
<br />
# ip addr add 192.168.100.254/24 dev tap0<br />
<br />
Ahora, sólo tiene que ejecutar KVM con estas opciones {{ic|-net}} como usuario normal:<br />
<br />
$ qemu-system-i386 -net nic -net vde -hda ''[...]''<br />
<br />
Configure la red para su invitado como lo haría en una red física.<br />
<br />
{{Tip (Español)|Es posible que desee configurar NAT en dispositivo de toque para acceder a Internet desde la máquina virtual. Consulte [[Internet sharing#Enable NAT]] para obtener más información.}}<br />
<br />
==== Startup scripts ====<br />
<br />
Ejemplo de script principal que inicia VDE:<br />
<br />
{{hc|/etc/systemd/scripts/qemu-network-env|<nowiki><br />
#!/bin/sh<br />
# Preparación del entorno de red QEMU/VDE<br />
<br />
# La configuración IP del dispositivo de derivación que se utilizará para<br />
# La red de la máquina virtual:<br />
<br />
TAP_DEV=tap0<br />
TAP_IP=192.168.100.254<br />
TAP_MASK=24<br />
TAP_NETWORK=192.168.100.0<br />
<br />
# Host interface<br />
NIC=eth0<br />
<br />
case "$1" in<br />
start)<br />
echo -n "Starting VDE network for QEMU: "<br />
<br />
# If you want tun kernel module to be loaded by script uncomment here<br />
#modprobe tun 2>/dev/null<br />
## Wait for the module to be loaded<br />
#while ! lsmod | grep -q "^tun"; do echo "Waiting for tun device"; sleep 1; done<br />
<br />
# Start tap switch<br />
vde_switch -tap "$TAP_DEV" -daemon -mod 660 -group users<br />
<br />
# Bring tap interface up<br />
ip address add "$TAP_IP"/"$TAP_MASK" dev "$TAP_DEV"<br />
ip link set "$TAP_DEV" up<br />
<br />
# Start IP Forwarding<br />
echo "1" > /proc/sys/net/ipv4/ip_forward<br />
iptables -t nat -A POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
;;<br />
stop)<br />
echo -n "Stopping VDE network for QEMU: "<br />
# Delete the NAT rules<br />
iptables -t nat -D POSTROUTING "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
<br />
# Bring tap interface down<br />
ip link set "$TAP_DEV" down<br />
<br />
# Kill VDE switch<br />
pgrep -f vde_switch | xargs kill -TERM<br />
;;<br />
restart|reload)<br />
$0 stop<br />
sleep 1<br />
$0 start<br />
;;<br />
*)<br />
echo "Usage: $0 {start|stop|restart|reload}"<br />
exit 1<br />
esac<br />
exit 0<br />
</nowiki>}}<br />
<br />
Ejemplo de servicio systemd utilizando el script anterior:<br />
<br />
{{hc|/etc/systemd/system/qemu-network-env.service|<nowiki><br />
[Unit]<br />
Description=Manage VDE Switch<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/etc/systemd/scripts/qemu-network-env start<br />
ExecStop=/etc/systemd/scripts/qemu-network-env stop<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
Cambiar permisos de {{ic|qemu-network-env}} para ser ejecutable<br />
<br />
# chmod u+x /etc/systemd/scripts/qemu-network-env<br />
<br />
Puede iniciar {{ic|qemu-network-env.service}} como de costumbre.<br />
<br />
==== Método alternativo ====<br />
<br />
Si el método anterior no funciona o no quiere meterse con las configuraciones del kernel, TUN, dnsmasq e iptables, puede hacer lo siguiente para obtener el mismo resultado.<br />
<br />
# vde_switch -daemon -mod 660 -group users<br />
# slirpvde --dhcp --daemon<br />
<br />
A continuación, para iniciar la VM con una conexión a la red del host:<br />
<br />
$ qemu-system-i386 -net nic,macaddr=52:54:00:00:EE:03 -net vde ''disk_image''<br />
<br />
=== Puente VDE2 ===<br />
<br />
Basado en [https://selamatpagicikgu.wordpress.com/2011/06/08/quickhowto-qemu-networking-using-vde-tuntap-and-bridge/ quickhowto: qemu networking using vde, tun/tap, and bridge] gráfico. Cualquier máquina virtual conectada a vde está expuesta externamente. Por ejemplo, cada máquina virtual puede recibir la configuración DHCP directamente desde su enrutador ADSL.<br />
<br />
==== Conceptos básicos ====<br />
<br />
Recuerde que necesita el módulo {{ic|tun}} y el paquete {{Pkg|bridge-utils}}.<br />
<br />
Cree el dispositivo vde2/tap:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
# ip link set tap0 up<br />
<br />
Cree el puente:<br />
<br />
# brctl addbr br0<br />
<br />
Agregue dispositivos:<br />
<br />
# brctl addif br0 eth0<br />
# brctl addif br0 tap0<br />
<br />
Y configure la interfaz del puente:<br />
<br />
# dhcpcd br0<br />
<br />
==== Startup scripts ====<br />
<br />
Todos los dispositivos deben estar configurados. Y sólo el puente necesita una dirección IP. Para dispositivos físicos en el puente (por ejemplo, {{ic|eth0}}), esto puede hacerse con [[netctl]] utilizando un perfil Ethernet personalizado con:<br />
<br />
{{hc|/etc/netctl/ethernet-noip|<nowiki><br />
Description='A more versatile static Ethernet connection'<br />
Interface=eth0<br />
Connection=ethernet<br />
IP=no<br />
</nowiki>}}<br />
<br />
El siguiente servicio systemd personalizado puede utilizarse para crear y activar una interfaz de toma VDE2 para su uso en el grupo de usuarios {{ic|users}}.<br />
<br />
{{hc|/etc/systemd/system/vde2@.service|<nowiki><br />
[Unit]<br />
Description=Network Connectivity for %i<br />
Wants=network.target<br />
Before=network.target<br />
<br />
[Service]<br />
Type=oneshot<br />
RemainAfterExit=yes<br />
ExecStart=/usr/bin/vde_switch -tap %i -daemon -mod 660 -group users<br />
ExecStart=/usr/bin/ip link set dev %i up<br />
ExecStop=/usr/bin/ip addr flush dev %i<br />
ExecStop=/usr/bin/ip link set dev %i down<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
Y, por último, puede crear el puente interfaz con netctl.<br />
<br />
== Gráficos ==<br />
<br />
QEMU puede utilizar las siguientes salidas gráficas diferentes: {{ic|std}}, {{ic|qxl}}, {{ic|vmware}}, {{ic|virtio}}, {{ic|cirrus}} y {{ic|none}}.<br />
<br />
=== std ===<br />
<br />
Con {{ic|-vga std}} puede obtener una resolución de hasta 2560 x 1600 píxeles sin necesidad de controladores invitados. Este es el valor predeterminado desde QEMU 2.2.<br />
<br />
=== qxl ===<br />
<br />
QXL Es un controlador de gráficos paravirtual con soporte 2D. Para usarlo, pase la opción {{ic|-vga qxl}} e instale los controladores en el invitado. Es posible que desee utilizar SPICE para mejorar el rendimiento gráfico al utilizar QXL.<br />
<br />
En los invitados de Linux, los módulos del kernel {{ic|qxl}} y {{ic|bochs_drm}} deben ser inicializados para poder tener un rendimiento decente.<br />
<br />
==== SPICE ====<br />
<br />
El proyecto [https://www.spice-space.org/ SPICE] tiene como objetivo proporcionar una solución completa de código abierto para el acceso remoto a máquinas virtuales de una manera transparente.<br />
<br />
SPICE sólo se puede utilizar cuando se utiliza QXL como la salida gráfica.<br />
<br />
El siguiente es un ejemplo de arranque con SPICE como protocolo de escritorio remoto:<br />
<br />
$ qemu-system-i386 -vga qxl -spice port=5930,disable-ticketing -chardev spicevm <br />
<br />
Conéctese al invitado utilizando un cliente SPICE. En este momento se recomienda {{Pkg|spice-gtk}}, sin embargo otros [https://www.spice-space.org/download.html clientes], incluyendo otras plataformas, están disponibles:<br />
<br />
$ spicy -h 127.0.0.1 -p 5930<br />
<br />
El uso de [[wikipedia:Unix_socket|Unix sockets]] en lugar de los puertos TCP no implica el uso de pila de red en el sistema host, por lo que es [https://unix.stackexchange.com/questions/91774/performance-of-unix- Sockets-vs-tcp-ports según se informa] mejor para el rendimiento. Ejemplo:<br />
$ qemu-system-x86_64 -vga qxl -device virtio-serial-pci -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent -spice unix,addr=/tmp/vm_spice.socket,disable-ticketing<br />
$ spicy --uri="spice+unix:///tmp/vm_spice.socket"<br />
<br />
Para una mejor compatibilidad con varios monitores, compartir el portapapeles, etc., los paquetes siguientes deben estar instalados en el invitado:<br />
* {{Pkg|spice-vdagent}}: Spice agent xorg cliente que permite copiar y pegar entre el cliente y X-session y más<br />
* {{Pkg|xf86-video-qxl}} {{AUR|xf86-video-qxl-git}}: Xorg X11 qxl controlador de vídeo<br />
* Para otros sistemas operativos, mire la sección Guest de la página [https://www.spice-space.org/download.html SPICE-Space download].<br />
<br />
=== vmware ===<br />
<br />
Aunque tiene pocos errores, tiene mejor rendimiento que std y cirrus. Instale los controladores de VMware {{Pkg|xf86-video-vmware}} y {{Pkg|xf86-input-vmmouse}} para los invitados de Arch Linux.<br />
<br />
=== virtio ===<br />
<br />
{{ic|virtio-vga}} / {{ic|virtio-gpu}} Es un controlador de gráficos 3D paravirtual basado en [https://virgil3d.github.io/ virgl]. Actualmente un trabajo en curso, que sólo admite a invitados Linux (>= 4.4) con {{Pkg|mesa}} (>= 11.2) compilados con la opción {{ic|1=--with-gallium-drivers=virgl}}.<br />
<br />
Para activar la aceleración 3D en el sistema invitado, seleccione vga con {{ic|-vga virtio}} y habilitar el contexto opengl en el dispositivo de visualización con {{ic|1=-display sdl,gl=on}} ó {{ic|1=-display gtk,gl=on}} Para la salida de pantalla sdl y gtk respectivamente. La configuración correcta se puede confirmar mirando el registro del kernel en el invitado:<br />
<br />
{{hc|# dmesg {{!}} grep drm |<br />
[drm] pci: virtio-vga detected<br />
[drm] virgl 3d acceleration enabled<br />
}}<br />
<br />
A partir de septiembre de 2016, el soporte para el protocolo de especias está en desarrollo y se puede probar la instalación de la versión de desarrollo de {{Pkg|spice}} (>= 0.13.2) y la recompilación de qemu.<br />
<br />
Para más información visite [https://web.archive.org/web/20171216170334/https://www.kraxel.org/blog/tag/virgl/ blog de kraxel].<br />
<br />
=== cirrus ===<br />
<br />
El adaptador gráfico cirrus fue el predeterminado [https://wiki.qemu.org/ChangeLog/2.2#VGA before 2.2]. [Https://www.kraxel.org/blog/2014/10/qemu-using-cirrus-considered-harmful/ no debería] utilizarse en sistemas modernos.<br />
<br />
=== none ===<br />
<br />
Esto es como un PC que no tiene tarjeta VGA en absoluto. Ni siquiera podrías acceder a ella con la opción {{ic|-vnc}}. Además, esto es diferente de la opción {{ic|-nographic}} que permite a QEMU emular una tarjeta VGA, pero deshabilita la visualización SDL.<br />
<br />
=== vnc ===<br />
<br />
Dado que usó la opción {{ic|-nographic}}, puede agregar la opción {{ic|-vnc display}} para que QEMU escuche en {{ic|display}} y redirigir la pantalla VGA a la sesión VNC . Hay un ejemplo de esto en las configuraciones de ejemplo de la sección [[#Inicio de las máquinas virtuales QEMU en el arranque]].<br />
<br />
$ qemu-system-i386 -vga std -nographic -vnc :0<br />
$ gvncviewer :0<br />
<br />
Al usar VNC, puede experimentar problemas de teclado descritos (en detalles gory) [https://www.berrange.com/posts/2010/07/04/more-than-you-or-i-ever-wanted-to-know-about-virtual-keyboard-handling/ aquí]. La solución es "no" usar la opción {{ic|-k}} en QEMU y usar {{ic|gvncviewer}} de {{Pkg|gtk-vnc}}. Ver también [https://www.mail-archive.com/libvir-list@redhat.com/msg13340.html este] mensaje publicado en la lista de correo de libvirt.<br />
<br />
== Audio ==<br />
<br />
=== Host ===<br />
<br />
El controlador de audio utilizado por QEMU se establece con la variable de entorno {{ic|QEMU_AUDIO_DRV}}:<br />
<br />
$ export QEMU_AUDIO_DRV=pa<br />
<br />
Ejecute el siguiente comando para obtener las opciones de configuración de QEMU relacionadas con PulseAudio:<br />
<br />
$ qemu-system-x86_64 -audio-help | awk '/Name: pa/' RS=<br />
<br />
Las opciones listadas se pueden exportar como variables de entorno, por ejemplo:<br />
<br />
{{bc|1=<br />
$ export QEMU_PA_SINK=alsa_output.pci-0000_04_01.0.analog-stereo.monitor<br />
$ export QEMU_PA_SOURCE=input<br />
}}<br />
<br />
=== Invitado ===<br />
<br />
Para obtener la lista de los controladores de audio de emulación compatibles:<br />
<br />
$ qemu-system-x86_64 -soundhw help<br />
<br />
Para usar (ej. {{ic|hda}}) para el invitado utilice el comando {{ic|-soundhw hda}} con QEMU.<br />
<br />
{{Note (Español)| Los controladores emulados con tarjeta gráfica de vídeo para la máquina invitada también pueden causar un problema con la calidad del sonido. Pruebe uno por uno para que funcione. Puede listar las opciones posibles con {{ic|qemu-system-x86_64 -h | grep vga}}.}}<br />
<br />
=== VirtIO sound ===<br />
<br />
VirtIO sound está disponible desde la versión 8.2.0 de QEMU. El uso es:<br />
<br />
-device virtio-sound-pci,audiodev=my_audiodev -audiodev alsa,id=my_audiodev<br />
<br />
Más información puede ser encontrada en la [https://qemu-project.gitlab.io/qemu/system/devices/virtio-snd.html documentación de QEMU].<br />
<br />
== Instalación de controladores virtio ==<br />
<br />
QEMU ofrece a los clientes la posibilidad de utilizar dispositivos bloqueados y de red paravirtualizados utilizando los controladores [https://wiki.libvirt.org/page/Virtio virtio], que proporcionan un mejor rendimiento y menores gastos generales.<br />
<br />
Un dispositivo virtio bloque requiere la opción {{ic|-drive}} en lugar del simple {{ic|-hd *}} más {{ic|1=if=virtio}}:<br />
<br />
$ qemu-system-i386 -boot order=c -drive file=''disk_image'',if=virtio<br />
<br />
{{Note (Español)|{{Ic|1=-boot order=c}} es absolutamente necesario cuando se desea arrancar desde él. No hay detección automática como con {{Ic|-hd*}}.}}<br />
<br />
* Casi de la misma manera para la red:<br />
<br />
$ qemu-system-i386 -net nic,model=virtio<br />
<br />
{{Note (Español)| Esto sólo funcionará si la máquina invitada tiene controladores para dispositivos virtio. Linux lo hace, y los controladores necesarios están incluidos en Arch Linux, pero no hay garantía de que los dispositivos virtio funcionen con otros sistemas operativos.}}<br />
<br />
=== Preparando a Arch Linux como invitado ===<br />
<br />
Para utilizar los dispositivos virtio después de instalar un invitado de Arch Linux, se deben cargar en el invitado los siguientes módulos: {{Ic|virtio}}, {{Ic|virtio_pci}}, {{Ic|virtio_blk}}, {{Ic|Virtio_net}}, y {{Ic|virtio_ring}}. Para los huéspedes de 32 bits, no es necesario el módulo "virtio" específico.<br />
<br />
Si desea arrancar desde un disco virtio, el disco ramd inicial debe contener los módulos necesarios. De forma predeterminada, esto es manejado por el gancho {{ic|autodetect}} de [[mkinitcpio]]. De lo contrario, utilice la matriz {{ic|MODULES}} en {{ic|/etc/mkinitcpio.conf}} para incluir los módulos necesarios y reconstruir el disco ramd inicial.<br />
<br />
{{hc|/etc/mkinitcpio.conf|2=<br />
MODULES="virtio virtio_blk virtio_pci virtio_net"}}<br />
<br />
Los discos Virtio se reconocen con el prefijo {{ic|'''v'''}} (ej. {{ic|'''v''' da}}, {{ic|'''v''' db}}, etc.); Por lo tanto, los cambios deben realizarse al menos en {{ic|/etc/fstab}} y {{ic|/boot/grub/grub.cfg}} al arrancar desde un disco virtio.<br />
<br />
{{Note (Español)|Cuando se hace referencia a discos por [[UUID]] en {{ic|/etc/fstab}} y bootloader, no hay nada que hacer.}}<br />
<br />
Se puede encontrar más información sobre la paravirtualización con KVM [https://www.linux-kvm.org/page/Boot_from_virtio_block_device aquí].<br />
<br />
También puede instalar {{Pkg|qemu-guest-agent}} para implementar la compatibilidad con los comandos QMP que mejorarán las capacidades de administración del hipervisor. Después de instalar el paquete, puedes habilitar e iniciar el {{ic|qemu-ga.service}}.<br />
<br />
=== Preparar un invitado de Windows ===<br />
<br />
{{Note (Español)|1=La única forma (fiable) de actualizar un cliente de Windows 8.1 a Windows 10 parece que es elegir temporalmente cpu core2duo, nx para la instalación [https://ubuntuforums.org/showthread.php?t=2289210]. Después de la instalación, puede volver a otros ajustes de la CPU (8/8/2015).}}<br />
<br />
==== Bloquear controladores de dispositivo ====<br />
<br />
===== Nueva instalación de Windows =====<br />
<br />
Windows no viene con los controladores virtio. Por lo tanto, tendrá que cargarlos durante la instalación. Hay básicamente dos maneras de hacer esto: vía disco blando o vía archivos de ISO. Ambas imágenes se pueden descargar desde el repositorio [https://fedoraproject.org/wiki/Windows_Virtio_Drivers Fedora].<br />
<br />
La opción del disquete es difícil porque necesitará presionar F6 (Shift-F6 en Windows más reciente) al inicio de la alimentación del QEMU. Esto es difícil ya que necesitas tiempo para conectar tu ventana de consola VNC. Puede intentar agregar un retardo a la secuencia de arranque. Consulte {{ic|man qemu-system}} para obtener más detalles sobre la aplicación de un retardo en el arranque.<br />
<br />
La opción ISO para cargar los controladores es la forma preferida, pero está disponible sólo en Windows Vista y Windows Server 2008 y versiones posteriores. El procedimiento consiste en cargar la imagen con controladores virtio en un dispositivo de cdrom adicional junto con el dispositivo de disco principal y el instalador de Windows:<br />
<br />
$ qemu-system-i386 ... \<br />
-drive file=''/path/to/primary/disk.img'',index=0,media=disk,if=virtio \<br />
-drive file=''/path/to/installer.iso'',index=2,media=cdrom \<br />
-drive file=''/path/to/virtio.iso'',index=3,media=cdrom \<br />
...<br />
<br />
Durante la instalación, el instalador de Windows le pedirá su clave de producto y realizará algunas comprobaciones adicionales. Cuando llegue a la "¿Dónde desea instalar Windows?" Pantalla, dará una advertencia de que no se encuentran discos. Siga las instrucciones de ejemplo siguientes (basadas en Windows Server 2012 R2 con Actualización).<br />
<br />
* Seleccione la opción {{ic|Load Drivers}}.<br />
* Desactive la casilla de "Ocultar los controladores que no son compatibles con el hardware de este equipo".<br />
* Haga clic en el botón Examinar y abra el CDROM para la virtio iso, normalmente llamada "virtio-win-XX".<br />
* Ahora vaya a {{ic|E:\viostor\[your-os]\amd64}}, seleccione y pulse OK.<br />
* Click Next<br />
<br />
Ahora debería ver sus discos virtio listados aquí, listos para ser seleccionados, formateados e instalados.<br />
<br />
===== Cambiar la máquina virtual existente de Windows para utilizar virtio =====<br />
<br />
Modificar un invitado de Windows existente para arrancar desde disco virtio es un poco difícil.<br />
<br />
Puede descargar el controlador de disco virtio desde el [https://fedoraproject.org/wiki/Windows_Virtio_Drivers repositorio de Fedora].<br />
<br />
Ahora necesita crear una nueva imagen de disco, que llene la fuerza de Windows para buscar el controlador. Por ejemplo:<br />
<br />
$ qemu-img create -f qcow2 ''fake.qcow2'' 1G<br />
<br />
Ejecute el invitado original de Windows (con el disco de inicio todavía en modo IDE) con el disco falso (en modo virtio) y un CD-ROM con el controlador.<br />
<br />
$ qemu-system-i386 -m 512 -vga std -drive file=''windows_disk_image'',if=ide -drive file=''fake.qcow2'',if=virtio -cdrom virtio-win-0.1-81.iso<br />
<br />
Windows detectará el disco falso y tratará de encontrar un controlador para ello. Si falla, vaya al '' Administrador de dispositivos '', busque la unidad SCSI con un icono de signo de exclamación (debe estar abierto), haga clic en '' Actualizar controlador '' y seleccione el CD-ROM virtual. No olvide seleccionar la casilla de verificación que dice que debe buscar directorios recursivamente.<br />
<br />
Cuando la instalación se realiza correctamente, puede apagar la máquina virtual y volver a iniciarla, ahora con el disco de arranque conectado en modo virtio:<br />
<br />
$ qemu-system-i386 -m 512 -vga std -drive file=''windows_disk_image'',if=virtio<br />
<br />
{{Note (Español)|Si encuentra la pantalla azul de Death, asegúrese de no olvidar el parámetro {{ic|-m}} y de que no arranca con virtio en lugar de ide para la unidad del sistema antes de instalar los controladores.}}<br />
<br />
==== Controladores de red ====<br />
<br />
La instalación de los controladores de red virtio es un poco más fácil, simplemente agregue el argumento {{ic|-net}} como se explicó anteriormente.<br />
<br />
$ qemu-system-i386 -m 512 -vga std -drive file=''windows_disk_image'',if=virtio -net nic,model=virtio -cdrom virtio-win-0.1-74.iso<br />
<br />
Windows detectará el adaptador de red y tratará de encontrar un controlador para ello. Si falla, vaya al ''Administrador de dispositivos'', localice el adaptador de red con un icono de signo de exclamación (debe estar abierto), haga clic en ''Actualizar controlador'' y seleccione el CD-ROM virtual. No olvide seleccionar la casilla de verificación que dice que debe buscar directorios recursivamente.<br />
<br />
=== Preparación de FreeBSD como invitado ===<br />
<br />
Instale el puerto {{ic|emulators/virtio-kmod}} si está utilizando FreeBSD 8.3 o posterior hasta 10.0-CURRENT donde están incluidos en el kernel. Después de la instalación, añada lo siguiente a su archivo {{ic|/boot/loader.conf}}:<br />
<br />
{{bc|<nowiki><br />
virtio_loader="YES"<br />
virtio_pci_load="YES"<br />
virtio_blk_load="YES"<br />
if_vtnet_load="YES"<br />
virtio_balloon_load="YES"<br />
</nowiki>}}<br />
<br />
A continuación, modifique su {{ic|/etc/fstab}} haciendo lo siguiente:<br />
<br />
{{bc|<nowiki><br />
sed -i bak "s/ada/vtbd/g" /etc/fstab<br />
</nowiki>}}<br />
<br />
Y verificar que {{ic|/etc/fstab}} es consistente. Si algo sale mal, sólo arranque en un CD de rescate y copie {{ic|/etc/fstab.bak}} de vuelta a {{ic|/etc/fstab}}.<br />
<br />
== Consejos y trucos ==<br />
<br />
=== Inicio de las máquinas virtuales QEMU en el arranque ===<br />
<br />
==== Con libvirt ====<br />
<br />
Si se configura una máquina virtual con [[libvirt]], se puede configurar a través de la interfaz gráfica de usuario de virt-manager para iniciar en el arranque de host, accediendo a las Opciones de arranque de la máquina virtual y seleccionando "Inicio de la máquina virtual en el arranque del host".<br />
<br />
==== Script personalizado ====<br />
<br />
Para ejecutar QEMU VMs al arrancar, puede usar las siguientes unidades systemd y config.<br />
<br />
{{hc|/etc/systemd/system/qemu@.service|<nowiki><br />
[Unit]<br />
Description=QEMU virtual machine<br />
<br />
[Service]<br />
Environment="type=system-x86_64" "haltcmd=kill -INT $MAINPID"<br />
EnvironmentFile=/etc/conf.d/qemu.d/%i<br />
ExecStart=/usr/bin/env qemu-${type} -name %i -nographic $args<br />
ExecStop=/bin/sh -c ${haltcmd}<br />
TimeoutStopSec=30<br />
KillMode=none<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
{{Note (Español)|De acuerdo con {{ic|systemd.service (5)}} y {{ic|systemd.kill (5)}} man, es necesario utilizar {{ic|1=KillMode=none}} opción. De lo contrario, el proceso qemu principal se eliminará inmediatamente después de que se cierre el comando {{ic|ExecStop}} (simplemente hace eco de una cadena) y su sistema de búsqueda no podrá apagarse correctamente.}}<br />
<br />
A continuación, cree archivos de configuración por-VM, denominados {{ic|/etc/conf.d/qemu.d/''vm_name''}}, con las siguientes variables establecidas:<br />
<br />
; type<br />
: QEMU binary to call. If specified, will be prepended with {{ic|/usr/bin/qemu-}} and that binary will be used to start the VM. I.e. you can boot e.g. {{ic|qemu-system-arm}} images with {{ic|1=type="system-arm"}}.<br />
; args<br />
: QEMU command line to start with. Will always be prepended with {{ic|-name ${vm} -nographic}}.<br />
; haltcmd<br />
: Command to shut down a VM safely. I am using {{ic|-monitor telnet:..}} and power off my VMs via ACPI by sending {{ic|system_powerdown}} to monitor. You can use SSH or some other ways.<br />
<br />
Ejemplo de configuración:<br />
<br />
{{hc|/etc/conf.d/qemu.d/one|<nowiki><br />
type="system-x86_64"<br />
<br />
args="-enable-kvm -m 512 -hda /dev/mapper/vg0-vm1 -net nic,macaddr=DE:AD:BE:EF:E0:00 \<br />
-net tap,ifname=tap0 -serial telnet:localhost:7000,server,nowait,nodelay \<br />
-monitor telnet:localhost:7100,server,nowait,nodelay -vnc :0"<br />
<br />
haltcmd="echo 'system_powerdown' | nc localhost 7100" # or netcat/ncat<br />
<br />
# You can use other ways to shut down your VM correctly<br />
#haltcmd="ssh powermanager@vm1 sudo poweroff"<br />
</nowiki>}}<br />
<br />
{{hc|/etc/conf.d/qemu.d/two|<nowiki><br />
args="-enable-kvm -m 512 -hda /srv/kvm/vm2.img -net nic,macaddr=DE:AD:BE:EF:E0:01 \<br />
-net tap,ifname=tap1 -serial telnet:localhost:7001,server,nowait,nodelay \<br />
-monitor telnet:localhost:7101,server,nowait,nodelay -vnc :1"<br />
<br />
haltcmd="echo 'system_powerdown' | nc localhost 7101"<br />
</nowiki>}}<br />
<br />
Para establecer qué máquinas virtuales se iniciarán al arrancar, habilite la unidad de [[systemd]] {{ic|qemu@''vm_name''.service}}.<br />
<br />
=== Integración del ratón ===<br />
<br />
Para evitar que el ratón sea agarrado al hacer clic en la ventana del sistema operativo invitado, agregue la opción {{ic|-usbdevice tablet}}. Esto significa que QEMU puede reportar la posición del ratón sin tener que agarrar el ratón. Esto también anula la emulación de ratón PS/2 cuando se activa. Por ejemplo:<br />
<br />
$ qemu-system-i386 -hda ''disk_image'' -m 512 -vga std -usbdevice tablet<br />
<br />
If that does not work, try the tip at [[#El cursor del ratón está nervioso o errático]].<br />
<br />
=== Dispositivo USB del host de paso ===<br />
<br />
Para acceder al dispositivo físico USB conectado al host desde la VM, puede utilizar la opción: {{ic|-usbdevice host:''vendor_id'':''product_id''}}.<br />
<br />
Puedes encontrar {{ic|vendor_id}} y {{ic|product_id}} de tu dispositivo con el comando {{ic|lsusb}}.<br />
<br />
Puesto que el chipset I440FX por defecto emulado por qemu cuentan con un solo controlador UHCI (USB 1), la opción {{ic|-usbdevice}} intentará conectar su dispositivo físico a él. En algunos casos esto puede causar problemas con los dispositivos más nuevos. Una posible solución es emular el chipset [https://wiki.qemu.org/Features/Q35 ICH9], que ofrece un controlador EHCI que soporta hasta 12 dispositivos, usando la opción {{ic|1=-machine type=q35}}.<br />
<br />
Una solución menos invasiva es emular un controlador EHCI (USB 2) o XHCI (USB 3) con la opción {{ic | 1 = -device usb-ehci, id = ehci}} o {{ic|1=-device nec -usb-xhci, id=xhci}} respectivamente y luego adjuntar su dispositivo físico con la opción {{ic|1=-device usb-host,..}} como sigue:<br />
<br />
-device usb-host,bus='''controller_id'''.0,vendorid=0x'''vendor_id''',productid=0x'''product_id'''<br />
<br />
También puede agregar la configuración {{ic|1=..., port =''<n>''}} a la opción anterior para especificar en qué puerto físico del controlador virtual que desea conectar su dispositivo, útil en El caso que desea agregar varios dispositivos usb a la VM.<br />
<br />
{{Note (Español)|Si encuentra errores de permisos al ejecutar QEMU, consulte [[udev#About udev rules]] para obtener información sobre cómo establecer permisos del dispositivo.}}<br />
<br />
=== Habilitar KSM ===<br />
<br />
Kernel Samepage Merging (KSM) es una característica del kernel de Linux que permite que una aplicación se registre con el kernel para que sus páginas se combinen con otros procesos que también se registren para que sus páginas se fusionen. El mecanismo KSM permite a las máquinas virtuales invitadas compartir páginas entre sí. En un entorno donde muchos de los sistemas operativos invitados son similares, esto puede resultar en ahorros significativos de memoria.<br />
<br />
Para activar KSM, simplemente ejecute:<br />
<br />
# echo 1 > /sys/kernel/mm/ksm/run<br />
<br />
Para hacerlo permanente, puede utilizar [[Systemd#systemd-tmpfiles - temporary files|archivos temporales de systemd]]:<br />
<br />
{{hc|/etc/tmpfiles.d/ksm.conf|<br />
w /sys/kernel/mm/ksm/run - - - - 1<br />
}}<br />
<br />
Si KSM está en ejecución y hay páginas que se van a fusionar (es decir, al menos dos máquinas virtuales similares se están ejecutando), entonces {{ic|/sys/kernel/mm/ksm/pages_shared}} debería ser distinto de cero. Consulte https://docs.kernel.org/vm/ksm.html{{Dead link (Español)|2022|09|22|status=404}} para obtener más información.<br />
<br />
{{Tip (Español)|Una manera fácil de ver lo bien que KSM está realizando es simplemente imprimir el contenido de todos los archivos de ese directorio: {{bc|$ grep./Sys/kernel/mm/ksm/*}}}}<br />
<br />
=== Multi-monitor support ===<br />
<br />
El controlador QXL de Linux soporta cuatro cabezas (pantallas virtuales) de forma predeterminada. Esto se puede cambiar a través del parámetro kernel {{ic | 1 = qxl.heads = N}}.<br />
<br />
El tamaño de memoria VGA predeterminado para los dispositivos QXL es de 16M (el tamaño de la VRAM es de 64M). Esto no es suficiente si desea habilitar dos monitores 1920x1200 ya que requiere 2 × 1920 × 4 (profundidad de color) × 1200 = 17.6 MiB memoria VGA. Esto se puede cambiar reemplazando {{ic|-vga qxl}} por {{ic|1=-vga none -device qxl-vga, vgamem_mb=32}}. Si alguna vez incrementas vgamem_mb más allá de 64M, también debes aumentar la opción {{ic|vram_size_mb}}.<br />
<br />
=== Copiar y pegar ===<br />
<br />
Para poder copiar y pegar entre el host y el invitado, debe habilitar el canal de comunicación del agente de especias. Requiere agregar un dispositivo virtio-serial al huésped, y abrir un puerto para el vdagent de la especia. También es necesario instalar el spice vdagent en invitado ({{Pkg|spice-vdagent}} para invitados de Arch, [https://www.spice-space.org/download.html Herramientas para invitados de Windows] para invitados de Windows). Asegúrese de que el agente se está ejecutando (y para el futuro, se iniciará automáticamente).<br />
<br />
Inicie QEMU con las siguientes opciones:<br />
<br />
$ qemu-system-i386 -vga qxl -spice port=5930,disable-ticketing -device virtio-serial-pci -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
La opción {{ic|-device virtio-serial-pci}} añade el dispositivo virtio-serial, {{ic|1=-device virtserialport, chardev=spicechannel0, nombre=com.redhat.spice.0}} abre un puerto Para spice vdagent en ese dispositivo y {{ic|1=-chardev spicevmc, id=spicechannel0, nombre=vdagent}} añade un spicevmc chardev para ese puerto.<br />
<br />
Es importante que la opción {{ic|1=chardev=}} del dispositivo {{ic|virtserialport}} coincida con la opción {{ic|1=id=}} dada a la opción {{ic | chardev}} ({{Ic|spicechannel0}} en este ejemplo). También es importante que el nombre del puerto sea {{ic|com.redhat.spice.0}}, ya que es el espacio de nombres donde vdagent está buscando en el invitado. Y finalmente, especifique {{ic|1=name=vdagent}} para que spice sepa para qué sirve este canal.<br />
<br />
=== Notas específicas de Windows ===<br />
<br />
QEMU puede ejecutar cualquier versión de Windows desde Windows 95 a través de Windows 10.<br />
<br />
Es posible ejecutar [[Windows PE]] en QEMU.<br />
<br />
==== Inicio rápido ====<br />
<br />
{{Note (Español)|Se requiere una cuenta de administrador para cambiar la configuración de energía.}}<br />
Para invitados de Windows 8 (o posteriores), es mejor desactivar "Activar inicio rápido (recomendado)" en Opciones de energía del Panel de control, ya que hace que el invitado se bloquee durante cada arranque.<br />
<br />
El inicio rápido también puede necesitar deshabilitarse para que los cambios en la opción {{ic|-smp}} se apliquen correctamente.<br />
<br />
==== Protocolo de escritorio remoto ====<br />
<br />
Si utiliza un invitado de MS Windows, puede utilizar RDP para conectarse a su VM invitada. Si está utilizando una VLAN o no está en la misma red que el invitado, utilice:<br />
<br />
$ qemu-system-i386 -nographic -net user,hostfwd=tcp::5555-:3389<br />
<br />
A continuación, conéctese con {{Pkg|rdesktop}} ó {{Pkg|freerdp}} al invitado. Por ejemplo:<br />
<br />
$ xfreerdp -g 2048x1152 localhost:5555 -z -x lan<br />
<br />
== Solución de problemas ==<br />
<br />
=== La máquina virtual virtual corre muy lento ===<br />
<br />
Hay algunas técnicas que se pueden usar para implementar rendimiento en la máquina virtual, por ejemplo:<br />
<br />
* Use la opción {{ic|-cpu host}} para hacer que QEMU emule la CPU del host. Si no se hace esto, podría intentar emular un CPU más genérico.<br />
* Especialmente para los invitados de Windows, habilite [https://blog.wikichoon.com/2014/07/enabling-hyper-v-enlightenments-with-kvm.html Iluminaciones de Hyper-V]: {{ic|1=-Host de la CPU, hv_relaxed, hv_spinlocks=0x1fff, hv_vapic, hv_time}}.<br />
* Si la máquina host tiene varias CPUs, asigne al invitado más CPUs usando la opción {{ic|-smp}}.<br />
* Asegúrese de haber asignado a la máquina virtual suficiente memoria. De forma predeterminada, QEMU sólo asigna 128 MiB de memoria a cada máquina virtual. Utilice la opción {{ic|-m}} para asignar más memoria. Por ejemplo, {{ic|-m 1024}} ejecuta una máquina virtual con 1024 MiB de memoria.<br />
* Utilice KVM si es posible: agregue {{ic|1=-machine type=pc, accel=kvm}} al comando de arranque QEMU que utilice.<br />
* Si es compatible con los controladores del sistema operativo invitado, utilice [https://wiki.libvirt.org/page/Virtio virtio] para dispositivos de red y/o bloque. Por ejemplo:<br />
$ qemu-system-i386 -net nic, model=virtio -net tap, if=tap0, script=no-drive file=''disk_image'',media=disco, if=virtio<br />
* Utilizar dispositivos TAP en lugar de redes en modo usuario. Consulte [[#Tap de red con QEMU]].<br />
* Si el sistema operativo invitado está haciendo escritura pesada en su disco, puede beneficiarse de ciertas opciones de montaje en el sistema de archivos del host. Por ejemplo, puede montar un [[Ext4|sistema de archivos ext4]] con la opción {{ic|1=barrier=0}}. Debe leer la documentación de las opciones que cambie porque a veces las opciones de mejora de rendimiento para los sistemas de archivos tienen el costo de integridad de los datos.<br />
* Si tiene una imagen de disco sin procesar, puede deshabilitar la caché:<br />
$ qemu-system-i386 -drive file=''disk_image'', if=virtio, cache=none<br />
* Utilice el nativo Linux AIO:<br />
$ qemu-system-i386 -drive file=''disk_image'', if=virtio, aio=native<br />
* Si utiliza una imagen de disco qcow2, el rendimiento de E/S se puede mejorar considerablemente al garantizar que el caché L2 es de tamaño suficiente. La fórmula [https://blogs.igalia.com/berto/2015/12/17/improving-disk-io-performance-in-qemu-2-5-with-the-qcow2-l2-cache/] para calcular La caché L2 es: l2_cache_size = disk_size * 8 / cluster_size. Suponiendo que la imagen qcow2 se creó con el tamaño de clúster predeterminado de 64 K, esto significa que para cada 8 GB de tamaño de la imagen qcow2, 1 MB de caché L2 es mejor para el rendimiento. QEMU utiliza sólo 1 MB por defecto; Especificar una caché más grande se hace en la línea de comandos QEMU. Por ejemplo, para especificar 4 MB de caché (adecuado para un disco de 32 GB con un tamaño de clúster de 64 KB):<br />
$ qemu-system-i386 -drive file=''disk_image'',format=qcow2, l2-cache-size=4M<br />
* Si está ejecutando varias máquinas virtuales al mismo tiempo que todas tienen el mismo sistema operativo instalado, puede ahorrar memoria al habilitar [[wikipedia: Kernel_SamePage_Merging_ (KSM)|kernel de la misma página de fusión]]. Consulte [[#Habilitar KSM]].<br />
* En algunos casos, la memoria se puede recuperar de correr máquinas virtuales ejecutando un controlador de globo de memoria en el sistema operativo invitado y lanzando QEMU con la opción {{ic|-balloon virtio}}.<br />
* Es posible utilizar una capa de emulación para un controlador ICH-9 AHCI (aunque puede ser inestable). La emulación AHCI soporta [[Wikipedia: Native_Command_Queuing|NCQ]], por lo que varias peticiones de lectura o escritura pueden estar pendientes al mismo tiempo:<br />
$ qemu-system-i386 -drive id=disc, file=''disk_image'', if=none -device ich9-ahci, id=ahci -device ide-drive, drive=disk, bus=ahci.0<br />
<br />
Mira https://www.linux-kvm.org/page/Tuning_KVM para más información.<br />
<br />
=== El cursor del ratón está nervioso o errático ===<br />
<br />
Si el cursor "brinca" descontroladamente, podría ayudar ingresar este comando en la terminal antes de iniciar QEMU<br />
<br />
$ export SDL_VIDEO_X11_DGAMOUSE=0<br />
<br />
Si funciono, puedes agregarlo a tu {{ic|~/.bashrc}} archivo.<br />
<br />
=== El cursor no es visible ===<br />
<br />
Añade {{ic|-show-cursor}} a las opciones de QEMU para poder ver el cursor.<br />
<br />
Si persiste, asegurate de configurar la pantalla apropiadamente<br />
<br />
Por ejemplo: {{ic|-vga qxl}}<br />
<br />
=== No se puede mover / adjuntar el cursor ===<br />
<br />
Reemplaza {{ic|-usbdevice tablet}} con {{ic|-usb}} como opción en QEMU.<br />
<br />
=== El teclado parece roto ó las teclas de flecha no funcionan ===<br />
<br />
Probablemente notarás que algunas de tus teclas no funcionan ó "presionan" la tecla equivocada (en particular, las flechas), preferentemente, necesitas especificar la distribución de tu teclado como una opción. La distribución del teclado puede encontrarse en {{ic|/usr/share/qemu/keymaps}}.<br />
<br />
$ qemu-system-i386 -k ''keymap'' ''disk_image''<br />
<br />
=== Pantalla de invitado estirada en el tamaño de la ventana ===<br />
<br />
Para restarurar el tamaño por defecto de la ventanta, presiona {{ic|Ctrl+Alt+u}}.<br />
<br />
=== ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy ===<br />
<br />
Si un mensaje de error como este es listado en el arranque de QEMU con la opción {{ic|-enable-kvm}}:<br />
<br />
ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy<br />
failed to initialize KVM: Device or resource busy<br />
<br />
Significa que otro [[hypervisor]] está actualmente activo. No se recomienda ó no es poible correr varios hypervisores en paralelo.<br />
<br />
=== Mensaje de error libgfapi ===<br />
<br />
El mensaje de error listado en el arranque:<br />
<br />
Failed to open module: libgfapi.so.0: cannot open shared object file: No such file or directory<br />
<br />
No es un problema, sólo significa que hace falta la dependencia opcional de GlusterFS<br />
<br />
=== Kernel panic en entornos live ===<br />
<br />
Si inicia un sistema en vivo (ó bootea uno) podría encontrar esto:<br />
<br />
end Kernel panic - not syncing: VFS: Unable to mount root fs on unknown block(0,0)<br />
<br />
Ó algún otro proceso de arranque (ej. no se puede desempaquetar initramfs, no puede iniciar un servicio foo).<br />
<br />
Intente iniciar la Máquina Virtual con el {{ic|-m VALOR}} switch y un tamaño apropiado de RAM, si la RAM es muy poca probablemente encontrará problemas similares a los anteriores.<br />
<br />
== Ver también ==<br />
<br />
* [https://qemu.org Sitio web oficial de QEMU]<br />
* [https://www.linux-kvm.org Sitio web oficial de KVM]<br />
* [https://web.archive.org/web/20200514080826/https://qemu.weilnetz.de/doc/qemu-doc.html Documentación para el usuario del emulador QEMU] (en inglés)<br />
* [https://en.wikibooks.org/wiki/QEMU Wikilibro de QEMU] (en inglés)<br />
* [http://alien.slackbook.org/dokuwiki/doku.php?id=slackware:qemu Virtualización de hardware con QEMU por AlienBOB (última actualización en 2008) (en inglés)<br />
* [http://blog.falconindy.com/articles/build-a-virtual-army.html Construyendo un ejército virtual] por Falconindy (en inglés)<br />
* [https://git.qemu.org/?p=qemu.git;a=tree;f=docs Últimos documentos]<br />
* [https://qemu.weilnetz.de/ QEMU en Windows]<br />
* [[wikipedia:Qemu|Wikipedia]]<br />
* [https://wiki.debian.org/QEMU QEMU - Wiki de Debian] (en inglés)<br />
* [https://people.gnome.org/~markmc/qemu-networking.html QEMU Networking on gnome.org]{{Dead link (Español)|2022|09|22|status=404}}<br />
* [http://bsdwiki.reedmedia.net/wiki/networking_qemu_virtual_bsd_systems.html Red virtual de QEMU en sistemas BSD] (en inglés)<br />
* [https://www.gnu.org/software/hurd/hurd/running/qemu.html QEMU on gnu.org]<br />
* [https://wiki.freebsd.org/qemu QEMU en FreeBSD como host] (en inglés)</div>Malcontenthttps://wiki.archlinux.org/index.php?title=QEMU_(Espa%C3%B1ol)&diff=796060QEMU (Español)2024-01-04T20:49:31Z<p>Malcontent: Fix Spanish translation</p>
<hr />
<div>[[Category:Emulation (Español)]]<br />
[[Category:Hypervisors (Español)]]<br />
[[de:QEMU]]<br />
[[en:QEMU]]<br />
[[fr:QEMU]]<br />
[[ja:QEMU]]<br />
[[zh-hans:QEMU]]<br />
{{Bad translation (Español)|No updates since 2017-01-12, English page has seen major changes since.}}<br />
{{TranslationStatus (Español)|QEMU|2017-01-12|463282}}<br />
{{Related articles start (Español)}}<br />
{{Related|:Category:Hypervisors}}<br />
{{Related|Libvirt}}<br />
{{Related articles end}}<br />
<br />
De acuerdo con [https://wiki.qemu.org/Main_Page la wiki de QEMU], "QEMU es un emulador genérico y de código abierto de máquinas virtuales."<br />
<br />
Cuando se utiliza como un emulador de máquina, QEMU puede correr sistemas operativos y programas hechos para una máquina en particular (por ej. una placa ARM) en una máquina diferente (e.j. tu PC x86). Usando la traducción dinámica, se consigue un rendimiento muy bueno.<br />
<br />
QEMU puede usar hipervisores como [[Xen]] o [[KVM]] para utilizar las extensiones del procesador para la virtualización. Cuando se utiliza como virtualizador, QEMU alcanza un performance cercano a el rendimiento nativo ejecutando el código de invitado directamente en el CPU host.<br />
<br />
== Instalación ==<br />
<br />
[[Help:Reading (Español)#Instalación de paquetes|Instale]] el paquete {{Pkg|qemu-desktop}} (ó {{Pkg|qemu-base}} para la versión sin GUI) y los paquetes opcionales para tus necesidades:<br />
<br />
* {{Pkg|qemu-emulators-full}} - Soporte extra para arquitecturas<br />
* {{Pkg|qemu-block-gluster}} - Soporte para bloque glusterfs <br />
* {{Pkg|qemu-block-iscsi}} - Soporte para bloque iSCSI <br />
* {{Pkg|qemu-block-rbd}}{{Broken package link (Español)|package not found}} - Soporte para bloque RBD <br />
* {{Pkg|samba}} - SMB/ Soporte para servidor CIFS<br />
<br />
== front-ends para QEMU ==<br />
<br />
A diferencia de otros programas de virtualización como [[VirtualBox]] y [[VMware]], QEMU no proporciona una interfaz gráfica de usuario para administrar máquinas virtuales (a parte de la ventana que aparece cuando se ejecuta una máquina virtual), tampoco proporciona una forma de crear una máquina virtual persistente con valores guardados. Todos los parámetros para ejecutar una máquina virtual deben especificarse en la línea de comandos en cada puesta en marcha, a menos que haga un script personalizadp para iniciar su máquina(s) virtual. Sin embargo, hay varios front-end GUI para QEMU: <br />
<br />
* {{AUR|qemu-launcher}}<br />
* {{AUR|qtemu}}<br />
* {{AUR|aqemu}}<br />
<br />
front-ends con soporte para QEMU están disponibles por [[libvirt]].<br />
<br />
== Creando un nuevo sistema virtualizado ==<br />
<br />
=== Creando una imagen de disco duro ===<br />
<br />
{{Tip (Español)|Véase la [https://en.wikibooks.org/wiki/QEMU/Images Wiki de QEMU] para más información sobre imágenes de QEMU.}}<br />
<br />
Para ejecutar QMEU necesitarás una imagen de disco duro, a menos que estés cargando un sistema en vivo desde el CD-ROM ó la red (y no para instalar un sistema operativo en una imagen de disco duro). Una imagen de disco es un archivo que almacena los contenidos del disco duro emulado.<br />
<br />
Una imagen de disco puede ser en "crudo", de manera que, literalemte, byte por byte es lo mismo que el cliente ve, y siempre utilizará toda la capacidad del disco duro del disco duro invitado en el host. Este método proporciona la menor sobrecarga de Entrada / Salida, pero puede desperdiciar una gran cantidad de espacio, ya que el espacio no utilizado por el invitado no se puede utilizar en el host. <br />
<br />
Por otra parte, la imagen de disco duro puede estar en un formato tal como el de ''qcow2'' el cuál únicamente asigna espacio a el archivo de la imagen cuando el SO invitado está escribiendo en los sectores del disco virtual. La imagen aparece como el tamaño total del sistema operativo huésped, a pesar que puede tomar hasta una cantidad muy pequeña de espacio en el sistema host. El uso de este formato en lugar de el "crudo" probablemente afecte el rendimiento. <br />
<br />
QEMU proporciona el {{ic|qemu-img}} comando para crear imagenes de disco.<br />
Por ejemplo, para crear una imagen de 4GB en formato "crudo":<br />
<br />
$ qemu-img create -f raw ''image_file'' 4G<br />
<br />
Se puede uiltizar {{ic|-f qcow2}} para crear un disco ''qcow2'' en su lugar. <br />
<br />
{{Note (Español)|También puedes simplemente crear una imagen "cruda" meidante la creación de un archivo del tamaño necesitado usando {{ic|dd}} ó {{ic|fallocate}}.}}<br />
<br />
{{Warning (Español)|Si almacenas una imágen de disco en un sistema de archivos [[Btrfs (Español)|Btrfs]], deberías considerar deshabilitar [[Btrfs (Español)#Copy-on-Write (CoW)|Copy-on-Write]] para el directorio antes de crear imágenes.}}<br />
<br />
==== Superposición de imágenes de almacenamiento ====<br />
<br />
Puede crear una imagen de almacenamiento una vez (la imagen de respaldo) y hacer que QEMU mantenga mutaciones a esta imagen en una imagen de superposición. Esto le permite volver a un estado anterior de esta imagen de almacenamiento. Puede volver a crear una nueva imagen de superposición en el momento en que desea revertir en función de la imagen de respaldo original.<br />
<br />
Para crear una imagen de superposición, ingrese el comando:<br />
<br />
$ qemu-img create -o backing_file=''img1.raw'',backing_fmt=''raw'' -f ''qcow2'' ''img1.cow''<br />
<br />
Después de eso, puede ejecutar su máquina virtual como de costumbre (ver [[#Ejecución del sistema virtualizado]]):<br />
<br />
$ qemu-system-x86_64 ''img1.cow''<br />
<br />
La imagen de respaldo se dejará intacta y se registrarán mutaciones en este almacenamiento en el archivo de imagen de superposición.<br />
<br />
Cuando cambia la ruta de acceso a la imagen de respaldo, se requiere reparación.<br />
<br />
{{Warning (Español)|La ruta del sistema de archivos absoluto de la imagen de respaldo se almacena en el archivo de imagen de superposición (binario)). Cambiar el trayecto de la imagen de respaldo requiere un esfuerzo.}}<br />
<br />
Asegúrese de que la ruta de la imagen de respaldo original sigue conduciendo a esta imagen. Si es necesario, haga un enlace simbólico en la ruta original a la nueva ruta. A continuación, emita un comando como:<br />
<br />
$ qemu-img rebase -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
A su discreción, usted puede alternativamente realizar un rebase 'inseguro' donde no se comprueba la ruta anterior a la imagen de respaldo:<br />
<br />
$ qemu-img rebase -u -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
==== Cambiar el tamaño de una imagen ====<br />
<br />
{{Warning (Español)|Cambiar el tamaño de una imagen que contiene un sistema de arranque NTFS podría hacer el sistema operativo instalado '''no arrancable'''. Para una explicación completa y solucioón alternativa mira [https://web.archive.org/web/20180319230757/http://tjworld.net/wiki/Howto/ResizeQemuDiskImages].}}<br />
<br />
El ejecutable {{ic|qemu-img}} tiene la opción {{ic|resize}}, que permite redimensionar fácilmente una imagen de disco duro. Funciona tanto para ''raw'' como para ''qcow2''. Por ejemplo, para aumentar el espacio de imagen en 10GB, ingresa:<br />
<br />
$ qemu-img resize ''disk_image'' +10G<br />
<br />
Después de ampliar la imagen de disco, debe utilizar el sistema de archivos y las herramientas de particionamiento dentro de la máquina virtual para comenzar a utilizar el nuevo espacio. Al reducir una imagen de disco, primero debe reducir los sistemas de archivos y los tamaños de partición asignados usando el sistema de archivos y las herramientas de partición dentro de la máquina virtual y luego reducir la imagen del disco en consecuencia, de lo contrario reducir la imagen del disco resultará en ¡pérdida de datos!<br />
<br />
=== Preparando el medio de instalación ===<br />
<br />
Para instalar un sistema operativo en su imagen de disco, necesita el medio de instalación (por ejemplo, disco óptico, unidad USB o imagen ISO) para el sistema operativo. El soporte de instalación no debe montarse porque QEMU accede directamente al medio.<br />
<br />
{{Tip (Español)|Si utiliza un disco óptico, es una buena idea volcar primero los medios a un archivo porque esto mejora el rendimiento y no requiere que tenga acceso directo a los dispositivos (es decir, puede ejecutar QEMU como un usuario normal sin tener Para cambiar permisos de acceso en el archivo de dispositivo del medio). Por ejemplo, si el nodo de dispositivo de CD-ROM tiene el nombre {{ic|/dev/cdrom}}, puede volcarlo a un archivo de comandos: {{bc|1=$ dd if=/dev/cdrom of=''Cd_image.iso''}}}}<br />
<br />
=== Instalando el sistema operativo ===<br />
<br />
Esta es la primera vez que necesitará iniciar el emulador. Para instalar el sistema operativo en la imagen de disco, debe adjuntar la imagen de disco y el medio de instalación a la máquina virtual y hacer que arranque desde el soporte de instalación.<br />
<br />
Por ejemplo, en invitados i386, para instalar desde un archivo ISO de arranque como CD-ROM y una imagen de disco sin formato:<br />
<br />
$ qemu-system-x86_64 -cdrom ''iso_image'' -boot order=d -drive file=''disk_image'',format=raw<br />
<br />
Consulte {{ic | qemu (1)}} para obtener más información sobre cómo cargar otros tipos de medios (como disquetes, imágenes de disco o unidades físicas) y [[#Ejecución del sistema virtualizado]] para otras opciones útiles.<br />
<br />
Una vez que el sistema operativo haya finalizado de instalar, la imagen de QEMU se puede iniciar directamente (ver [[#Ejecución del sistema virtualizado]]).<br />
<br />
{{Warning (Español)|De forma predeterminada, sólo se asignan 128 MB de memoria a la máquina. La cantidad de memoria se puede ajustar con el interruptor {{ic | -m}}, por ejemplo {{ic | -m 512M}} o {{ic | -m 2G}}.}}<br />
<br />
{{Tip (Español)|<br />
* En lugar de especificar {{ic | 1 = -boot order = x}}, algunos usuarios pueden sentirse más cómodos usando un menú de arranque: {{ic | 1 = -boot menu = on}}, al menos durante la configuración y la experimentación.<br />
* Si necesita reemplazar disquetes o CD como parte del proceso de instalación, puede usar el monitor de la máquina QEMU (presione {{ic | Ctrl + Alt + 2}} en la ventana de la máquina virtual) para quitar y conectar dispositivos de almacenamiento a un máquina virtual. Escriba {{ic | info block}} para ver los dispositivos de bloque y use el comando {{ic | change}} para intercambiar un dispositivo. Pulse {{ic | Ctrl + Alt + 1}} para volver a la máquina virtual.}}<br />
<br />
== Ejecución del sistema virtualizado ==<br />
<br />
Los binarios {{ic|qemu-system-*}} (por e.j. {{ic|qemu-system-i386}} ó {{ic|qemu-system-x86_64}}, dependiendo de la arquitectura del huésped) se usan para ejecutar el sistema virtualizado. El uso es:<br />
<br />
$ qemu-system-x86_64 ''options'' ''disk_image''<br />
<br />
Las opciones son las mismas para todos los binarios {{ic|qemu-system-*}}, mira {{ic|qemu(1)}} para más información sobre todas las opciones.<br />
<br />
Por defecto, QEMU mostrará la salida de video de la máquina virtual en una ventana. Una cosa a considerar: al hacer click dentro de la ventana de QMEU, el puntero del cursor será capturado. Para liberarlo presione {{ic|Ctrl+Alt+g}}.<br />
<br />
{{Warning (Español)|QEMU nunca debe ejecutarse como root. Si se debe iniciar en root, deberá usar la opción {{ic|-runas}} para que QEMU utilice privilegios de root.}}<br />
<br />
=== Activar KVM ===<br />
<br />
KVM debe ser soportado por su procesador y kernel, y necesariamente los [[kernel modules (Español)|módulos del kernel]] deben ser cargados. Mira [[KVM]] para más información.<br />
<br />
Para iniciar QEMU en modo KVM, adjunta {{ic|-enable-kvm}} a las opciones de inicio adicionales. Para verificar si KVM está activado para ejecutar una máquina virtual, ingresa a la wiki de QEMU [https://en.wikibooks.org/wiki/QEMU/Monitor Monitor], usando {{ic|Ctrl+Alt+Shift+2}}, e ingresando {{ic|info kvm}}. <br />
<br />
{{Note (Español)|<br />
* Si inicia su máquina virtual con una herramienta GUI y experimenta un rendimiento muy malo, debe verificar el soporte adecuado de KVM. <br />
* KVM necesita activarse en orden de iniciar adecuadamente Windows 7 y Windows 8 sin ''pantallazo azul''.<br />
}}<br />
<br />
=== Habilitar soporte IOMMU (Intel VT-d/AMD-Vi) ===<br />
<br />
Usando IOMMU (unidad de gestión de memoria de entrada y salida) se abre a las caraterísticas como el paso del PCI y la protección de la memoria de dispositivos defectuosos o maliciosos, mira [[wikipedia:Input-output memory management unit#Advantages]] y [https://www.quora.com/Memory-Management-computer-programming/Could-you-explain-IOMMU-in-plain-English Memory Management (computer programming): Could you explain IOMMU in plain English?].<br />
<br />
Para habilitar IOMMU:<br />
#Asegure que AMD-Vi/Intel VT-d es soportado por el CPU y es habilitado en la configuración de BIOS.<br />
#Agregue {{ic|1=intel_iommu=on}} si tienes un procesador Intel ó {{ic|1=amd_iommu=on}} si tienes un procesador AMD en los parámetros del kernel ([[kernel parameters]])<br />
#Reinicie y asegure que IOMMU está habilitado verificando {{ic|dmesg}} para {{ic|DMAR}}: {{ic|[0.000000] DMAR: IOMMU enabled}}<br />
#Añade {{ic|-device intel-iommu}} para crear el dispositivo IOMMU:<br />
<br />
$ qemu-system-x86_64 '''-enable-kvm -machine q35 -device intel-iommu''' -cpu host ..<br />
<br />
== Mover datos entre el host y el Sistema Operativo huésped ==<br />
<br />
=== Red ===<br />
<br />
Los datos pueden compartirse entre el host y el sistema operativo huésped usando cualquier protocolo de red que pueda transferir archivos, como [[NFS]], [[SMB]], [[Wikipedia:Network Block Device|NBD]], HTTP, [[Very Secure FTP Daemon|FTP]], ó [[SSH]], siempre que haya configurado la red apropiadamente y haya habilitado los servicios apropiados. <br />
<br />
La red por defecto del modo de usuario permite al huésped acceder al sistema operativo host en la dirección IP 10.0.2.2. Todos los servidores que se estén ejecutando en el sistema operativo anfitrión, como un servidor SSH o un servidor SMB, estarán accesibles en esta dirección IP. Así que en los invitados, puede montar los directorios exportados en el host a través de [[SMB]] o [[NFS]], o puede acceder al servidor HTTP del host, etc.<br />
No será posible que el sistema operativo anfitrión acceda a los servidores que se ejecutan en el sistema operativo invitado, pero esto puede hacerse con otras configuraciones de red (consulte [[#Tap de red con QEMU]]).<br />
<br />
=== Servidor SMB incorporado de QEMU ===<br />
<br />
La documentación de QEMU dice que tiene un servidor SMB "incorporado", pero en realidad acaba de iniciar [[Samba]] con un archivo {{ic | smb.conf}} generado automáticamente ubicado en {{ic|/tmp/qemu- Smb.''Pid''-0/smb.conf}} y lo hace accesible para el invitado en una dirección IP diferente (10.0.2.4 por defecto). Esto sólo funciona para la red de usuarios, y esto no es necesariamente muy útil ya que el invitado también puede acceder al servicio normal [[Samba]] en el host si ha configurado acciones en él.<br />
<br />
Para habilitar esta característica, inicie QEMU con un comando como:<br />
<br />
$ qemu-system-x86_64 -nic user,id=nic0,smb=''shared_dir_path'' ''disk_image''<br />
<br />
donde {{ic|''shared_dir_path''}} es un directorio que quieres compartir entre huésped y el host.<br />
<br />
Luego, en el invitado, podrá acceder al directorio compartido del host 10.0.2.4 con el nombre de recurso "qemu". Por ejemplo, en el Explorador de Windows iría a {{ic | \\ 10.0.2.4 \ qemu}}.<br />
<br />
{{Note (Español)|<br />
* Si estás usando opciones de compartir varias veces como {{ic|1=-net user, smb='' shared_dir_path1 '' -net user, smb='' shared_dir_path2 ''}} ó {{ic | 1 = -net user , Smb = '' shared_dir_path1 '', smb = '' shared_dir_path2 ''}} entonces solo compartirá el último definido.<br />
* Si no puede acceder a la carpeta compartida y el sistema invitado es Windows, compruebe que está habilitado el protocolo [http://ecross.mvps.org/howto/enable-netbios-over-tcp-ip-with-windows.htm NetBIOS ]{{Dead link (Español)|2023|05|06|status=domain name not resolved}} Y que un cortafuegos no bloquea los puertos [https://technet.microsoft.com/en-us/library/cc940063.aspx] utilizados por el protocolo NetBIOS.<br />
}}<br />
<br />
=== Montaje de una partición dentro de una imagen de disco raw ===<br />
<br />
Cuando la máquina virtual no se está ejecutando, es posible montar las particiones que están dentro de un archivo de imagen de disco sin formato configurándolas como dispositivos de bucle invertido. Esto no funciona con imágenes de disco en formatos especiales, como qcow2, aunque se pueden montar usando {{ic|qemu-nbd}}.<br />
<br />
{{Warning (Español)| Debe asegurarse de desmontar las particiones antes de ejecutar la máquina virtual de nuevo. De lo contrario, es muy probable que ocurra la corrupción de datos.}}<br />
<br />
==== Con la especificación manual del desplazamiento de bytes ====<br />
<br />
Una forma de montar una partición de imagen de disco es montar la imagen de disco en un cierto desplazamiento usando un comando como el siguiente:<br />
<br />
$ mount -o loop, offset = 32256 ''disk_image'' ''mountpoint''<br />
<br />
La opción {{ic|1 = offset = 32256}} se pasa realmente al programa {{ic|losetup}} para configurar un dispositivo de bucle invertido que empieza en el desplazamiento de byte 32256 del archivo y continúa hasta el final. A continuación, se monta este dispositivo de bucle invertido. También puede utilizar la opción {{ic|sizelimit}} para especificar el tamaño exacto de la partición, pero esto normalmente no es necesario.<br />
<br />
Dependiendo de la imagen del disco, la partición necesaria no se puede iniciar en el desplazamiento 32256. Ejecute {{ic|fdisk -l '' disk_image ''}} para ver las particiones de la imagen. Fdisk da las compensaciones de inicio y fin en sectores de 512 bytes, así que multiplique por 512 para obtener el desplazamiento correcto para pasar a {{ic|mount}}.<br />
<br />
==== Con las particiones autodetecting del módulo de bucle (loop) ====<br />
<br />
El controlador de bucle de Linux realmente admite particiones en dispositivos de bucle invertido, pero está desactivado de forma predeterminada. Para habilitarlo, haga lo siguiente:<br />
<br />
* Deshacerse de todos los dispositivos de bucle invertido (desmontar todas las imágenes montadas, etc.).<br />
* [[Kernel modules (Español)#Manejo manual de módulos|Descargar]] el módulo del kernel {{ic|loop}} y cargarlo con el conjunto de parámetros {{ic|1 = max_part = 15}}. Además, el número máximo de dispositivos de bucle puede controlarse con el parámetro {{ic | max_loop}}.<br />
<br />
{{Tip (Español)|Puede poner una entrada en {{ic|/etc/modprobe.d}} para cargar el módulo de bucle con {{ic|1=max_part=15}} cada vez, o puede poner {{ic|1 = loop.max_part = 15}} en la línea de comandos del kernel, dependiendo de si tiene o no el módulo {{ic|loop.ko}} integrado en su kernel.}}<br />
<br />
Configure su imagen como un dispositivo de bucle invertido:<br />
<br />
$ losetup -f -P ''disk_image''<br />
<br />
Entonces, si el dispositivo creado fue {{ic|/dev/loop0}}, se habrán creado automáticamente dispositivos adicionales {{ic|/dev/loop0pX}}, donde X es el número de la partición. Estos dispositivos de loopback de partición se pueden montar directamente. Por ejemplo:<br />
<br />
$ mount /dev/loop0p1 ''punto de montaje''<br />
<br />
Para montar la imagen de disco con '' udisksctl '', vea [[Udisks#Mount loop devices]].<br />
<br />
==== Con kpartx ====<br />
<br />
'' 'Kpartx' '' del paquete {{Pkg|multipath-tools}} puede leer una tabla de particiones en un dispositivo y crear un nuevo dispositivo para cada partición. Por ejemplo:<br />
# Kpartx -a '' disk_image ''<br />
<br />
Esto configurará el dispositivo de bucle invertido y creará los dispositivos de partición necesarios en {{ic|/dev/mapper/}}.<br />
<br />
=== Montar una partición dentro de una imagen qcow2 ===<br />
<br />
Puede montar una partición dentro de una imagen qcow2 usando {{ic|qemu-nbd}}. Mira [https://en.wikibooks.org/wiki/QEMU/Images#Mounting_an_image_on_the_host Wikibooks].<br />
<br />
=== Utilizar cualquier partición real como la única partición primaria de una imagen de disco duro ===<br />
<br />
A veces, puede que desee utilizar una de las particiones del sistema desde dentro de QEMU. El uso de una partición sin procesar para una máquina virtual mejorará el rendimiento, ya que las operaciones de lectura y escritura no pasan por la capa del sistema de archivos del host físico. Esta partición también proporciona una forma de compartir datos entre el host y el invitado.<br />
<br />
En Arch Linux, los archivos de dispositivo para las particiones sin procesar son, por defecto, propiedad de '' root '' y del grupo '' disk ''. Si desea que un usuario no root pueda leer y escribir en una partición en bruto, debe cambiar el propietario del archivo de dispositivo de la partición para ese usuario.<br />
<br />
{{Warning (Español)|<br />
* Aunque es posible, no se recomienda permitir que las máquinas virtuales alteren los datos críticos en el sistema host, como la partición raíz.<br />
* No debe montar un sistema de archivos en una partición de lectura-escritura en el host y el invitado al mismo tiempo. De lo contrario, se producirá corrupción de datos.<br />
}}<br />
<br />
Después de hacerlo, puede adjuntar la partición a una máquina virtual QEMU como un disco virtual.<br />
<br />
Sin embargo, las cosas son un poco más complicadas si desea tener la máquina virtual ''completa'' contenida en una partición. En ese caso, no habría ningún archivo de imagen de disco para arrancar realmente la máquina virtual, ya que no se puede instalar un cargador de arranque en una partición que está formateada como un sistema de archivos y no como un dispositivo particionado con un MBR. Una máquina virtual de este tipo se puede iniciar especificando el kernel y el initramfs manualmente o simulando un disco con un MBR usando RAID lineal.<br />
<br />
==== Especificar el kernel y el initrd manualmente ====<br />
<br />
QEMU es compatible con cargar [[Kernels|Linux kernels]] e [[initramfs|init ramdisks]] directamente, evitando así los cargadores de arranque como [[GRUB]]. A continuación, se puede iniciar con la partición física que contiene el sistema de archivos raíz como el disco virtual, que no parecen ser particionados. Esto se hace emitiendo un comando similar al siguiente:<br />
<br />
{{Note (Español)| En este ejemplo, se trata de las imágenes del '''host''' que se están utilizando, no del invitado. Si desea utilizar las imágenes del huésped, monte {{ic|/dev/sda3}} de sólo lectura (para proteger el sistema de archivos del host) y especifique {{ic|/full/path/to/images}} ó usar algún truco kexec en el invitado para recargar el kernel del invitado (extiende el tiempo de arranque).}}<br />
<br />
$ Qemu-system-i386 -kernel /boot/vmlinuz-linux -initrd /boot/initramfs-linux.img -append root=/dev/sda/dev/sda3<br />
<br />
En el ejemplo anterior, la partición física que se utiliza para el sistema de archivos raíz del huésped es {{ic|/dev/sda3}} en el host, pero aparece como {{ic|/dev/sda}} en el invitado.<br />
<br />
Por supuesto, puede especificar cualquier kernel e initrd que desee, y no sólo los que vienen con Arch Linux.<br />
<br />
Cuando hay varios [[kernel parameters]] que se pasan a la opción {{ic|-append}}, necesitan ser citados usando comillas simples o dobles. Por ejemplo:<br />
<br />
$ ... -append 'root=/dev/sda1 console=ttyS0'<br />
<br />
==== Simular disco virtual con MBR usando RAID lineal ====<br />
<br />
Una forma más complicada de tener una máquina virtual usar una partición física, mientras que mantener esa partición formateada como un sistema de archivos y no sólo tener la partición invitado la partición como si fuera un disco, es simular un MBR para que pueda Arranque utilizando un gestor de arranque tal como GRUB.<br />
<br />
Puede hacerlo utilizando el RAID del software en modo lineal (necesita el controlador de kernel {{ic|linear.ko}}) y un dispositivo de loopback: el truco consiste en añadir previamente un registro maestro de arranque (MBR) Real que desea incrustar en una imagen de disco RAEM QEMU.<br />
<br />
Suponga que tiene una partición simple {{ic|/|hdaN}} con algún sistema de archivos en la que desea formar parte de una imagen de disco QEMU. En primer lugar, crear un pequeño archivo para mantener el MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=32<br />
<br />
Aquí, se crea un archivo de 16 KB (32 * 512 bytes). Es importante no hacerlo demasiado pequeño (incluso si el MBR sólo necesita un bloque de 512 bytes), ya que cuanto menor sea, menor será el tamaño del chasis del dispositivo RAID de software, lo que podría tener un impacto En el rendimiento. A continuación, configura un dispositivo de bucle invertido en el archivo MBR:<br />
<br />
# losetup -f ''/path/to/mbr''<br />
<br />
Supongamos que el dispositivo resultante es {{ic|/dev/loop0}}, porque ya no habríamos estado usando otros bucle. El siguiente paso es crear la imagen de disco "fusionada" MBR + {{ic|/dev/hda''N''}} utilizando RAID de software:<br />
<br />
# modprobe lineal<br />
<br />
# mdadm --build --verbose /dev/md0 --chunk=16 --level=linear --raid-devices=2 /dev/loop0/dev/hda''N''<br />
<br />
El resultante {{ic|/dev/md0}} es lo que utilizará como una imagen de disco cruda QEMU (no olvide establecer los permisos para que el emulador pueda acceder a él). El último paso (y algo complicado) es configurar la configuración del disco (geometría del disco y tabla de particiones) para que el punto de inicio de la partición primaria en el MBR coincida con el de {{ic|/dev/hda''N''}}} Dentro {{ic|/dev/md0}} (un desplazamiento de exactamente 16 * 512 = 16384 bytes en este ejemplo). Hacer esto usando {{ic|fdisk}} en la máquina host, no en el emulador: la rutina de detección de disco crudo predeterminada de QEMU a menudo da lugar a offsets redondeados no kilobyte (como 31.5 KB, como en la sección anterior) que No puede ser administrado por el código RAID de software. Por lo tanto, desde el anfitrión:<br />
<br />
$ fdisk /dev/md0<br />
<br />
Pulse {{ic|X}} para entrar en el menú de expertos. Establezca el número de sectores por pista para que el tamaño de un cilindro coincida con el tamaño de su archivo MBR. Para dos cabezas y un tamaño de sector de 512, el número de sectores por pista debe ser 16, por lo que obtenemos cilindros de tamaño 2x16x512 = 16k.<br />
<br />
Ahora, presione {{ic|R}} para regresar al menú principal.<br />
<br />
Presione {{ic|P}} y compruebe que el tamaño del cilindro es ahora 16k.<br />
<br />
Ahora, cree una única partición primaria correspondiente a {{ic|/dev/hda''N''}}. Debe comenzar en el cilindro 2 y terminar en el extremo del disco (tenga en cuenta que el número de cilindros ahora difiere de lo que era cuando se introdujo fdisk.<br />
<br />
Finalmente, escribe el resultado al archivo: ya está. Ahora tiene una partición que puede montar directamente desde su host, así como parte de una imagen de disco QEMU:<br />
<br />
$ Qemu-system-i386 -hdc /dev/md0 ''[...]''<br />
<br />
Por supuesto, puede configurar con seguridad cualquier cargador de arranque en esta imagen de disco utilizando QEMU, siempre que la partición original {{ic|/dev/hda''N''}} contenga las herramientas necesarias.<br />
<br />
== Redes ==<br />
<br />
El rendimiento de la red virtual debería ser mejor con los dispositivos de derivación (tap) y puentes que con la red en modo de usuario o vde porque los dispositivos de derivación y los puentes se implementan en el kernel.<br />
<br />
Además, el rendimiento de la red se puede mejorar asignando a las máquinas virtuales un dispositivo de red [https://wiki.libvirt.org/page/Virtio virtio] en lugar de la emulación predeterminada de una NIC e1000. Consulte [[#Instalación de controladores virtio]] para obtener más información.<br />
<br />
=== Advertencia de dirección a nivel de enlace ===<br />
<br />
Al asignar el argumento {{ic|-net nic}} a QEMU, asignará por defecto a una máquina virtual una interfaz de red con la dirección de enlace {{ic|52:54:00:12:34:56}}. Sin embargo, cuando se utiliza la creación de redes puenteadas con varias máquinas virtuales, es esencial que cada máquina virtual tenga una dirección única de nivel de enlace (MAC) en el lado de la máquina virtual del dispositivo de derivación. De lo contrario, el puente no funcionará correctamente, ya que recibirá paquetes de varias fuentes que tienen la misma dirección de nivel de enlace. Este problema se produce incluso si los propios dispositivos de derivación tienen direcciones de nivel de enlace únicas porque la dirección de nivel de enlace de origen no se vuelve a escribir a medida que los paquetes pasan a través del dispositivo de derivación.<br />
<br />
Asegúrese de que cada máquina virtual tiene una dirección única de nivel de enlace, pero siempre debe comenzar con {{ic|52:54:}}. Utilice la opción siguiente, reemplazar ''X'' por un dígito hexadecimal arbitrario:<br />
<br />
$ qemu-system-i386 -net nic,macaddr=52:54:''XX:XX:XX:XX'' -net vde ''disk_image''<br />
<br />
Generar direcciones únicas de nivel de enlace se puede realizar de varias maneras:<br />
<br />
<ol><br />
<li>Especificar manualmente la dirección única de nivel de enlace para cada NIC. El beneficio es que el servidor DHCP asignará la misma dirección IP cada vez que se ejecute la máquina virtual, pero es inutilizable para un gran número de máquinas virtuales.<br />
</li><br />
<li>Generar dirección de nivel de enlace aleatoria cada vez que se ejecuta la máquina virtual. Prácticamente cero probabilidad de colisiones, pero la desventaja es que el servidor DHCP asignará una dirección IP diferente cada vez. Puede utilizar el siguiente comando en una secuencia de comandos para generar una dirección de nivel de enlace aleatoria en una variable {{ic|macaddr}}:<br />
<br />
{{bc|1=<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
qemu-system-i386 -net nic,macaddr="$macaddr" -net vde ''disk_image''<br />
}}<br />
<br />
</li><br />
<li>Utilice el siguiente script {{ic|qemu-mac-hasher.py}} para generar la dirección de nivel de enlace desde el nombre de la máquina virtual mediante una función de hash. Dado que los nombres de las máquinas virtuales son únicos, este método combina los beneficios de los métodos antes mencionados: genera la misma dirección de nivel de enlace cada vez que se ejecuta el script, aunque preserva la probabilidad prácticamente nula de colisiones.<br />
<br />
{{hc|qemu-mac-hasher.py|<nowiki><br />
#!/usr/bin/env python<br />
<br />
import sys<br />
import zlib<br />
<br />
if len(sys.argv) != 2:<br />
print("usage: %s <VM Name>" % sys.argv[0])<br />
sys.exit(1)<br />
<br />
crc = zlib.crc32(sys.argv[1].encode("utf-8")) & 0xffffffff<br />
crc = str(hex(crc))[2:]<br />
print("52:54:%s%s:%s%s:%s%s:%s%s" % tuple(crc))<br />
</nowiki>}}<br />
<br />
En un script, puede utilizar por ejemplo:<br />
<br />
vm_name="''VM Name''"<br />
qemu-system-i386 -name "$vm_name" -net nic,macaddr=$(qemu-mac-hasher.py "$vm_name") -net vde ''disk_image''<br />
</li><br />
</ol><br />
<br />
=== Redes en modo de usuario ===<br />
<br />
De forma predeterminada, sin ningún argumento {{ic|-netdev}}, QEMU utilizará la red en modo usuario con un servidor DHCP incorporado. A sus máquinas virtuales se les asignará una dirección IP cuando ejecuten su cliente DHCP, y podrán acceder a la red del host físico a través de la mascarada de IP realizada por QEMU.<br />
<br />
{{Warning (Español)| Esto sólo funciona con los protocolos TCP y UDP, por lo que ICMP, incluido {{ic|ping}}, no funcionará. No utilice {{ic|ping}} para probar la conectividad de red.}}<br />
<br />
Esta configuración predeterminada permite que sus máquinas virtuales accedan fácilmente a Internet, siempre que el host esté conectado a él, pero las máquinas virtuales no estarán directamente visibles en la red externa ni las máquinas virtuales podrán comunicarse entre sí si empieza Más de uno simultáneamente.<br />
<br />
La red de usuario en modo QEMU puede ofrecer más capacidades, como servidores TFTP o SMB incorporados, redirigir los puertos del host al huésped (por ejemplo, para permitir conexiones SSH al invitado) o conectar invitados a las VLAN para que puedan hablar entre sí. Consulte la documentación de QEMU en el indicador {{ic|-net user}} para obtener más detalles.<br />
<br />
Sin embargo, la conexión en red en modo usuario tiene limitaciones tanto en la utilidad como en el rendimiento. Las configuraciones de red más avanzadas requieren el uso de dispositivos de derivación u otros métodos.<br />
<br />
=== Tap de red con QEMU ===<br />
<br />
Los [[wikipedia:TUN/TAP|dispositivos tap]] Son una característica del kernel de Linux que le permite crear interfaces de red virtuales que aparecen como interfaces de red reales. Los paquetes enviados a una interfaz de derivación se entregan a un programa de espacio de usuario, tal como QEMU, que se ha enlazado a la interfaz.<br />
<br />
QEMU puede utilizar la red de derivación para una máquina virtual de modo que los paquetes enviados a la interfaz de derivación se envíen a la máquina virtual y aparezcan como procedentes de una interfaz de red (normalmente una interfaz Ethernet) en la máquina virtual. Por el contrario, todo lo que la máquina virtual envía a través de su interfaz de red aparecerá en la interfaz de tap.<br />
<br />
Los dispositivos de toque son soportados por los controladores de puente de Linux, por lo que es posible conectar entre sí los dispositivos entre sí y posiblemente con otras interfaces de host como {{ic|eth0}}. Esto es deseable si desea que sus máquinas virtuales puedan hablar entre sí, o si desea que otras máquinas en su LAN puedan hablar con las máquinas virtuales.<br />
<br />
{{Warning (Español)|Si conectas el dispositivo de toque y alguna interfaz de host, como {{ic|eth0}}, las máquinas virtuales aparecerán directamente en la red externa, lo que los exponerá a posibles ataques. Dependiendo de los recursos a los que tengan acceso sus máquinas virtuales, es posible que tenga que tomar todas las [[Firewalls|precauciones]] que normalmente tomaría al asegurar una computadora para proteger sus máquinas virtuales. Si el riesgo es demasiado grande, las máquinas virtuales tienen pocos recursos o se configuran varias máquinas virtuales, una solución mejor podría ser utilizar [[#Red de host solamente]] y configurar NAT. En este caso sólo necesitará un firewall en el host en lugar de múltiples firewalls para cada huésped.}}<br />
<br />
Como se indica en la sección de conexión en red de modo de usuario, los dispositivos de derivación ofrecen un rendimiento de red más alto que el modo de usuario. Si el OS invitado admite el controlador de red virtio, el rendimiento de la red se incrementará considerablemente también. Suponiendo el uso del dispositivo tap0, que el controlador virtio se utiliza en el invitado, y que no se utilizan scripts para ayudar a iniciar / detener la creación de redes, a continuación es parte del comando qemu se debe ver:<br />
<br />
-net nic, model=virtio -net tap, ifname=tap0, script=no, downscript=no<br />
<br />
Pero si ya está utilizando un dispositivo de tap con virtio controlador de red, uno puede incluso aumentar el rendimiento de la red mediante la activación de vhost, como:<br />
<br />
-net nic, model=virtio -net tap, ifname=tap0, script=no, downscript=no, vhost=on<br />
<br />
Ver http://www.linux-kvm.com/content/how-maximize-virtio-net-performance-vhost-net para obtener más información.<br />
<br />
==== Red de host solamente ====<br />
<br />
Si al puente se le da una dirección IP y se permite el tráfico destinado a ello, pero no hay una interfaz real (por ejemplo, {{ic|eth0}}) conectada al puente, las máquinas virtuales podrán hablar entre sí y la Sistema anfitrión. Sin embargo, no podrán hablar con nada en la red externa, siempre y cuando no configure IP enmascarada en el host físico. Esta configuración se llama '' red de host solamente '' por otro software de virtualización como [[VirtualBox]].<br />
<br />
{{Tip (Español)|<br />
* Si desea configurar IP masquerading, ej. NAT para máquinas virtuales, consulte la página [[Internet sharing#Enable NAT]].<br />
* Es posible que desee tener un servidor DHCP que se ejecute en la interfaz de puente para dar servicio a la red virtual. Por ejemplo, para usar la subred {{ic|172.20.0.1/16}} con [[dnsmasq]] como servidor DHCP:<br />
# ip addr add 172.20.0.1/16 dev br0<br />
# ip link set br0 up<br />
# dnsmasq --interface&#61;br0 --bind-interfaces --dhcp-range&#61;172.20.0.2,172.20.255.254<br />
}}<br />
<br />
==== Red interna ====<br />
<br />
Si no le da al puente una dirección IP y agrega una regla [[iptables]] para eliminar todo el tráfico al puente en la cadena INPUT, las máquinas virtuales podrán hablar entre sí, pero no con el host físico ó la red exterior. Esta configuración se llama "red interna" por otro software de virtualización como [[VirtualBox]]. Deberá asignar direcciones IP estáticas a las máquinas virtuales o ejecutar un servidor DHCP en una de ellas.<br />
<br />
De forma predeterminada, iptables eliminaría los paquetes de la red de bridge. Es posible que necesite utilizar dicha regla iptables para permitir paquetes en una red puenteada:<br />
<br />
# iptables -I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Redes puenteadas usando qemu-bridge-helper ====<br />
<br />
{{Note (Español)| Este método está disponible desde QEMU 1.1, consulte https://wiki.qemu.org/Features/HelperNetworking.}}<br />
<br />
Este método no requiere una secuencia de comandos de inicio y acepta fácilmente múltiples tomas y puentes múltiples. Utiliza el binario {{ic|/usr/lib/qemu/qemu-bridge-helper}}, que permite crear dispositivos de derivación en un puente existente.<br />
<br />
{{Tip (Español)|Véase [[Network bridge]] para obtener información sobre cómo crear un puente.}}<br />
<br />
En primer lugar, cree un archivo de configuración que contenga los nombres de todos los puentes que QEMU utilizará:<br />
<br />
{{hc|/etc/qemu/bridge.conf|<br />
allow ''bridge0''<br />
allow ''bridge1''<br />
...}}<br />
<br />
Ahora inicie la VM. El uso más básico sería:<br />
<br />
$ qemu-system-i386 -net nic -net bridge,br=''bridge0'' ''[...]''<br />
<br />
Con múltiples taps, el uso más básico requiere especificar la VLAN para todos los NIC adicionales:<br />
<br />
$ qemu-system-i386 -net nic -net bridge,br=''bridge0'' -net nic,vlan=1 -net bridge,vlan=1,br=''bridge1'' ''[...]''<br />
<br />
==== Creación manual del puente ====<br />
<br />
{{Tip (Español)|Desde QEMU 1.1, el [https://wiki.qemu.org/Features/HelperNetworking puente de red ayudante] puede establecer tun / tap up para usted sin necesidad de secuencias de comandos adicionales. Consulte [[#Redes puenteadas usando qemu-bridge-helper]].}}<br />
<br />
A continuación se describe cómo conectar una máquina virtual con una interfaz de host como {{ic | eth0}}, que es probablemente la configuración más común. Esta configuración hace que parezca que la máquina virtual está ubicada directamente en la red externa, en el mismo segmento Ethernet que la máquina host física.<br />
<br />
Vamos a reemplazar el adaptador Ethernet normal con un adaptador de puente y enlazar el adaptador Ethernet normal a él.<br />
<br />
* Instale {{Pkg|bridge-utils}}, que proporciona {{ic|brctl}} para manipular puentes.<br />
<br />
* Habilitar el reenvío IPv4:<br />
<br />
# sysctl net.ipv4.ip_forward=1<br />
<br />
Para hacer el cambio permanente, cambie {{ic|1=net.ipv4.ip_forward = 0}} a {{ic|1=net.ipv4.ip_forward = 1}} en {{ic|/etc/sysctl.d/99-sysctl.conf}}.<br />
<br />
* Cargue el módulo {{ic|tun}} y configurelo para cargarlo en el arranque. Véase [[Kernel modules (Español)]] para más detalles.<br />
<br />
* Ahora cree el puente. Ver [[Bridge with netctl]] para más detalles. Recuerde nombrar su puente como {{ic|br0}}, o modifique lo scripts a continuación del nombre del puente.<br />
<br />
* Cree el script que QEMU utiliza para abrir el adaptador de toma con los permisos {{ic|root:kvm}} 750:<br />
{{hc|/etc/qemu-ifup|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifup"<br />
echo "Bringing up $1 for bridged mode..."<br />
sudo /usr/bin/ip link set $1 up promisc on<br />
echo "Adding $1 to br0..."<br />
sudo /usr/bin/brctl addif br0 $1<br />
sleep 2<br />
</nowiki>}}<br />
<br />
* Cree el guión que QEMU utiliza para derribar el adaptador de toma en {{ic|/etc/qemu-ifdown}} con los permisos {{ic|root:kvm}} 750:<br />
{{hc|/etc/qemu-ifdown|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifdown"<br />
sudo /usr/bin/ip link set $1 down<br />
sudo /usr/bin/brctl delif br0 $1<br />
sudo /usr/bin/ip link delete dev $1<br />
</nowiki>}}<br />
<br />
* Use {{ic|visudo}} para añadir lo siguiente a el archivo {{ic|sudoers}}:<br />
{{bc|<nowiki><br />
Cmnd_Alias QEMU=/usr/bin/ip,/usr/bin/modprobe,/usr/bin/brctl<br />
%kvm ALL=NOPASSWD: QEMU<br />
</nowiki>}}<br />
<br />
* Se inicia QEMU con el siguiente script {{ic|run-qemu}}:<br />
{{hc|run-qemu|<nowiki><br />
#!/bin/bash<br />
USERID=$(whoami)<br />
<br />
# Get name of newly created TAP device; see https://bbs.archlinux.org/viewtopic.php?pid=1285079#p1285079<br />
precreationg=$(/usr/bin/ip tuntap list | /usr/bin/cut -d: -f1 | /usr/bin/sort)<br />
sudo /usr/bin/ip tuntap add user $USERID mode tap<br />
postcreation=$(/usr/bin/ip tuntap list | /usr/bin/cut -d: -f1 | /usr/bin/sort)<br />
IFACE=$(comm -13 <(echo "$precreationg") <(echo "$postcreation"))<br />
<br />
# This line creates a random MAC address. The downside is the DHCP server will assign a different IP address each time<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
# Instead, uncomment and edit this line to set a static MAC address. The benefit is that the DHCP server will assign the same IP address.<br />
# macaddr='52:54:be:36:42:a9'<br />
<br />
qemu-system-i386 -net nic,macaddr=$macaddr -net tap,ifname="$IFACE" $*<br />
<br />
sudo ip link set dev $IFACE down &> /dev/null<br />
sudo ip tuntap del $IFACE mode tap &> /dev/null<br />
</nowiki>}}<br />
<br />
Para ejecutar una VM, haz algo como esto:<br />
<br />
$ run-qemu -hda ''myvm.img'' -m 512 -vga std<br />
<br />
* Se recomienda, por motivos de rendimiento y seguridad, deshabilitar el firewall [http://ebtables.netfilter.org/documentation/bridge-nf.html en el puente]:<br />
{{hc|/etc/sysctl.d/10-disable-firewall-on-bridge.conf|<nowiki><br />
net.bridge.bridge-nf-call-ip6tables = 0<br />
net.bridge.bridge-nf-call-iptables = 0<br />
net.bridge.bridge-nf-call-arptables = 0<br />
</nowiki>}}<br />
Ejecute {{ic|sysctl -p /etc/sysctl.d/10-disable-firewall-on-bridge.conf}} para aplicar los cambios inmediatamente.<br />
<br />
Ver [https://wiki.libvirt.org/page/Networking#Creating_network_initscripts libvirt wiki] y [https://bugzilla.redhat.com/show_bug.cgi?id=512206 Fedora bug 512206]. Si obtiene errores de sysctl durante el inicio de archivos no existentes, haga que el módulo {{ic|bridge}} se cargue al arrancar. Véase [[Kernel module (Español)#systemd]].<br />
<br />
Como alternativa, puede configurar [[iptables]] para permitir que todo el tráfico se reenvíe a través del puente mediante la adición de una regla como esta:<br />
<br />
-I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Compartición de red entre dispositivo físico y un dispositivo de toque a través de iptables ====<br />
<br />
La conexión en puente funciona bien entre una interfaz cableada (por ejemplo, eth0), y es fácil de configurar. Sin embargo, si el host se conecta a la red a través de un dispositivo inalámbrico, el puente no es posible.<br />
<br />
Consulte [[Network bridge#Wireless interface on a bridge]] como referencia.<br />
<br />
Una forma de superar esto es configurar un dispositivo de derivación con una IP estática, haciendo que linux maneje automáticamente el enrutamiento para ella y, a continuación, reenvíe el tráfico entre la interfaz de derivación y el dispositivo conectado a la red a través de las reglas de iptables.<br />
<br />
Consulte [[Internet sharing]] como referencia.<br />
<br />
Allí puede encontrar lo que se necesita para compartir la red entre dispositivos, incluidos los de tap y tun. Lo siguiente sólo indica algunas de las configuraciones de host requeridas. Como se indica en la referencia anterior, el cliente debe configurarse para una IP estática, utilizando la IP asignada a la interfaz de derivación como puerta de enlace. La advertencia es que los servidores DNS del cliente pueden necesitar ser editados manualmente si cambian al cambiar de un dispositivo host conectado a la red a otro.<br />
<br />
Para permitir el reenvío de IP en cada inicio, es necesario agregar las siguientes líneas al archivo de configuración de sysctl dentro de /etc/sysctl.d:<br />
<br />
net.ipv4.ip_forward = 1<br />
net.ipv6.conf.default.forwarding = 1<br />
net.ipv6.conf.all.forwarding = 1<br />
<br />
Las reglas de iptables pueden verse así:<br />
<br />
# Forwarding from/to outside<br />
iptables -A FORWARD -i ${INT} -o ${EXT_0} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_1} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_2} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_0} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_1} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_2} -o ${INT} -j ACCEPT<br />
# NAT/Masquerade (network address translation)<br />
iptables -t nat -A POSTROUTING -o ${EXT_0} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_1} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_2} -j MASQUERADE<br />
<br />
El anterior supone que hay 3 dispositivos conectados a la red compartiendo tráfico con un dispositivo interno, donde por ejemplo:<br />
<br />
INT=tap0<br />
EXT_0=eth0<br />
EXT_1=wlan0<br />
EXT_2=tun0<br />
<br />
El anterior muestra un reenvío que permitiría compartir conexiones cableadas e inalámbricas con el dispositivo de derivación (tap).<br />
<br />
Las reglas de reenvío que se muestran son apátridas y para el reenvío puro. Se podría pensar en restringir el tráfico específico, poniendo un cortafuegos en el lugar para proteger al huésped y otros. Sin embargo, esto reduciría el rendimiento de la red, mientras que un simple puente no incluye nada de eso.<br />
<br />
Bonus: Si la conexión es cableada o inalámbrica, si se conecta a través de VPN a un sitio remoto con un dispositivo tun, suponiendo que el dispositivo tun abierto para esa conexión es tun0, y las reglas iptables anteriores se aplican, entonces la conexión remota se obtiene también Compartido con el huésped. Esto evita la necesidad de que el invitado también abra una conexión VPN. Una vez más, como la red de invitados debe ser estática, entonces si la conexión del host de forma remota de esta manera, uno probablemente tendrá que editar los servidores DNS en el invitado.<br />
<br />
=== Trabajo en red con VDE2 ===<br />
<br />
==== ¿Qué es VDE? ====<br />
<br />
VDE significa Virtual Distributed Ethernet. Comenzó como una mejora del interruptor [[User-mode Linux|uml]] _. Es una caja de herramientas para administrar redes virtuales.<br />
<br />
La idea es crear interruptores virtuales, que son básicamente sockets, y "conectar" tanto máquinas físicas como máquinas virtuales en ellas. La configuración que mostramos aquí es bastante simple; Sin embargo, VDE es mucho más potente que esto, puede conectar conmutadores virtuales juntos, ejecutarlos en diferentes hosts y supervisar el tráfico en los switches. Usted está invitado a leer [https://web.archive.org/web/20190821040940/http://wiki.virtualsquare.org/wiki/index.php/Main_Page la documentación del proyecto].<br />
<br />
La ventaja de este método es que no tienes que agregar privilegios de sudo a tus usuarios. No se debe permitir que los usuarios regulares ejecuten modprobe.<br />
<br />
==== Basics ====<br />
<br />
El soporte de VDE puede ser [[pacman|instalado]] a través del paquete {{Pkg|vde2}} en los [[repositorios oficiales]].<br />
<br />
En nuestra configuración, usamos tun/tap para crear una interfaz virtual en el host. Cargue el módulo {{ic|tun}} (véase [[kernel modules (Español)]] para obtener más detalles):<br />
<br />
# modprobe tun<br />
<br />
Ahora crea el conmutador virtual:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
<br />
Esta línea crea el switch, crea {{ic|tap0}}, lo "enchufa" y permite a los usuarios del grupo {{ic|users}} usarlo.<br />
<br />
La interfaz está conectada pero no está configurada todavía. Para configurarlo, ejecute este comando:<br />
<br />
# ip addr add 192.168.100.254/24 dev tap0<br />
<br />
Ahora, sólo tiene que ejecutar KVM con estas opciones {{ic|-net}} como usuario normal:<br />
<br />
$ qemu-system-i386 -net nic -net vde -hda ''[...]''<br />
<br />
Configure la red para su invitado como lo haría en una red física.<br />
<br />
{{Tip (Español)|Es posible que desee configurar NAT en dispositivo de toque para acceder a Internet desde la máquina virtual. Consulte [[Internet sharing#Enable NAT]] para obtener más información.}}<br />
<br />
==== Startup scripts ====<br />
<br />
Ejemplo de script principal que inicia VDE:<br />
<br />
{{hc|/etc/systemd/scripts/qemu-network-env|<nowiki><br />
#!/bin/sh<br />
# Preparación del entorno de red QEMU/VDE<br />
<br />
# La configuración IP del dispositivo de derivación que se utilizará para<br />
# La red de la máquina virtual:<br />
<br />
TAP_DEV=tap0<br />
TAP_IP=192.168.100.254<br />
TAP_MASK=24<br />
TAP_NETWORK=192.168.100.0<br />
<br />
# Host interface<br />
NIC=eth0<br />
<br />
case "$1" in<br />
start)<br />
echo -n "Starting VDE network for QEMU: "<br />
<br />
# If you want tun kernel module to be loaded by script uncomment here<br />
#modprobe tun 2>/dev/null<br />
## Wait for the module to be loaded<br />
#while ! lsmod | grep -q "^tun"; do echo "Waiting for tun device"; sleep 1; done<br />
<br />
# Start tap switch<br />
vde_switch -tap "$TAP_DEV" -daemon -mod 660 -group users<br />
<br />
# Bring tap interface up<br />
ip address add "$TAP_IP"/"$TAP_MASK" dev "$TAP_DEV"<br />
ip link set "$TAP_DEV" up<br />
<br />
# Start IP Forwarding<br />
echo "1" > /proc/sys/net/ipv4/ip_forward<br />
iptables -t nat -A POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
;;<br />
stop)<br />
echo -n "Stopping VDE network for QEMU: "<br />
# Delete the NAT rules<br />
iptables -t nat -D POSTROUTING "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
<br />
# Bring tap interface down<br />
ip link set "$TAP_DEV" down<br />
<br />
# Kill VDE switch<br />
pgrep -f vde_switch | xargs kill -TERM<br />
;;<br />
restart|reload)<br />
$0 stop<br />
sleep 1<br />
$0 start<br />
;;<br />
*)<br />
echo "Usage: $0 {start|stop|restart|reload}"<br />
exit 1<br />
esac<br />
exit 0<br />
</nowiki>}}<br />
<br />
Ejemplo de servicio systemd utilizando el script anterior:<br />
<br />
{{hc|/etc/systemd/system/qemu-network-env.service|<nowiki><br />
[Unit]<br />
Description=Manage VDE Switch<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/etc/systemd/scripts/qemu-network-env start<br />
ExecStop=/etc/systemd/scripts/qemu-network-env stop<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
Cambiar permisos de {{ic|qemu-network-env}} para ser ejecutable<br />
<br />
# chmod u+x /etc/systemd/scripts/qemu-network-env<br />
<br />
Puede iniciar {{ic|qemu-network-env.service}} como de costumbre.<br />
<br />
==== Método alternativo ====<br />
<br />
Si el método anterior no funciona o no quiere meterse con las configuraciones del kernel, TUN, dnsmasq e iptables, puede hacer lo siguiente para obtener el mismo resultado.<br />
<br />
# vde_switch -daemon -mod 660 -group users<br />
# slirpvde --dhcp --daemon<br />
<br />
A continuación, para iniciar la VM con una conexión a la red del host:<br />
<br />
$ qemu-system-i386 -net nic,macaddr=52:54:00:00:EE:03 -net vde ''disk_image''<br />
<br />
=== Puente VDE2 ===<br />
<br />
Basado en [https://selamatpagicikgu.wordpress.com/2011/06/08/quickhowto-qemu-networking-using-vde-tuntap-and-bridge/ quickhowto: qemu networking using vde, tun/tap, and bridge] gráfico. Cualquier máquina virtual conectada a vde está expuesta externamente. Por ejemplo, cada máquina virtual puede recibir la configuración DHCP directamente desde su enrutador ADSL.<br />
<br />
==== Conceptos básicos ====<br />
<br />
Recuerde que necesita el módulo {{ic|tun}} y el paquete {{Pkg|bridge-utils}}.<br />
<br />
Cree el dispositivo vde2/tap:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
# ip link set tap0 up<br />
<br />
Cree el puente:<br />
<br />
# brctl addbr br0<br />
<br />
Agregue dispositivos:<br />
<br />
# brctl addif br0 eth0<br />
# brctl addif br0 tap0<br />
<br />
Y configure la interfaz del puente:<br />
<br />
# dhcpcd br0<br />
<br />
==== Startup scripts ====<br />
<br />
Todos los dispositivos deben estar configurados. Y sólo el puente necesita una dirección IP. Para dispositivos físicos en el puente (por ejemplo, {{ic|eth0}}), esto puede hacerse con [[netctl]] utilizando un perfil Ethernet personalizado con:<br />
<br />
{{hc|/etc/netctl/ethernet-noip|<nowiki><br />
Description='A more versatile static Ethernet connection'<br />
Interface=eth0<br />
Connection=ethernet<br />
IP=no<br />
</nowiki>}}<br />
<br />
El siguiente servicio systemd personalizado puede utilizarse para crear y activar una interfaz de toma VDE2 para su uso en el grupo de usuarios {{ic|users}}.<br />
<br />
{{hc|/etc/systemd/system/vde2@.service|<nowiki><br />
[Unit]<br />
Description=Network Connectivity for %i<br />
Wants=network.target<br />
Before=network.target<br />
<br />
[Service]<br />
Type=oneshot<br />
RemainAfterExit=yes<br />
ExecStart=/usr/bin/vde_switch -tap %i -daemon -mod 660 -group users<br />
ExecStart=/usr/bin/ip link set dev %i up<br />
ExecStop=/usr/bin/ip addr flush dev %i<br />
ExecStop=/usr/bin/ip link set dev %i down<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
Y, por último, puede crear el puente interfaz con netctl.<br />
<br />
== Gráficos ==<br />
<br />
QEMU puede utilizar las siguientes salidas gráficas diferentes: {{ic|std}}, {{ic|qxl}}, {{ic|vmware}}, {{ic|virtio}}, {{ic|cirrus}} y {{ic|none}}.<br />
<br />
=== std ===<br />
<br />
Con {{ic|-vga std}} puede obtener una resolución de hasta 2560 x 1600 píxeles sin necesidad de controladores invitados. Este es el valor predeterminado desde QEMU 2.2.<br />
<br />
=== qxl ===<br />
<br />
QXL Es un controlador de gráficos paravirtual con soporte 2D. Para usarlo, pase la opción {{ic|-vga qxl}} e instale los controladores en el invitado. Es posible que desee utilizar SPICE para mejorar el rendimiento gráfico al utilizar QXL.<br />
<br />
En los invitados de Linux, los módulos del kernel {{ic|qxl}} y {{ic|bochs_drm}} deben ser inicializados para poder tener un rendimiento decente.<br />
<br />
==== SPICE ====<br />
<br />
El proyecto [https://www.spice-space.org/ SPICE] tiene como objetivo proporcionar una solución completa de código abierto para el acceso remoto a máquinas virtuales de una manera transparente.<br />
<br />
SPICE sólo se puede utilizar cuando se utiliza QXL como la salida gráfica.<br />
<br />
El siguiente es un ejemplo de arranque con SPICE como protocolo de escritorio remoto:<br />
<br />
$ qemu-system-i386 -vga qxl -spice port=5930,disable-ticketing -chardev spicevm <br />
<br />
Conéctese al invitado utilizando un cliente SPICE. En este momento se recomienda {{Pkg|spice-gtk}}, sin embargo otros [https://www.spice-space.org/download.html clientes], incluyendo otras plataformas, están disponibles:<br />
<br />
$ spicy -h 127.0.0.1 -p 5930<br />
<br />
El uso de [[wikipedia:Unix_socket|Unix sockets]] en lugar de los puertos TCP no implica el uso de pila de red en el sistema host, por lo que es [https://unix.stackexchange.com/questions/91774/performance-of-unix- Sockets-vs-tcp-ports según se informa] mejor para el rendimiento. Ejemplo:<br />
$ qemu-system-x86_64 -vga qxl -device virtio-serial-pci -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent -spice unix,addr=/tmp/vm_spice.socket,disable-ticketing<br />
$ spicy --uri="spice+unix:///tmp/vm_spice.socket"<br />
<br />
Para una mejor compatibilidad con varios monitores, compartir el portapapeles, etc., los paquetes siguientes deben estar instalados en el invitado:<br />
* {{Pkg|spice-vdagent}}: Spice agent xorg cliente que permite copiar y pegar entre el cliente y X-session y más<br />
* {{Pkg|xf86-video-qxl}} {{AUR|xf86-video-qxl-git}}: Xorg X11 qxl controlador de vídeo<br />
* Para otros sistemas operativos, mire la sección Guest de la página [https://www.spice-space.org/download.html SPICE-Space download].<br />
<br />
=== vmware ===<br />
<br />
Aunque tiene pocos errores, tiene mejor rendimiento que std y cirrus. Instale los controladores de VMware {{Pkg|xf86-video-vmware}} y {{Pkg|xf86-input-vmmouse}} para los invitados de Arch Linux.<br />
<br />
=== virtio ===<br />
<br />
{{ic|virtio-vga}} / {{ic|virtio-gpu}} Es un controlador de gráficos 3D paravirtual basado en [https://virgil3d.github.io/ virgl]. Actualmente un trabajo en curso, que sólo admite a invitados Linux (>= 4.4) con {{Pkg|mesa}} (>= 11.2) compilados con la opción {{ic|1=--with-gallium-drivers=virgl}}.<br />
<br />
Para activar la aceleración 3D en el sistema invitado, seleccione vga con {{ic|-vga virtio}} y habilitar el contexto opengl en el dispositivo de visualización con {{ic|1=-display sdl,gl=on}} ó {{ic|1=-display gtk,gl=on}} Para la salida de pantalla sdl y gtk respectivamente. La configuración correcta se puede confirmar mirando el registro del kernel en el invitado:<br />
<br />
{{hc|# dmesg {{!}} grep drm |<br />
[drm] pci: virtio-vga detected<br />
[drm] virgl 3d acceleration enabled<br />
}}<br />
<br />
A partir de septiembre de 2016, el soporte para el protocolo de especias está en desarrollo y se puede probar la instalación de la versión de desarrollo de {{Pkg|spice}} (>= 0.13.2) y la recompilación de qemu.<br />
<br />
Para más información visite [https://web.archive.org/web/20171216170334/https://www.kraxel.org/blog/tag/virgl/ blog de kraxel].<br />
<br />
=== cirrus ===<br />
<br />
El adaptador gráfico cirrus fue el predeterminado [https://wiki.qemu.org/ChangeLog/2.2#VGA before 2.2]. [Https://www.kraxel.org/blog/2014/10/qemu-using-cirrus-considered-harmful/ no debería] utilizarse en sistemas modernos.<br />
<br />
=== none ===<br />
<br />
Esto es como un PC que no tiene tarjeta VGA en absoluto. Ni siquiera podrías acceder a ella con la opción {{ic|-vnc}}. Además, esto es diferente de la opción {{ic|-nographic}} que permite a QEMU emular una tarjeta VGA, pero deshabilita la visualización SDL.<br />
<br />
=== vnc ===<br />
<br />
Dado que usó la opción {{ic|-nographic}}, puede agregar la opción {{ic|-vnc display}} para que QEMU escuche en {{ic|display}} y redirigir la pantalla VGA a la sesión VNC . Hay un ejemplo de esto en las configuraciones de ejemplo de la sección [[#Inicio de las máquinas virtuales QEMU en el arranque]].<br />
<br />
$ qemu-system-i386 -vga std -nographic -vnc :0<br />
$ gvncviewer :0<br />
<br />
Al usar VNC, puede experimentar problemas de teclado descritos (en detalles gory) [https://www.berrange.com/posts/2010/07/04/more-than-you-or-i-ever-wanted-to-know-about-virtual-keyboard-handling/ aquí]. La solución es "no" usar la opción {{ic|-k}} en QEMU y usar {{ic|gvncviewer}} de {{Pkg|gtk-vnc}}. Ver también [https://www.mail-archive.com/libvir-list@redhat.com/msg13340.html este] mensaje publicado en la lista de correo de libvirt.<br />
<br />
== Audio ==<br />
<br />
=== Host ===<br />
<br />
El controlador de audio utilizado por QEMU se establece con la variable de entorno {{ic|QEMU_AUDIO_DRV}}:<br />
<br />
$ export QEMU_AUDIO_DRV=pa<br />
<br />
Ejecute el siguiente comando para obtener las opciones de configuración de QEMU relacionadas con PulseAudio:<br />
<br />
$ qemu-system-x86_64 -audio-help | awk '/Name: pa/' RS=<br />
<br />
Las opciones listadas se pueden exportar como variables de entorno, por ejemplo:<br />
<br />
{{bc|1=<br />
$ export QEMU_PA_SINK=alsa_output.pci-0000_04_01.0.analog-stereo.monitor<br />
$ export QEMU_PA_SOURCE=input<br />
}}<br />
<br />
=== Invitado ===<br />
<br />
Para obtener la lista de los controladores de audio de emulación compatibles:<br />
<br />
$ qemu-system-x86_64 -soundhw help<br />
<br />
Para usar (ej. {{ic|hda}}) para el invitado utilice el comando {{ic|-soundhw hda}} con QEMU.<br />
<br />
{{Note (Español)| Los controladores emulados con tarjeta gráfica de vídeo para la máquina invitada también pueden causar un problema con la calidad del sonido. Pruebe uno por uno para que funcione. Puede listar las opciones posibles con {{ic|qemu-system-x86_64 -h | grep vga}}.}}<br />
<br />
=== VirtIO sound ===<br />
<br />
VirtIO sound está disponible desde la versión 8.2.0 de QEMU. El uso es:<br />
<br />
-device virtio-sound-pci,audiodev=my_audiodev -audiodev alsa,id=my_audiodev<br />
<br />
Más información puede ser encontrada en [https://qemu-project.gitlab.io/qemu/system/devices/virtio-snd.html documentación QEMU].<br />
<br />
== Instalación de controladores virtio ==<br />
<br />
QEMU ofrece a los clientes la posibilidad de utilizar dispositivos bloqueados y de red paravirtualizados utilizando los controladores [https://wiki.libvirt.org/page/Virtio virtio], que proporcionan un mejor rendimiento y menores gastos generales.<br />
<br />
Un dispositivo virtio bloque requiere la opción {{ic|-drive}} en lugar del simple {{ic|-hd *}} más {{ic|1=if=virtio}}:<br />
<br />
$ qemu-system-i386 -boot order=c -drive file=''disk_image'',if=virtio<br />
<br />
{{Note (Español)|{{Ic|1=-boot order=c}} es absolutamente necesario cuando se desea arrancar desde él. No hay detección automática como con {{Ic|-hd*}}.}}<br />
<br />
* Casi de la misma manera para la red:<br />
<br />
$ qemu-system-i386 -net nic,model=virtio<br />
<br />
{{Note (Español)| Esto sólo funcionará si la máquina invitada tiene controladores para dispositivos virtio. Linux lo hace, y los controladores necesarios están incluidos en Arch Linux, pero no hay garantía de que los dispositivos virtio funcionen con otros sistemas operativos.}}<br />
<br />
=== Preparando a Arch Linux como invitado ===<br />
<br />
Para utilizar los dispositivos virtio después de instalar un invitado de Arch Linux, se deben cargar en el invitado los siguientes módulos: {{Ic|virtio}}, {{Ic|virtio_pci}}, {{Ic|virtio_blk}}, {{Ic|Virtio_net}}, y {{Ic|virtio_ring}}. Para los huéspedes de 32 bits, no es necesario el módulo "virtio" específico.<br />
<br />
Si desea arrancar desde un disco virtio, el disco ramd inicial debe contener los módulos necesarios. De forma predeterminada, esto es manejado por el gancho {{ic|autodetect}} de [[mkinitcpio]]. De lo contrario, utilice la matriz {{ic|MODULES}} en {{ic|/etc/mkinitcpio.conf}} para incluir los módulos necesarios y reconstruir el disco ramd inicial.<br />
<br />
{{hc|/etc/mkinitcpio.conf|2=<br />
MODULES="virtio virtio_blk virtio_pci virtio_net"}}<br />
<br />
Los discos Virtio se reconocen con el prefijo {{ic|'''v'''}} (ej. {{ic|'''v''' da}}, {{ic|'''v''' db}}, etc.); Por lo tanto, los cambios deben realizarse al menos en {{ic|/etc/fstab}} y {{ic|/boot/grub/grub.cfg}} al arrancar desde un disco virtio.<br />
<br />
{{Note (Español)|Cuando se hace referencia a discos por [[UUID]] en {{ic|/etc/fstab}} y bootloader, no hay nada que hacer.}}<br />
<br />
Se puede encontrar más información sobre la paravirtualización con KVM [https://www.linux-kvm.org/page/Boot_from_virtio_block_device aquí].<br />
<br />
También puede instalar {{Pkg|qemu-guest-agent}} para implementar la compatibilidad con los comandos QMP que mejorarán las capacidades de administración del hipervisor. Después de instalar el paquete, puedes habilitar e iniciar el {{ic|qemu-ga.service}}.<br />
<br />
=== Preparar un invitado de Windows ===<br />
<br />
{{Note (Español)|1=La única forma (fiable) de actualizar un cliente de Windows 8.1 a Windows 10 parece que es elegir temporalmente cpu core2duo, nx para la instalación [https://ubuntuforums.org/showthread.php?t=2289210]. Después de la instalación, puede volver a otros ajustes de la CPU (8/8/2015).}}<br />
<br />
==== Bloquear controladores de dispositivo ====<br />
<br />
===== Nueva instalación de Windows =====<br />
<br />
Windows no viene con los controladores virtio. Por lo tanto, tendrá que cargarlos durante la instalación. Hay básicamente dos maneras de hacer esto: vía disco blando o vía archivos de ISO. Ambas imágenes se pueden descargar desde el repositorio [https://fedoraproject.org/wiki/Windows_Virtio_Drivers Fedora].<br />
<br />
La opción del disquete es difícil porque necesitará presionar F6 (Shift-F6 en Windows más reciente) al inicio de la alimentación del QEMU. Esto es difícil ya que necesitas tiempo para conectar tu ventana de consola VNC. Puede intentar agregar un retardo a la secuencia de arranque. Consulte {{ic|man qemu-system}} para obtener más detalles sobre la aplicación de un retardo en el arranque.<br />
<br />
La opción ISO para cargar los controladores es la forma preferida, pero está disponible sólo en Windows Vista y Windows Server 2008 y versiones posteriores. El procedimiento consiste en cargar la imagen con controladores virtio en un dispositivo de cdrom adicional junto con el dispositivo de disco principal y el instalador de Windows:<br />
<br />
$ qemu-system-i386 ... \<br />
-drive file=''/path/to/primary/disk.img'',index=0,media=disk,if=virtio \<br />
-drive file=''/path/to/installer.iso'',index=2,media=cdrom \<br />
-drive file=''/path/to/virtio.iso'',index=3,media=cdrom \<br />
...<br />
<br />
Durante la instalación, el instalador de Windows le pedirá su clave de producto y realizará algunas comprobaciones adicionales. Cuando llegue a la "¿Dónde desea instalar Windows?" Pantalla, dará una advertencia de que no se encuentran discos. Siga las instrucciones de ejemplo siguientes (basadas en Windows Server 2012 R2 con Actualización).<br />
<br />
* Seleccione la opción {{ic|Load Drivers}}.<br />
* Desactive la casilla de "Ocultar los controladores que no son compatibles con el hardware de este equipo".<br />
* Haga clic en el botón Examinar y abra el CDROM para la virtio iso, normalmente llamada "virtio-win-XX".<br />
* Ahora vaya a {{ic|E:\viostor\[your-os]\amd64}}, seleccione y pulse OK.<br />
* Click Next<br />
<br />
Ahora debería ver sus discos virtio listados aquí, listos para ser seleccionados, formateados e instalados.<br />
<br />
===== Cambiar la máquina virtual existente de Windows para utilizar virtio =====<br />
<br />
Modificar un invitado de Windows existente para arrancar desde disco virtio es un poco difícil.<br />
<br />
Puede descargar el controlador de disco virtio desde el [https://fedoraproject.org/wiki/Windows_Virtio_Drivers repositorio de Fedora].<br />
<br />
Ahora necesita crear una nueva imagen de disco, que llene la fuerza de Windows para buscar el controlador. Por ejemplo:<br />
<br />
$ qemu-img create -f qcow2 ''fake.qcow2'' 1G<br />
<br />
Ejecute el invitado original de Windows (con el disco de inicio todavía en modo IDE) con el disco falso (en modo virtio) y un CD-ROM con el controlador.<br />
<br />
$ qemu-system-i386 -m 512 -vga std -drive file=''windows_disk_image'',if=ide -drive file=''fake.qcow2'',if=virtio -cdrom virtio-win-0.1-81.iso<br />
<br />
Windows detectará el disco falso y tratará de encontrar un controlador para ello. Si falla, vaya al '' Administrador de dispositivos '', busque la unidad SCSI con un icono de signo de exclamación (debe estar abierto), haga clic en '' Actualizar controlador '' y seleccione el CD-ROM virtual. No olvide seleccionar la casilla de verificación que dice que debe buscar directorios recursivamente.<br />
<br />
Cuando la instalación se realiza correctamente, puede apagar la máquina virtual y volver a iniciarla, ahora con el disco de arranque conectado en modo virtio:<br />
<br />
$ qemu-system-i386 -m 512 -vga std -drive file=''windows_disk_image'',if=virtio<br />
<br />
{{Note (Español)|Si encuentra la pantalla azul de Death, asegúrese de no olvidar el parámetro {{ic|-m}} y de que no arranca con virtio en lugar de ide para la unidad del sistema antes de instalar los controladores.}}<br />
<br />
==== Controladores de red ====<br />
<br />
La instalación de los controladores de red virtio es un poco más fácil, simplemente agregue el argumento {{ic|-net}} como se explicó anteriormente.<br />
<br />
$ qemu-system-i386 -m 512 -vga std -drive file=''windows_disk_image'',if=virtio -net nic,model=virtio -cdrom virtio-win-0.1-74.iso<br />
<br />
Windows detectará el adaptador de red y tratará de encontrar un controlador para ello. Si falla, vaya al ''Administrador de dispositivos'', localice el adaptador de red con un icono de signo de exclamación (debe estar abierto), haga clic en ''Actualizar controlador'' y seleccione el CD-ROM virtual. No olvide seleccionar la casilla de verificación que dice que debe buscar directorios recursivamente.<br />
<br />
=== Preparación de FreeBSD como invitado ===<br />
<br />
Instale el puerto {{ic|emulators/virtio-kmod}} si está utilizando FreeBSD 8.3 o posterior hasta 10.0-CURRENT donde están incluidos en el kernel. Después de la instalación, añada lo siguiente a su archivo {{ic|/boot/loader.conf}}:<br />
<br />
{{bc|<nowiki><br />
virtio_loader="YES"<br />
virtio_pci_load="YES"<br />
virtio_blk_load="YES"<br />
if_vtnet_load="YES"<br />
virtio_balloon_load="YES"<br />
</nowiki>}}<br />
<br />
A continuación, modifique su {{ic|/etc/fstab}} haciendo lo siguiente:<br />
<br />
{{bc|<nowiki><br />
sed -i bak "s/ada/vtbd/g" /etc/fstab<br />
</nowiki>}}<br />
<br />
Y verificar que {{ic|/etc/fstab}} es consistente. Si algo sale mal, sólo arranque en un CD de rescate y copie {{ic|/etc/fstab.bak}} de vuelta a {{ic|/etc/fstab}}.<br />
<br />
== Consejos y trucos ==<br />
<br />
=== Inicio de las máquinas virtuales QEMU en el arranque ===<br />
<br />
==== Con libvirt ====<br />
<br />
Si se configura una máquina virtual con [[libvirt]], se puede configurar a través de la interfaz gráfica de usuario de virt-manager para iniciar en el arranque de host, accediendo a las Opciones de arranque de la máquina virtual y seleccionando "Inicio de la máquina virtual en el arranque del host".<br />
<br />
==== Script personalizado ====<br />
<br />
Para ejecutar QEMU VMs al arrancar, puede usar las siguientes unidades systemd y config.<br />
<br />
{{hc|/etc/systemd/system/qemu@.service|<nowiki><br />
[Unit]<br />
Description=QEMU virtual machine<br />
<br />
[Service]<br />
Environment="type=system-x86_64" "haltcmd=kill -INT $MAINPID"<br />
EnvironmentFile=/etc/conf.d/qemu.d/%i<br />
ExecStart=/usr/bin/env qemu-${type} -name %i -nographic $args<br />
ExecStop=/bin/sh -c ${haltcmd}<br />
TimeoutStopSec=30<br />
KillMode=none<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
{{Note (Español)|De acuerdo con {{ic|systemd.service (5)}} y {{ic|systemd.kill (5)}} man, es necesario utilizar {{ic|1=KillMode=none}} opción. De lo contrario, el proceso qemu principal se eliminará inmediatamente después de que se cierre el comando {{ic|ExecStop}} (simplemente hace eco de una cadena) y su sistema de búsqueda no podrá apagarse correctamente.}}<br />
<br />
A continuación, cree archivos de configuración por-VM, denominados {{ic|/etc/conf.d/qemu.d/''vm_name''}}, con las siguientes variables establecidas:<br />
<br />
; type<br />
: QEMU binary to call. If specified, will be prepended with {{ic|/usr/bin/qemu-}} and that binary will be used to start the VM. I.e. you can boot e.g. {{ic|qemu-system-arm}} images with {{ic|1=type="system-arm"}}.<br />
; args<br />
: QEMU command line to start with. Will always be prepended with {{ic|-name ${vm} -nographic}}.<br />
; haltcmd<br />
: Command to shut down a VM safely. I am using {{ic|-monitor telnet:..}} and power off my VMs via ACPI by sending {{ic|system_powerdown}} to monitor. You can use SSH or some other ways.<br />
<br />
Ejemplo de configuración:<br />
<br />
{{hc|/etc/conf.d/qemu.d/one|<nowiki><br />
type="system-x86_64"<br />
<br />
args="-enable-kvm -m 512 -hda /dev/mapper/vg0-vm1 -net nic,macaddr=DE:AD:BE:EF:E0:00 \<br />
-net tap,ifname=tap0 -serial telnet:localhost:7000,server,nowait,nodelay \<br />
-monitor telnet:localhost:7100,server,nowait,nodelay -vnc :0"<br />
<br />
haltcmd="echo 'system_powerdown' | nc localhost 7100" # or netcat/ncat<br />
<br />
# You can use other ways to shut down your VM correctly<br />
#haltcmd="ssh powermanager@vm1 sudo poweroff"<br />
</nowiki>}}<br />
<br />
{{hc|/etc/conf.d/qemu.d/two|<nowiki><br />
args="-enable-kvm -m 512 -hda /srv/kvm/vm2.img -net nic,macaddr=DE:AD:BE:EF:E0:01 \<br />
-net tap,ifname=tap1 -serial telnet:localhost:7001,server,nowait,nodelay \<br />
-monitor telnet:localhost:7101,server,nowait,nodelay -vnc :1"<br />
<br />
haltcmd="echo 'system_powerdown' | nc localhost 7101"<br />
</nowiki>}}<br />
<br />
Para establecer qué máquinas virtuales se iniciarán al arrancar, habilite la unidad de [[systemd]] {{ic|qemu@''vm_name''.service}}.<br />
<br />
=== Integración del ratón ===<br />
<br />
Para evitar que el ratón sea agarrado al hacer clic en la ventana del sistema operativo invitado, agregue la opción {{ic|-usbdevice tablet}}. Esto significa que QEMU puede reportar la posición del ratón sin tener que agarrar el ratón. Esto también anula la emulación de ratón PS/2 cuando se activa. Por ejemplo:<br />
<br />
$ qemu-system-i386 -hda ''disk_image'' -m 512 -vga std -usbdevice tablet<br />
<br />
If that does not work, try the tip at [[#El cursor del ratón está nervioso o errático]].<br />
<br />
=== Dispositivo USB del host de paso ===<br />
<br />
Para acceder al dispositivo físico USB conectado al host desde la VM, puede utilizar la opción: {{ic|-usbdevice host:''vendor_id'':''product_id''}}.<br />
<br />
Puedes encontrar {{ic|vendor_id}} y {{ic|product_id}} de tu dispositivo con el comando {{ic|lsusb}}.<br />
<br />
Puesto que el chipset I440FX por defecto emulado por qemu cuentan con un solo controlador UHCI (USB 1), la opción {{ic|-usbdevice}} intentará conectar su dispositivo físico a él. En algunos casos esto puede causar problemas con los dispositivos más nuevos. Una posible solución es emular el chipset [https://wiki.qemu.org/Features/Q35 ICH9], que ofrece un controlador EHCI que soporta hasta 12 dispositivos, usando la opción {{ic|1=-machine type=q35}}.<br />
<br />
Una solución menos invasiva es emular un controlador EHCI (USB 2) o XHCI (USB 3) con la opción {{ic | 1 = -device usb-ehci, id = ehci}} o {{ic|1=-device nec -usb-xhci, id=xhci}} respectivamente y luego adjuntar su dispositivo físico con la opción {{ic|1=-device usb-host,..}} como sigue:<br />
<br />
-device usb-host,bus='''controller_id'''.0,vendorid=0x'''vendor_id''',productid=0x'''product_id'''<br />
<br />
También puede agregar la configuración {{ic|1=..., port =''<n>''}} a la opción anterior para especificar en qué puerto físico del controlador virtual que desea conectar su dispositivo, útil en El caso que desea agregar varios dispositivos usb a la VM.<br />
<br />
{{Note (Español)|Si encuentra errores de permisos al ejecutar QEMU, consulte [[udev#About udev rules]] para obtener información sobre cómo establecer permisos del dispositivo.}}<br />
<br />
=== Habilitar KSM ===<br />
<br />
Kernel Samepage Merging (KSM) es una característica del kernel de Linux que permite que una aplicación se registre con el kernel para que sus páginas se combinen con otros procesos que también se registren para que sus páginas se fusionen. El mecanismo KSM permite a las máquinas virtuales invitadas compartir páginas entre sí. En un entorno donde muchos de los sistemas operativos invitados son similares, esto puede resultar en ahorros significativos de memoria.<br />
<br />
Para activar KSM, simplemente ejecute:<br />
<br />
# echo 1 > /sys/kernel/mm/ksm/run<br />
<br />
Para hacerlo permanente, puede utilizar [[Systemd#systemd-tmpfiles - temporary files|archivos temporales de systemd]]:<br />
<br />
{{hc|/etc/tmpfiles.d/ksm.conf|<br />
w /sys/kernel/mm/ksm/run - - - - 1<br />
}}<br />
<br />
Si KSM está en ejecución y hay páginas que se van a fusionar (es decir, al menos dos máquinas virtuales similares se están ejecutando), entonces {{ic|/sys/kernel/mm/ksm/pages_shared}} debería ser distinto de cero. Consulte https://docs.kernel.org/vm/ksm.html{{Dead link (Español)|2022|09|22|status=404}} para obtener más información.<br />
<br />
{{Tip (Español)|Una manera fácil de ver lo bien que KSM está realizando es simplemente imprimir el contenido de todos los archivos de ese directorio: {{bc|$ grep./Sys/kernel/mm/ksm/*}}}}<br />
<br />
=== Multi-monitor support ===<br />
<br />
El controlador QXL de Linux soporta cuatro cabezas (pantallas virtuales) de forma predeterminada. Esto se puede cambiar a través del parámetro kernel {{ic | 1 = qxl.heads = N}}.<br />
<br />
El tamaño de memoria VGA predeterminado para los dispositivos QXL es de 16M (el tamaño de la VRAM es de 64M). Esto no es suficiente si desea habilitar dos monitores 1920x1200 ya que requiere 2 × 1920 × 4 (profundidad de color) × 1200 = 17.6 MiB memoria VGA. Esto se puede cambiar reemplazando {{ic|-vga qxl}} por {{ic|1=-vga none -device qxl-vga, vgamem_mb=32}}. Si alguna vez incrementas vgamem_mb más allá de 64M, también debes aumentar la opción {{ic|vram_size_mb}}.<br />
<br />
=== Copiar y pegar ===<br />
<br />
Para poder copiar y pegar entre el host y el invitado, debe habilitar el canal de comunicación del agente de especias. Requiere agregar un dispositivo virtio-serial al huésped, y abrir un puerto para el vdagent de la especia. También es necesario instalar el spice vdagent en invitado ({{Pkg|spice-vdagent}} para invitados de Arch, [https://www.spice-space.org/download.html Herramientas para invitados de Windows] para invitados de Windows). Asegúrese de que el agente se está ejecutando (y para el futuro, se iniciará automáticamente).<br />
<br />
Inicie QEMU con las siguientes opciones:<br />
<br />
$ qemu-system-i386 -vga qxl -spice port=5930,disable-ticketing -device virtio-serial-pci -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
La opción {{ic|-device virtio-serial-pci}} añade el dispositivo virtio-serial, {{ic|1=-device virtserialport, chardev=spicechannel0, nombre=com.redhat.spice.0}} abre un puerto Para spice vdagent en ese dispositivo y {{ic|1=-chardev spicevmc, id=spicechannel0, nombre=vdagent}} añade un spicevmc chardev para ese puerto.<br />
<br />
Es importante que la opción {{ic|1=chardev=}} del dispositivo {{ic|virtserialport}} coincida con la opción {{ic|1=id=}} dada a la opción {{ic | chardev}} ({{Ic|spicechannel0}} en este ejemplo). También es importante que el nombre del puerto sea {{ic|com.redhat.spice.0}}, ya que es el espacio de nombres donde vdagent está buscando en el invitado. Y finalmente, especifique {{ic|1=name=vdagent}} para que spice sepa para qué sirve este canal.<br />
<br />
=== Notas específicas de Windows ===<br />
<br />
QEMU puede ejecutar cualquier versión de Windows desde Windows 95 a través de Windows 10.<br />
<br />
Es posible ejecutar [[Windows PE]] en QEMU.<br />
<br />
==== Inicio rápido ====<br />
<br />
{{Note (Español)|Se requiere una cuenta de administrador para cambiar la configuración de energía.}}<br />
Para invitados de Windows 8 (o posteriores), es mejor desactivar "Activar inicio rápido (recomendado)" en Opciones de energía del Panel de control, ya que hace que el invitado se bloquee durante cada arranque.<br />
<br />
El inicio rápido también puede necesitar deshabilitarse para que los cambios en la opción {{ic|-smp}} se apliquen correctamente.<br />
<br />
==== Protocolo de escritorio remoto ====<br />
<br />
Si utiliza un invitado de MS Windows, puede utilizar RDP para conectarse a su VM invitada. Si está utilizando una VLAN o no está en la misma red que el invitado, utilice:<br />
<br />
$ qemu-system-i386 -nographic -net user,hostfwd=tcp::5555-:3389<br />
<br />
A continuación, conéctese con {{Pkg|rdesktop}} ó {{Pkg|freerdp}} al invitado. Por ejemplo:<br />
<br />
$ xfreerdp -g 2048x1152 localhost:5555 -z -x lan<br />
<br />
== Solución de problemas ==<br />
<br />
=== La máquina virtual virtual corre muy lento ===<br />
<br />
Hay algunas técnicas que se pueden usar para implementar rendimiento en la máquina virtual, por ejemplo:<br />
<br />
* Use la opción {{ic|-cpu host}} para hacer que QEMU emule la CPU del host. Si no se hace esto, podría intentar emular un CPU más genérico.<br />
* Especialmente para los invitados de Windows, habilite [https://blog.wikichoon.com/2014/07/enabling-hyper-v-enlightenments-with-kvm.html Iluminaciones de Hyper-V]: {{ic|1=-Host de la CPU, hv_relaxed, hv_spinlocks=0x1fff, hv_vapic, hv_time}}.<br />
* Si la máquina host tiene varias CPUs, asigne al invitado más CPUs usando la opción {{ic|-smp}}.<br />
* Asegúrese de haber asignado a la máquina virtual suficiente memoria. De forma predeterminada, QEMU sólo asigna 128 MiB de memoria a cada máquina virtual. Utilice la opción {{ic|-m}} para asignar más memoria. Por ejemplo, {{ic|-m 1024}} ejecuta una máquina virtual con 1024 MiB de memoria.<br />
* Utilice KVM si es posible: agregue {{ic|1=-machine type=pc, accel=kvm}} al comando de arranque QEMU que utilice.<br />
* Si es compatible con los controladores del sistema operativo invitado, utilice [https://wiki.libvirt.org/page/Virtio virtio] para dispositivos de red y/o bloque. Por ejemplo:<br />
$ qemu-system-i386 -net nic, model=virtio -net tap, if=tap0, script=no-drive file=''disk_image'',media=disco, if=virtio<br />
* Utilizar dispositivos TAP en lugar de redes en modo usuario. Consulte [[#Tap de red con QEMU]].<br />
* Si el sistema operativo invitado está haciendo escritura pesada en su disco, puede beneficiarse de ciertas opciones de montaje en el sistema de archivos del host. Por ejemplo, puede montar un [[Ext4|sistema de archivos ext4]] con la opción {{ic|1=barrier=0}}. Debe leer la documentación de las opciones que cambie porque a veces las opciones de mejora de rendimiento para los sistemas de archivos tienen el costo de integridad de los datos.<br />
* Si tiene una imagen de disco sin procesar, puede deshabilitar la caché:<br />
$ qemu-system-i386 -drive file=''disk_image'', if=virtio, cache=none<br />
* Utilice el nativo Linux AIO:<br />
$ qemu-system-i386 -drive file=''disk_image'', if=virtio, aio=native<br />
* Si utiliza una imagen de disco qcow2, el rendimiento de E/S se puede mejorar considerablemente al garantizar que el caché L2 es de tamaño suficiente. La fórmula [https://blogs.igalia.com/berto/2015/12/17/improving-disk-io-performance-in-qemu-2-5-with-the-qcow2-l2-cache/] para calcular La caché L2 es: l2_cache_size = disk_size * 8 / cluster_size. Suponiendo que la imagen qcow2 se creó con el tamaño de clúster predeterminado de 64 K, esto significa que para cada 8 GB de tamaño de la imagen qcow2, 1 MB de caché L2 es mejor para el rendimiento. QEMU utiliza sólo 1 MB por defecto; Especificar una caché más grande se hace en la línea de comandos QEMU. Por ejemplo, para especificar 4 MB de caché (adecuado para un disco de 32 GB con un tamaño de clúster de 64 KB):<br />
$ qemu-system-i386 -drive file=''disk_image'',format=qcow2, l2-cache-size=4M<br />
* Si está ejecutando varias máquinas virtuales al mismo tiempo que todas tienen el mismo sistema operativo instalado, puede ahorrar memoria al habilitar [[wikipedia: Kernel_SamePage_Merging_ (KSM)|kernel de la misma página de fusión]]. Consulte [[#Habilitar KSM]].<br />
* En algunos casos, la memoria se puede recuperar de correr máquinas virtuales ejecutando un controlador de globo de memoria en el sistema operativo invitado y lanzando QEMU con la opción {{ic|-balloon virtio}}.<br />
* Es posible utilizar una capa de emulación para un controlador ICH-9 AHCI (aunque puede ser inestable). La emulación AHCI soporta [[Wikipedia: Native_Command_Queuing|NCQ]], por lo que varias peticiones de lectura o escritura pueden estar pendientes al mismo tiempo:<br />
$ qemu-system-i386 -drive id=disc, file=''disk_image'', if=none -device ich9-ahci, id=ahci -device ide-drive, drive=disk, bus=ahci.0<br />
<br />
Mira https://www.linux-kvm.org/page/Tuning_KVM para más información.<br />
<br />
=== El cursor del ratón está nervioso o errático ===<br />
<br />
Si el cursor "brinca" descontroladamente, podría ayudar ingresar este comando en la terminal antes de iniciar QEMU<br />
<br />
$ export SDL_VIDEO_X11_DGAMOUSE=0<br />
<br />
Si funciono, puedes agregarlo a tu {{ic|~/.bashrc}} archivo.<br />
<br />
=== El cursor no es visible ===<br />
<br />
Añade {{ic|-show-cursor}} a las opciones de QEMU para poder ver el cursor.<br />
<br />
Si persiste, asegurate de configurar la pantalla apropiadamente<br />
<br />
Por ejemplo: {{ic|-vga qxl}}<br />
<br />
=== No se puede mover / adjuntar el cursor ===<br />
<br />
Reemplaza {{ic|-usbdevice tablet}} con {{ic|-usb}} como opción en QEMU.<br />
<br />
=== El teclado parece roto ó las teclas de flecha no funcionan ===<br />
<br />
Probablemente notarás que algunas de tus teclas no funcionan ó "presionan" la tecla equivocada (en particular, las flechas), preferentemente, necesitas especificar la distribución de tu teclado como una opción. La distribución del teclado puede encontrarse en {{ic|/usr/share/qemu/keymaps}}.<br />
<br />
$ qemu-system-i386 -k ''keymap'' ''disk_image''<br />
<br />
=== Pantalla de invitado estirada en el tamaño de la ventana ===<br />
<br />
Para restarurar el tamaño por defecto de la ventanta, presiona {{ic|Ctrl+Alt+u}}.<br />
<br />
=== ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy ===<br />
<br />
Si un mensaje de error como este es listado en el arranque de QEMU con la opción {{ic|-enable-kvm}}:<br />
<br />
ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy<br />
failed to initialize KVM: Device or resource busy<br />
<br />
Significa que otro [[hypervisor]] está actualmente activo. No se recomienda ó no es poible correr varios hypervisores en paralelo.<br />
<br />
=== Mensaje de error libgfapi ===<br />
<br />
El mensaje de error listado en el arranque:<br />
<br />
Failed to open module: libgfapi.so.0: cannot open shared object file: No such file or directory<br />
<br />
No es un problema, sólo significa que hace falta la dependencia opcional de GlusterFS<br />
<br />
=== Kernel panic en entornos live ===<br />
<br />
Si inicia un sistema en vivo (ó bootea uno) podría encontrar esto:<br />
<br />
end Kernel panic - not syncing: VFS: Unable to mount root fs on unknown block(0,0)<br />
<br />
Ó algún otro proceso de arranque (ej. no se puede desempaquetar initramfs, no puede iniciar un servicio foo).<br />
<br />
Intente iniciar la Máquina Virtual con el {{ic|-m VALOR}} switch y un tamaño apropiado de RAM, si la RAM es muy poca probablemente encontrará problemas similares a los anteriores.<br />
<br />
== Ver también ==<br />
<br />
* [https://qemu.org Sitio web oficial de QEMU]<br />
* [https://www.linux-kvm.org Sitio web oficial de KVM]<br />
* [https://web.archive.org/web/20200514080826/https://qemu.weilnetz.de/doc/qemu-doc.html Documentación para el usuario del emulador QEMU] (en inglés)<br />
* [https://en.wikibooks.org/wiki/QEMU Wikilibro de QEMU] (en inglés)<br />
* [http://alien.slackbook.org/dokuwiki/doku.php?id=slackware:qemu Virtualización de hardware con QEMU por AlienBOB (última actualización en 2008) (en inglés)<br />
* [http://blog.falconindy.com/articles/build-a-virtual-army.html Construyendo un ejército virtual] por Falconindy (en inglés)<br />
* [https://git.qemu.org/?p=qemu.git;a=tree;f=docs Últimos documentos]<br />
* [https://qemu.weilnetz.de/ QEMU en Windows]<br />
* [[wikipedia:Qemu|Wikipedia]]<br />
* [https://wiki.debian.org/QEMU QEMU - Wiki de Debian] (en inglés)<br />
* [https://people.gnome.org/~markmc/qemu-networking.html QEMU Networking on gnome.org]{{Dead link (Español)|2022|09|22|status=404}}<br />
* [http://bsdwiki.reedmedia.net/wiki/networking_qemu_virtual_bsd_systems.html Red virtual de QEMU en sistemas BSD] (en inglés)<br />
* [https://www.gnu.org/software/hurd/hurd/running/qemu.html QEMU on gnu.org]<br />
* [https://wiki.freebsd.org/qemu QEMU en FreeBSD como host] (en inglés)</div>Malcontenthttps://wiki.archlinux.org/index.php?title=QEMU_(Espa%C3%B1ol)&diff=796048QEMU (Español)2024-01-04T16:32:13Z<p>Malcontent: Fix section issue</p>
<hr />
<div>[[Category:Emulation (Español)]]<br />
[[Category:Hypervisors (Español)]]<br />
[[de:QEMU]]<br />
[[en:QEMU]]<br />
[[fr:QEMU]]<br />
[[ja:QEMU]]<br />
[[zh-hans:QEMU]]<br />
{{Bad translation (Español)|No updates since 2017-01-12, English page has seen major changes since.}}<br />
{{TranslationStatus (Español)|QEMU|2017-01-12|463282}}<br />
{{Related articles start (Español)}}<br />
{{Related|:Category:Hypervisors}}<br />
{{Related|Libvirt}}<br />
{{Related articles end}}<br />
<br />
De acuerdo con [https://wiki.qemu.org/Main_Page la wiki de QEMU], "QEMU es un emulador genérico y de código abierto de máquinas virtuales."<br />
<br />
Cuando se utiliza como un emulador de máquina, QEMU puede correr sistemas operativos y programas hechos para una máquina en particular (por ej. una placa ARM) en una máquina diferente (e.j. tu PC x86). Usando la traducción dinámica, se consigue un rendimiento muy bueno.<br />
<br />
QEMU puede usar hipervisores como [[Xen]] o [[KVM]] para utilizar las extensiones del procesador para la virtualización. Cuando se utiliza como virtualizador, QEMU alcanza un performance cercano a el rendimiento nativo ejecutando el código de invitado directamente en el CPU host.<br />
<br />
== Instalación ==<br />
<br />
[[Help:Reading (Español)#Instalación de paquetes|Instale]] el paquete {{Pkg|qemu-desktop}} (ó {{Pkg|qemu-base}} para la versión sin GUI) y los paquetes opcionales para tus necesidades:<br />
<br />
* {{Pkg|qemu-emulators-full}} - Soporte extra para arquitecturas<br />
* {{Pkg|qemu-block-gluster}} - Soporte para bloque glusterfs <br />
* {{Pkg|qemu-block-iscsi}} - Soporte para bloque iSCSI <br />
* {{Pkg|qemu-block-rbd}}{{Broken package link (Español)|package not found}} - Soporte para bloque RBD <br />
* {{Pkg|samba}} - SMB/ Soporte para servidor CIFS<br />
<br />
== front-ends para QEMU ==<br />
<br />
A diferencia de otros programas de virtualización como [[VirtualBox]] y [[VMware]], QEMU no proporciona una interfaz gráfica de usuario para administrar máquinas virtuales (a parte de la ventana que aparece cuando se ejecuta una máquina virtual), tampoco proporciona una forma de crear una máquina virtual persistente con valores guardados. Todos los parámetros para ejecutar una máquina virtual deben especificarse en la línea de comandos en cada puesta en marcha, a menos que haga un script personalizadp para iniciar su máquina(s) virtual. Sin embargo, hay varios front-end GUI para QEMU: <br />
<br />
* {{AUR|qemu-launcher}}<br />
* {{AUR|qtemu}}<br />
* {{AUR|aqemu}}<br />
<br />
front-ends con soporte para QEMU están disponibles por [[libvirt]].<br />
<br />
== Creando un nuevo sistema virtualizado ==<br />
<br />
=== Creando una imagen de disco duro ===<br />
<br />
{{Tip (Español)|Véase la [https://en.wikibooks.org/wiki/QEMU/Images Wiki de QEMU] para más información sobre imágenes de QEMU.}}<br />
<br />
Para ejecutar QMEU necesitarás una imagen de disco duro, a menos que estés cargando un sistema en vivo desde el CD-ROM ó la red (y no para instalar un sistema operativo en una imagen de disco duro). Una imagen de disco es un archivo que almacena los contenidos del disco duro emulado.<br />
<br />
Una imagen de disco puede ser en "crudo", de manera que, literalemte, byte por byte es lo mismo que el cliente ve, y siempre utilizará toda la capacidad del disco duro del disco duro invitado en el host. Este método proporciona la menor sobrecarga de Entrada / Salida, pero puede desperdiciar una gran cantidad de espacio, ya que el espacio no utilizado por el invitado no se puede utilizar en el host. <br />
<br />
Por otra parte, la imagen de disco duro puede estar en un formato tal como el de ''qcow2'' el cuál únicamente asigna espacio a el archivo de la imagen cuando el SO invitado está escribiendo en los sectores del disco virtual. La imagen aparece como el tamaño total del sistema operativo huésped, a pesar que puede tomar hasta una cantidad muy pequeña de espacio en el sistema host. El uso de este formato en lugar de el "crudo" probablemente afecte el rendimiento. <br />
<br />
QEMU proporciona el {{ic|qemu-img}} comando para crear imagenes de disco.<br />
Por ejemplo, para crear una imagen de 4GB en formato "crudo":<br />
<br />
$ qemu-img create -f raw ''image_file'' 4G<br />
<br />
Se puede uiltizar {{ic|-f qcow2}} para crear un disco ''qcow2'' en su lugar. <br />
<br />
{{Note (Español)|También puedes simplemente crear una imagen "cruda" meidante la creación de un archivo del tamaño necesitado usando {{ic|dd}} ó {{ic|fallocate}}.}}<br />
<br />
{{Warning (Español)|Si almacenas una imágen de disco en un sistema de archivos [[Btrfs (Español)|Btrfs]], deberías considerar deshabilitar [[Btrfs (Español)#Copy-on-Write (CoW)|Copy-on-Write]] para el directorio antes de crear imágenes.}}<br />
<br />
==== Superposición de imágenes de almacenamiento ====<br />
<br />
Puede crear una imagen de almacenamiento una vez (la imagen de respaldo) y hacer que QEMU mantenga mutaciones a esta imagen en una imagen de superposición. Esto le permite volver a un estado anterior de esta imagen de almacenamiento. Puede volver a crear una nueva imagen de superposición en el momento en que desea revertir en función de la imagen de respaldo original.<br />
<br />
Para crear una imagen de superposición, ingrese el comando:<br />
<br />
$ qemu-img create -o backing_file=''img1.raw'',backing_fmt=''raw'' -f ''qcow2'' ''img1.cow''<br />
<br />
Después de eso, puede ejecutar su máquina virtual como de costumbre (ver [[#Ejecución del sistema virtualizado]]):<br />
<br />
$ qemu-system-x86_64 ''img1.cow''<br />
<br />
La imagen de respaldo se dejará intacta y se registrarán mutaciones en este almacenamiento en el archivo de imagen de superposición.<br />
<br />
Cuando cambia la ruta de acceso a la imagen de respaldo, se requiere reparación.<br />
<br />
{{Warning (Español)|La ruta del sistema de archivos absoluto de la imagen de respaldo se almacena en el archivo de imagen de superposición (binario)). Cambiar el trayecto de la imagen de respaldo requiere un esfuerzo.}}<br />
<br />
Asegúrese de que la ruta de la imagen de respaldo original sigue conduciendo a esta imagen. Si es necesario, haga un enlace simbólico en la ruta original a la nueva ruta. A continuación, emita un comando como:<br />
<br />
$ qemu-img rebase -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
A su discreción, usted puede alternativamente realizar un rebase 'inseguro' donde no se comprueba la ruta anterior a la imagen de respaldo:<br />
<br />
$ qemu-img rebase -u -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
==== Cambiar el tamaño de una imagen ====<br />
<br />
{{Warning (Español)|Cambiar el tamaño de una imagen que contiene un sistema de arranque NTFS podría hacer el sistema operativo instalado '''no arrancable'''. Para una explicación completa y solucioón alternativa mira [https://web.archive.org/web/20180319230757/http://tjworld.net/wiki/Howto/ResizeQemuDiskImages].}}<br />
<br />
El ejecutable {{ic|qemu-img}} tiene la opción {{ic|resize}}, que permite redimensionar fácilmente una imagen de disco duro. Funciona tanto para ''raw'' como para ''qcow2''. Por ejemplo, para aumentar el espacio de imagen en 10GB, ingresa:<br />
<br />
$ qemu-img resize ''disk_image'' +10G<br />
<br />
Después de ampliar la imagen de disco, debe utilizar el sistema de archivos y las herramientas de particionamiento dentro de la máquina virtual para comenzar a utilizar el nuevo espacio. Al reducir una imagen de disco, primero debe reducir los sistemas de archivos y los tamaños de partición asignados usando el sistema de archivos y las herramientas de partición dentro de la máquina virtual y luego reducir la imagen del disco en consecuencia, de lo contrario reducir la imagen del disco resultará en ¡pérdida de datos!<br />
<br />
=== Preparando el medio de instalación ===<br />
<br />
Para instalar un sistema operativo en su imagen de disco, necesita el medio de instalación (por ejemplo, disco óptico, unidad USB o imagen ISO) para el sistema operativo. El soporte de instalación no debe montarse porque QEMU accede directamente al medio.<br />
<br />
{{Tip (Español)|Si utiliza un disco óptico, es una buena idea volcar primero los medios a un archivo porque esto mejora el rendimiento y no requiere que tenga acceso directo a los dispositivos (es decir, puede ejecutar QEMU como un usuario normal sin tener Para cambiar permisos de acceso en el archivo de dispositivo del medio). Por ejemplo, si el nodo de dispositivo de CD-ROM tiene el nombre {{ic|/dev/cdrom}}, puede volcarlo a un archivo de comandos: {{bc|1=$ dd if=/dev/cdrom of=''Cd_image.iso''}}}}<br />
<br />
=== Instalando el sistema operativo ===<br />
<br />
Esta es la primera vez que necesitará iniciar el emulador. Para instalar el sistema operativo en la imagen de disco, debe adjuntar la imagen de disco y el medio de instalación a la máquina virtual y hacer que arranque desde el soporte de instalación.<br />
<br />
Por ejemplo, en invitados i386, para instalar desde un archivo ISO de arranque como CD-ROM y una imagen de disco sin formato:<br />
<br />
$ qemu-system-x86_64 -cdrom ''iso_image'' -boot order=d -drive file=''disk_image'',format=raw<br />
<br />
Consulte {{ic | qemu (1)}} para obtener más información sobre cómo cargar otros tipos de medios (como disquetes, imágenes de disco o unidades físicas) y [[#Ejecución del sistema virtualizado]] para otras opciones útiles.<br />
<br />
Una vez que el sistema operativo haya finalizado de instalar, la imagen de QEMU se puede iniciar directamente (ver [[#Ejecución del sistema virtualizado]]).<br />
<br />
{{Warning (Español)|De forma predeterminada, sólo se asignan 128 MB de memoria a la máquina. La cantidad de memoria se puede ajustar con el interruptor {{ic | -m}}, por ejemplo {{ic | -m 512M}} o {{ic | -m 2G}}.}}<br />
<br />
{{Tip (Español)|<br />
* En lugar de especificar {{ic | 1 = -boot order = x}}, algunos usuarios pueden sentirse más cómodos usando un menú de arranque: {{ic | 1 = -boot menu = on}}, al menos durante la configuración y la experimentación.<br />
* Si necesita reemplazar disquetes o CD como parte del proceso de instalación, puede usar el monitor de la máquina QEMU (presione {{ic | Ctrl + Alt + 2}} en la ventana de la máquina virtual) para quitar y conectar dispositivos de almacenamiento a un máquina virtual. Escriba {{ic | info block}} para ver los dispositivos de bloque y use el comando {{ic | change}} para intercambiar un dispositivo. Pulse {{ic | Ctrl + Alt + 1}} para volver a la máquina virtual.}}<br />
<br />
== Ejecución del sistema virtualizado ==<br />
<br />
Los binarios {{ic|qemu-system-*}} (por e.j. {{ic|qemu-system-i386}} ó {{ic|qemu-system-x86_64}}, dependiendo de la arquitectura del huésped) se usan para ejecutar el sistema virtualizado. El uso es:<br />
<br />
$ qemu-system-x86_64 ''options'' ''disk_image''<br />
<br />
Las opciones son las mismas para todos los binarios {{ic|qemu-system-*}}, mira {{ic|qemu(1)}} para más información sobre todas las opciones.<br />
<br />
Por defecto, QEMU mostrará la salida de video de la máquina virtual en una ventana. Una cosa a considerar: al hacer click dentro de la ventana de QMEU, el puntero del cursor será capturado. Para liberarlo presione {{ic|Ctrl+Alt+g}}.<br />
<br />
{{Warning (Español)|QEMU nunca debe ejecutarse como root. Si se debe iniciar en root, deberá usar la opción {{ic|-runas}} para que QEMU utilice privilegios de root.}}<br />
<br />
=== Activar KVM ===<br />
<br />
KVM debe ser soportado por su procesador y kernel, y necesariamente los [[kernel modules (Español)|módulos del kernel]] deben ser cargados. Mira [[KVM]] para más información.<br />
<br />
Para iniciar QEMU en modo KVM, adjunta {{ic|-enable-kvm}} a las opciones de inicio adicionales. Para verificar si KVM está activado para ejecutar una máquina virtual, ingresa a la wiki de QEMU [https://en.wikibooks.org/wiki/QEMU/Monitor Monitor], usando {{ic|Ctrl+Alt+Shift+2}}, e ingresando {{ic|info kvm}}. <br />
<br />
{{Note (Español)|<br />
* Si inicia su máquina virtual con una herramienta GUI y experimenta un rendimiento muy malo, debe verificar el soporte adecuado de KVM. <br />
* KVM necesita activarse en orden de iniciar adecuadamente Windows 7 y Windows 8 sin ''pantallazo azul''.<br />
}}<br />
<br />
=== Habilitar soporte IOMMU (Intel VT-d/AMD-Vi) ===<br />
<br />
Usando IOMMU (unidad de gestión de memoria de entrada y salida) se abre a las caraterísticas como el paso del PCI y la protección de la memoria de dispositivos defectuosos o maliciosos, mira [[wikipedia:Input-output memory management unit#Advantages]] y [https://www.quora.com/Memory-Management-computer-programming/Could-you-explain-IOMMU-in-plain-English Memory Management (computer programming): Could you explain IOMMU in plain English?].<br />
<br />
Para habilitar IOMMU:<br />
#Asegure que AMD-Vi/Intel VT-d es soportado por el CPU y es habilitado en la configuración de BIOS.<br />
#Agregue {{ic|1=intel_iommu=on}} si tienes un procesador Intel ó {{ic|1=amd_iommu=on}} si tienes un procesador AMD en los parámetros del kernel ([[kernel parameters]])<br />
#Reinicie y asegure que IOMMU está habilitado verificando {{ic|dmesg}} para {{ic|DMAR}}: {{ic|[0.000000] DMAR: IOMMU enabled}}<br />
#Añade {{ic|-device intel-iommu}} para crear el dispositivo IOMMU:<br />
<br />
$ qemu-system-x86_64 '''-enable-kvm -machine q35 -device intel-iommu''' -cpu host ..<br />
<br />
== Mover datos entre el host y el Sistema Operativo huésped ==<br />
<br />
=== Red ===<br />
<br />
Los datos pueden compartirse entre el host y el sistema operativo huésped usando cualquier protocolo de red que pueda transferir archivos, como [[NFS]], [[SMB]], [[Wikipedia:Network Block Device|NBD]], HTTP, [[Very Secure FTP Daemon|FTP]], ó [[SSH]], siempre que haya configurado la red apropiadamente y haya habilitado los servicios apropiados. <br />
<br />
La red por defecto del modo de usuario permite al huésped acceder al sistema operativo host en la dirección IP 10.0.2.2. Todos los servidores que se estén ejecutando en el sistema operativo anfitrión, como un servidor SSH o un servidor SMB, estarán accesibles en esta dirección IP. Así que en los invitados, puede montar los directorios exportados en el host a través de [[SMB]] o [[NFS]], o puede acceder al servidor HTTP del host, etc.<br />
No será posible que el sistema operativo anfitrión acceda a los servidores que se ejecutan en el sistema operativo invitado, pero esto puede hacerse con otras configuraciones de red (consulte [[#Tap de red con QEMU]]).<br />
<br />
=== Servidor SMB incorporado de QEMU ===<br />
<br />
La documentación de QEMU dice que tiene un servidor SMB "incorporado", pero en realidad acaba de iniciar [[Samba]] con un archivo {{ic | smb.conf}} generado automáticamente ubicado en {{ic|/tmp/qemu- Smb.''Pid''-0/smb.conf}} y lo hace accesible para el invitado en una dirección IP diferente (10.0.2.4 por defecto). Esto sólo funciona para la red de usuarios, y esto no es necesariamente muy útil ya que el invitado también puede acceder al servicio normal [[Samba]] en el host si ha configurado acciones en él.<br />
<br />
Para habilitar esta característica, inicie QEMU con un comando como:<br />
<br />
$ qemu-system-x86_64 -nic user,id=nic0,smb=''shared_dir_path'' ''disk_image''<br />
<br />
donde {{ic|''shared_dir_path''}} es un directorio que quieres compartir entre huésped y el host.<br />
<br />
Luego, en el invitado, podrá acceder al directorio compartido del host 10.0.2.4 con el nombre de recurso "qemu". Por ejemplo, en el Explorador de Windows iría a {{ic | \\ 10.0.2.4 \ qemu}}.<br />
<br />
{{Note (Español)|<br />
* Si estás usando opciones de compartir varias veces como {{ic|1=-net user, smb='' shared_dir_path1 '' -net user, smb='' shared_dir_path2 ''}} ó {{ic | 1 = -net user , Smb = '' shared_dir_path1 '', smb = '' shared_dir_path2 ''}} entonces solo compartirá el último definido.<br />
* Si no puede acceder a la carpeta compartida y el sistema invitado es Windows, compruebe que está habilitado el protocolo [http://ecross.mvps.org/howto/enable-netbios-over-tcp-ip-with-windows.htm NetBIOS ]{{Dead link (Español)|2023|05|06|status=domain name not resolved}} Y que un cortafuegos no bloquea los puertos [https://technet.microsoft.com/en-us/library/cc940063.aspx] utilizados por el protocolo NetBIOS.<br />
}}<br />
<br />
=== Montaje de una partición dentro de una imagen de disco raw ===<br />
<br />
Cuando la máquina virtual no se está ejecutando, es posible montar las particiones que están dentro de un archivo de imagen de disco sin formato configurándolas como dispositivos de bucle invertido. Esto no funciona con imágenes de disco en formatos especiales, como qcow2, aunque se pueden montar usando {{ic|qemu-nbd}}.<br />
<br />
{{Warning (Español)| Debe asegurarse de desmontar las particiones antes de ejecutar la máquina virtual de nuevo. De lo contrario, es muy probable que ocurra la corrupción de datos.}}<br />
<br />
==== Con la especificación manual del desplazamiento de bytes ====<br />
<br />
Una forma de montar una partición de imagen de disco es montar la imagen de disco en un cierto desplazamiento usando un comando como el siguiente:<br />
<br />
$ mount -o loop, offset = 32256 ''disk_image'' ''mountpoint''<br />
<br />
La opción {{ic|1 = offset = 32256}} se pasa realmente al programa {{ic|losetup}} para configurar un dispositivo de bucle invertido que empieza en el desplazamiento de byte 32256 del archivo y continúa hasta el final. A continuación, se monta este dispositivo de bucle invertido. También puede utilizar la opción {{ic|sizelimit}} para especificar el tamaño exacto de la partición, pero esto normalmente no es necesario.<br />
<br />
Dependiendo de la imagen del disco, la partición necesaria no se puede iniciar en el desplazamiento 32256. Ejecute {{ic|fdisk -l '' disk_image ''}} para ver las particiones de la imagen. Fdisk da las compensaciones de inicio y fin en sectores de 512 bytes, así que multiplique por 512 para obtener el desplazamiento correcto para pasar a {{ic|mount}}.<br />
<br />
==== Con las particiones autodetecting del módulo de bucle (loop) ====<br />
<br />
El controlador de bucle de Linux realmente admite particiones en dispositivos de bucle invertido, pero está desactivado de forma predeterminada. Para habilitarlo, haga lo siguiente:<br />
<br />
* Deshacerse de todos los dispositivos de bucle invertido (desmontar todas las imágenes montadas, etc.).<br />
* [[Kernel modules (Español)#Manejo manual de módulos|Descargar]] el módulo del kernel {{ic|loop}} y cargarlo con el conjunto de parámetros {{ic|1 = max_part = 15}}. Además, el número máximo de dispositivos de bucle puede controlarse con el parámetro {{ic | max_loop}}.<br />
<br />
{{Tip (Español)|Puede poner una entrada en {{ic|/etc/modprobe.d}} para cargar el módulo de bucle con {{ic|1=max_part=15}} cada vez, o puede poner {{ic|1 = loop.max_part = 15}} en la línea de comandos del kernel, dependiendo de si tiene o no el módulo {{ic|loop.ko}} integrado en su kernel.}}<br />
<br />
Configure su imagen como un dispositivo de bucle invertido:<br />
<br />
$ losetup -f -P ''disk_image''<br />
<br />
Entonces, si el dispositivo creado fue {{ic|/dev/loop0}}, se habrán creado automáticamente dispositivos adicionales {{ic|/dev/loop0pX}}, donde X es el número de la partición. Estos dispositivos de loopback de partición se pueden montar directamente. Por ejemplo:<br />
<br />
$ mount /dev/loop0p1 ''punto de montaje''<br />
<br />
Para montar la imagen de disco con '' udisksctl '', vea [[Udisks#Mount loop devices]].<br />
<br />
==== Con kpartx ====<br />
<br />
'' 'Kpartx' '' del paquete {{Pkg|multipath-tools}} puede leer una tabla de particiones en un dispositivo y crear un nuevo dispositivo para cada partición. Por ejemplo:<br />
# Kpartx -a '' disk_image ''<br />
<br />
Esto configurará el dispositivo de bucle invertido y creará los dispositivos de partición necesarios en {{ic|/dev/mapper/}}.<br />
<br />
=== Montar una partición dentro de una imagen qcow2 ===<br />
<br />
Puede montar una partición dentro de una imagen qcow2 usando {{ic|qemu-nbd}}. Mira [https://en.wikibooks.org/wiki/QEMU/Images#Mounting_an_image_on_the_host Wikibooks].<br />
<br />
=== Utilizar cualquier partición real como la única partición primaria de una imagen de disco duro ===<br />
<br />
A veces, puede que desee utilizar una de las particiones del sistema desde dentro de QEMU. El uso de una partición sin procesar para una máquina virtual mejorará el rendimiento, ya que las operaciones de lectura y escritura no pasan por la capa del sistema de archivos del host físico. Esta partición también proporciona una forma de compartir datos entre el host y el invitado.<br />
<br />
En Arch Linux, los archivos de dispositivo para las particiones sin procesar son, por defecto, propiedad de '' root '' y del grupo '' disk ''. Si desea que un usuario no root pueda leer y escribir en una partición en bruto, debe cambiar el propietario del archivo de dispositivo de la partición para ese usuario.<br />
<br />
{{Warning (Español)|<br />
* Aunque es posible, no se recomienda permitir que las máquinas virtuales alteren los datos críticos en el sistema host, como la partición raíz.<br />
* No debe montar un sistema de archivos en una partición de lectura-escritura en el host y el invitado al mismo tiempo. De lo contrario, se producirá corrupción de datos.<br />
}}<br />
<br />
Después de hacerlo, puede adjuntar la partición a una máquina virtual QEMU como un disco virtual.<br />
<br />
Sin embargo, las cosas son un poco más complicadas si desea tener la máquina virtual ''completa'' contenida en una partición. En ese caso, no habría ningún archivo de imagen de disco para arrancar realmente la máquina virtual, ya que no se puede instalar un cargador de arranque en una partición que está formateada como un sistema de archivos y no como un dispositivo particionado con un MBR. Una máquina virtual de este tipo se puede iniciar especificando el kernel y el initramfs manualmente o simulando un disco con un MBR usando RAID lineal.<br />
<br />
==== Especificar el kernel y el initrd manualmente ====<br />
<br />
QEMU es compatible con cargar [[Kernels|Linux kernels]] e [[initramfs|init ramdisks]] directamente, evitando así los cargadores de arranque como [[GRUB]]. A continuación, se puede iniciar con la partición física que contiene el sistema de archivos raíz como el disco virtual, que no parecen ser particionados. Esto se hace emitiendo un comando similar al siguiente:<br />
<br />
{{Note (Español)| En este ejemplo, se trata de las imágenes del '''host''' que se están utilizando, no del invitado. Si desea utilizar las imágenes del huésped, monte {{ic|/dev/sda3}} de sólo lectura (para proteger el sistema de archivos del host) y especifique {{ic|/full/path/to/images}} ó usar algún truco kexec en el invitado para recargar el kernel del invitado (extiende el tiempo de arranque).}}<br />
<br />
$ Qemu-system-i386 -kernel /boot/vmlinuz-linux -initrd /boot/initramfs-linux.img -append root=/dev/sda/dev/sda3<br />
<br />
En el ejemplo anterior, la partición física que se utiliza para el sistema de archivos raíz del huésped es {{ic|/dev/sda3}} en el host, pero aparece como {{ic|/dev/sda}} en el invitado.<br />
<br />
Por supuesto, puede especificar cualquier kernel e initrd que desee, y no sólo los que vienen con Arch Linux.<br />
<br />
Cuando hay varios [[kernel parameters]] que se pasan a la opción {{ic|-append}}, necesitan ser citados usando comillas simples o dobles. Por ejemplo:<br />
<br />
$ ... -append 'root=/dev/sda1 console=ttyS0'<br />
<br />
==== Simular disco virtual con MBR usando RAID lineal ====<br />
<br />
Una forma más complicada de tener una máquina virtual usar una partición física, mientras que mantener esa partición formateada como un sistema de archivos y no sólo tener la partición invitado la partición como si fuera un disco, es simular un MBR para que pueda Arranque utilizando un gestor de arranque tal como GRUB.<br />
<br />
Puede hacerlo utilizando el RAID del software en modo lineal (necesita el controlador de kernel {{ic|linear.ko}}) y un dispositivo de loopback: el truco consiste en añadir previamente un registro maestro de arranque (MBR) Real que desea incrustar en una imagen de disco RAEM QEMU.<br />
<br />
Suponga que tiene una partición simple {{ic|/|hdaN}} con algún sistema de archivos en la que desea formar parte de una imagen de disco QEMU. En primer lugar, crear un pequeño archivo para mantener el MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=32<br />
<br />
Aquí, se crea un archivo de 16 KB (32 * 512 bytes). Es importante no hacerlo demasiado pequeño (incluso si el MBR sólo necesita un bloque de 512 bytes), ya que cuanto menor sea, menor será el tamaño del chasis del dispositivo RAID de software, lo que podría tener un impacto En el rendimiento. A continuación, configura un dispositivo de bucle invertido en el archivo MBR:<br />
<br />
# losetup -f ''/path/to/mbr''<br />
<br />
Supongamos que el dispositivo resultante es {{ic|/dev/loop0}}, porque ya no habríamos estado usando otros bucle. El siguiente paso es crear la imagen de disco "fusionada" MBR + {{ic|/dev/hda''N''}} utilizando RAID de software:<br />
<br />
# modprobe lineal<br />
<br />
# mdadm --build --verbose /dev/md0 --chunk=16 --level=linear --raid-devices=2 /dev/loop0/dev/hda''N''<br />
<br />
El resultante {{ic|/dev/md0}} es lo que utilizará como una imagen de disco cruda QEMU (no olvide establecer los permisos para que el emulador pueda acceder a él). El último paso (y algo complicado) es configurar la configuración del disco (geometría del disco y tabla de particiones) para que el punto de inicio de la partición primaria en el MBR coincida con el de {{ic|/dev/hda''N''}}} Dentro {{ic|/dev/md0}} (un desplazamiento de exactamente 16 * 512 = 16384 bytes en este ejemplo). Hacer esto usando {{ic|fdisk}} en la máquina host, no en el emulador: la rutina de detección de disco crudo predeterminada de QEMU a menudo da lugar a offsets redondeados no kilobyte (como 31.5 KB, como en la sección anterior) que No puede ser administrado por el código RAID de software. Por lo tanto, desde el anfitrión:<br />
<br />
$ fdisk /dev/md0<br />
<br />
Pulse {{ic|X}} para entrar en el menú de expertos. Establezca el número de sectores por pista para que el tamaño de un cilindro coincida con el tamaño de su archivo MBR. Para dos cabezas y un tamaño de sector de 512, el número de sectores por pista debe ser 16, por lo que obtenemos cilindros de tamaño 2x16x512 = 16k.<br />
<br />
Ahora, presione {{ic|R}} para regresar al menú principal.<br />
<br />
Presione {{ic|P}} y compruebe que el tamaño del cilindro es ahora 16k.<br />
<br />
Ahora, cree una única partición primaria correspondiente a {{ic|/dev/hda''N''}}. Debe comenzar en el cilindro 2 y terminar en el extremo del disco (tenga en cuenta que el número de cilindros ahora difiere de lo que era cuando se introdujo fdisk.<br />
<br />
Finalmente, escribe el resultado al archivo: ya está. Ahora tiene una partición que puede montar directamente desde su host, así como parte de una imagen de disco QEMU:<br />
<br />
$ Qemu-system-i386 -hdc /dev/md0 ''[...]''<br />
<br />
Por supuesto, puede configurar con seguridad cualquier cargador de arranque en esta imagen de disco utilizando QEMU, siempre que la partición original {{ic|/dev/hda''N''}} contenga las herramientas necesarias.<br />
<br />
== Redes ==<br />
<br />
El rendimiento de la red virtual debería ser mejor con los dispositivos de derivación (tap) y puentes que con la red en modo de usuario o vde porque los dispositivos de derivación y los puentes se implementan en el kernel.<br />
<br />
Además, el rendimiento de la red se puede mejorar asignando a las máquinas virtuales un dispositivo de red [https://wiki.libvirt.org/page/Virtio virtio] en lugar de la emulación predeterminada de una NIC e1000. Consulte [[#Instalación de controladores virtio]] para obtener más información.<br />
<br />
=== Advertencia de dirección a nivel de enlace ===<br />
<br />
Al asignar el argumento {{ic|-net nic}} a QEMU, asignará por defecto a una máquina virtual una interfaz de red con la dirección de enlace {{ic|52:54:00:12:34:56}}. Sin embargo, cuando se utiliza la creación de redes puenteadas con varias máquinas virtuales, es esencial que cada máquina virtual tenga una dirección única de nivel de enlace (MAC) en el lado de la máquina virtual del dispositivo de derivación. De lo contrario, el puente no funcionará correctamente, ya que recibirá paquetes de varias fuentes que tienen la misma dirección de nivel de enlace. Este problema se produce incluso si los propios dispositivos de derivación tienen direcciones de nivel de enlace únicas porque la dirección de nivel de enlace de origen no se vuelve a escribir a medida que los paquetes pasan a través del dispositivo de derivación.<br />
<br />
Asegúrese de que cada máquina virtual tiene una dirección única de nivel de enlace, pero siempre debe comenzar con {{ic|52:54:}}. Utilice la opción siguiente, reemplazar ''X'' por un dígito hexadecimal arbitrario:<br />
<br />
$ qemu-system-i386 -net nic,macaddr=52:54:''XX:XX:XX:XX'' -net vde ''disk_image''<br />
<br />
Generar direcciones únicas de nivel de enlace se puede realizar de varias maneras:<br />
<br />
<ol><br />
<li>Especificar manualmente la dirección única de nivel de enlace para cada NIC. El beneficio es que el servidor DHCP asignará la misma dirección IP cada vez que se ejecute la máquina virtual, pero es inutilizable para un gran número de máquinas virtuales.<br />
</li><br />
<li>Generar dirección de nivel de enlace aleatoria cada vez que se ejecuta la máquina virtual. Prácticamente cero probabilidad de colisiones, pero la desventaja es que el servidor DHCP asignará una dirección IP diferente cada vez. Puede utilizar el siguiente comando en una secuencia de comandos para generar una dirección de nivel de enlace aleatoria en una variable {{ic|macaddr}}:<br />
<br />
{{bc|1=<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
qemu-system-i386 -net nic,macaddr="$macaddr" -net vde ''disk_image''<br />
}}<br />
<br />
</li><br />
<li>Utilice el siguiente script {{ic|qemu-mac-hasher.py}} para generar la dirección de nivel de enlace desde el nombre de la máquina virtual mediante una función de hash. Dado que los nombres de las máquinas virtuales son únicos, este método combina los beneficios de los métodos antes mencionados: genera la misma dirección de nivel de enlace cada vez que se ejecuta el script, aunque preserva la probabilidad prácticamente nula de colisiones.<br />
<br />
{{hc|qemu-mac-hasher.py|<nowiki><br />
#!/usr/bin/env python<br />
<br />
import sys<br />
import zlib<br />
<br />
if len(sys.argv) != 2:<br />
print("usage: %s <VM Name>" % sys.argv[0])<br />
sys.exit(1)<br />
<br />
crc = zlib.crc32(sys.argv[1].encode("utf-8")) & 0xffffffff<br />
crc = str(hex(crc))[2:]<br />
print("52:54:%s%s:%s%s:%s%s:%s%s" % tuple(crc))<br />
</nowiki>}}<br />
<br />
En un script, puede utilizar por ejemplo:<br />
<br />
vm_name="''VM Name''"<br />
qemu-system-i386 -name "$vm_name" -net nic,macaddr=$(qemu-mac-hasher.py "$vm_name") -net vde ''disk_image''<br />
</li><br />
</ol><br />
<br />
=== Redes en modo de usuario ===<br />
<br />
De forma predeterminada, sin ningún argumento {{ic|-netdev}}, QEMU utilizará la red en modo usuario con un servidor DHCP incorporado. A sus máquinas virtuales se les asignará una dirección IP cuando ejecuten su cliente DHCP, y podrán acceder a la red del host físico a través de la mascarada de IP realizada por QEMU.<br />
<br />
{{Warning (Español)| Esto sólo funciona con los protocolos TCP y UDP, por lo que ICMP, incluido {{ic|ping}}, no funcionará. No utilice {{ic|ping}} para probar la conectividad de red.}}<br />
<br />
Esta configuración predeterminada permite que sus máquinas virtuales accedan fácilmente a Internet, siempre que el host esté conectado a él, pero las máquinas virtuales no estarán directamente visibles en la red externa ni las máquinas virtuales podrán comunicarse entre sí si empieza Más de uno simultáneamente.<br />
<br />
La red de usuario en modo QEMU puede ofrecer más capacidades, como servidores TFTP o SMB incorporados, redirigir los puertos del host al huésped (por ejemplo, para permitir conexiones SSH al invitado) o conectar invitados a las VLAN para que puedan hablar entre sí. Consulte la documentación de QEMU en el indicador {{ic|-net user}} para obtener más detalles.<br />
<br />
Sin embargo, la conexión en red en modo usuario tiene limitaciones tanto en la utilidad como en el rendimiento. Las configuraciones de red más avanzadas requieren el uso de dispositivos de derivación u otros métodos.<br />
<br />
=== Tap de red con QEMU ===<br />
<br />
Los [[wikipedia:TUN/TAP|dispositivos tap]] Son una característica del kernel de Linux que le permite crear interfaces de red virtuales que aparecen como interfaces de red reales. Los paquetes enviados a una interfaz de derivación se entregan a un programa de espacio de usuario, tal como QEMU, que se ha enlazado a la interfaz.<br />
<br />
QEMU puede utilizar la red de derivación para una máquina virtual de modo que los paquetes enviados a la interfaz de derivación se envíen a la máquina virtual y aparezcan como procedentes de una interfaz de red (normalmente una interfaz Ethernet) en la máquina virtual. Por el contrario, todo lo que la máquina virtual envía a través de su interfaz de red aparecerá en la interfaz de tap.<br />
<br />
Los dispositivos de toque son soportados por los controladores de puente de Linux, por lo que es posible conectar entre sí los dispositivos entre sí y posiblemente con otras interfaces de host como {{ic|eth0}}. Esto es deseable si desea que sus máquinas virtuales puedan hablar entre sí, o si desea que otras máquinas en su LAN puedan hablar con las máquinas virtuales.<br />
<br />
{{Warning (Español)|Si conectas el dispositivo de toque y alguna interfaz de host, como {{ic|eth0}}, las máquinas virtuales aparecerán directamente en la red externa, lo que los exponerá a posibles ataques. Dependiendo de los recursos a los que tengan acceso sus máquinas virtuales, es posible que tenga que tomar todas las [[Firewalls|precauciones]] que normalmente tomaría al asegurar una computadora para proteger sus máquinas virtuales. Si el riesgo es demasiado grande, las máquinas virtuales tienen pocos recursos o se configuran varias máquinas virtuales, una solución mejor podría ser utilizar [[#Red de host solamente]] y configurar NAT. En este caso sólo necesitará un firewall en el host en lugar de múltiples firewalls para cada huésped.}}<br />
<br />
Como se indica en la sección de conexión en red de modo de usuario, los dispositivos de derivación ofrecen un rendimiento de red más alto que el modo de usuario. Si el OS invitado admite el controlador de red virtio, el rendimiento de la red se incrementará considerablemente también. Suponiendo el uso del dispositivo tap0, que el controlador virtio se utiliza en el invitado, y que no se utilizan scripts para ayudar a iniciar / detener la creación de redes, a continuación es parte del comando qemu se debe ver:<br />
<br />
-net nic, model=virtio -net tap, ifname=tap0, script=no, downscript=no<br />
<br />
Pero si ya está utilizando un dispositivo de tap con virtio controlador de red, uno puede incluso aumentar el rendimiento de la red mediante la activación de vhost, como:<br />
<br />
-net nic, model=virtio -net tap, ifname=tap0, script=no, downscript=no, vhost=on<br />
<br />
Ver http://www.linux-kvm.com/content/how-maximize-virtio-net-performance-vhost-net para obtener más información.<br />
<br />
==== Red de host solamente ====<br />
<br />
Si al puente se le da una dirección IP y se permite el tráfico destinado a ello, pero no hay una interfaz real (por ejemplo, {{ic|eth0}}) conectada al puente, las máquinas virtuales podrán hablar entre sí y la Sistema anfitrión. Sin embargo, no podrán hablar con nada en la red externa, siempre y cuando no configure IP enmascarada en el host físico. Esta configuración se llama '' red de host solamente '' por otro software de virtualización como [[VirtualBox]].<br />
<br />
{{Tip (Español)|<br />
* Si desea configurar IP masquerading, ej. NAT para máquinas virtuales, consulte la página [[Internet sharing#Enable NAT]].<br />
* Es posible que desee tener un servidor DHCP que se ejecute en la interfaz de puente para dar servicio a la red virtual. Por ejemplo, para usar la subred {{ic|172.20.0.1/16}} con [[dnsmasq]] como servidor DHCP:<br />
# ip addr add 172.20.0.1/16 dev br0<br />
# ip link set br0 up<br />
# dnsmasq --interface&#61;br0 --bind-interfaces --dhcp-range&#61;172.20.0.2,172.20.255.254<br />
}}<br />
<br />
==== Red interna ====<br />
<br />
Si no le da al puente una dirección IP y agrega una regla [[iptables]] para eliminar todo el tráfico al puente en la cadena INPUT, las máquinas virtuales podrán hablar entre sí, pero no con el host físico ó la red exterior. Esta configuración se llama "red interna" por otro software de virtualización como [[VirtualBox]]. Deberá asignar direcciones IP estáticas a las máquinas virtuales o ejecutar un servidor DHCP en una de ellas.<br />
<br />
De forma predeterminada, iptables eliminaría los paquetes de la red de bridge. Es posible que necesite utilizar dicha regla iptables para permitir paquetes en una red puenteada:<br />
<br />
# iptables -I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Redes puenteadas usando qemu-bridge-helper ====<br />
<br />
{{Note (Español)| Este método está disponible desde QEMU 1.1, consulte https://wiki.qemu.org/Features/HelperNetworking.}}<br />
<br />
Este método no requiere una secuencia de comandos de inicio y acepta fácilmente múltiples tomas y puentes múltiples. Utiliza el binario {{ic|/usr/lib/qemu/qemu-bridge-helper}}, que permite crear dispositivos de derivación en un puente existente.<br />
<br />
{{Tip (Español)|Véase [[Network bridge]] para obtener información sobre cómo crear un puente.}}<br />
<br />
En primer lugar, cree un archivo de configuración que contenga los nombres de todos los puentes que QEMU utilizará:<br />
<br />
{{hc|/etc/qemu/bridge.conf|<br />
allow ''bridge0''<br />
allow ''bridge1''<br />
...}}<br />
<br />
Ahora inicie la VM. El uso más básico sería:<br />
<br />
$ qemu-system-i386 -net nic -net bridge,br=''bridge0'' ''[...]''<br />
<br />
Con múltiples taps, el uso más básico requiere especificar la VLAN para todos los NIC adicionales:<br />
<br />
$ qemu-system-i386 -net nic -net bridge,br=''bridge0'' -net nic,vlan=1 -net bridge,vlan=1,br=''bridge1'' ''[...]''<br />
<br />
==== Creación manual del puente ====<br />
<br />
{{Tip (Español)|Desde QEMU 1.1, el [https://wiki.qemu.org/Features/HelperNetworking puente de red ayudante] puede establecer tun / tap up para usted sin necesidad de secuencias de comandos adicionales. Consulte [[#Redes puenteadas usando qemu-bridge-helper]].}}<br />
<br />
A continuación se describe cómo conectar una máquina virtual con una interfaz de host como {{ic | eth0}}, que es probablemente la configuración más común. Esta configuración hace que parezca que la máquina virtual está ubicada directamente en la red externa, en el mismo segmento Ethernet que la máquina host física.<br />
<br />
Vamos a reemplazar el adaptador Ethernet normal con un adaptador de puente y enlazar el adaptador Ethernet normal a él.<br />
<br />
* Instale {{Pkg|bridge-utils}}, que proporciona {{ic|brctl}} para manipular puentes.<br />
<br />
* Habilitar el reenvío IPv4:<br />
<br />
# sysctl net.ipv4.ip_forward=1<br />
<br />
Para hacer el cambio permanente, cambie {{ic|1=net.ipv4.ip_forward = 0}} a {{ic|1=net.ipv4.ip_forward = 1}} en {{ic|/etc/sysctl.d/99-sysctl.conf}}.<br />
<br />
* Cargue el módulo {{ic|tun}} y configurelo para cargarlo en el arranque. Véase [[Kernel modules (Español)]] para más detalles.<br />
<br />
* Ahora cree el puente. Ver [[Bridge with netctl]] para más detalles. Recuerde nombrar su puente como {{ic|br0}}, o modifique lo scripts a continuación del nombre del puente.<br />
<br />
* Cree el script que QEMU utiliza para abrir el adaptador de toma con los permisos {{ic|root:kvm}} 750:<br />
{{hc|/etc/qemu-ifup|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifup"<br />
echo "Bringing up $1 for bridged mode..."<br />
sudo /usr/bin/ip link set $1 up promisc on<br />
echo "Adding $1 to br0..."<br />
sudo /usr/bin/brctl addif br0 $1<br />
sleep 2<br />
</nowiki>}}<br />
<br />
* Cree el guión que QEMU utiliza para derribar el adaptador de toma en {{ic|/etc/qemu-ifdown}} con los permisos {{ic|root:kvm}} 750:<br />
{{hc|/etc/qemu-ifdown|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifdown"<br />
sudo /usr/bin/ip link set $1 down<br />
sudo /usr/bin/brctl delif br0 $1<br />
sudo /usr/bin/ip link delete dev $1<br />
</nowiki>}}<br />
<br />
* Use {{ic|visudo}} para añadir lo siguiente a el archivo {{ic|sudoers}}:<br />
{{bc|<nowiki><br />
Cmnd_Alias QEMU=/usr/bin/ip,/usr/bin/modprobe,/usr/bin/brctl<br />
%kvm ALL=NOPASSWD: QEMU<br />
</nowiki>}}<br />
<br />
* Se inicia QEMU con el siguiente script {{ic|run-qemu}}:<br />
{{hc|run-qemu|<nowiki><br />
#!/bin/bash<br />
USERID=$(whoami)<br />
<br />
# Get name of newly created TAP device; see https://bbs.archlinux.org/viewtopic.php?pid=1285079#p1285079<br />
precreationg=$(/usr/bin/ip tuntap list | /usr/bin/cut -d: -f1 | /usr/bin/sort)<br />
sudo /usr/bin/ip tuntap add user $USERID mode tap<br />
postcreation=$(/usr/bin/ip tuntap list | /usr/bin/cut -d: -f1 | /usr/bin/sort)<br />
IFACE=$(comm -13 <(echo "$precreationg") <(echo "$postcreation"))<br />
<br />
# This line creates a random MAC address. The downside is the DHCP server will assign a different IP address each time<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
# Instead, uncomment and edit this line to set a static MAC address. The benefit is that the DHCP server will assign the same IP address.<br />
# macaddr='52:54:be:36:42:a9'<br />
<br />
qemu-system-i386 -net nic,macaddr=$macaddr -net tap,ifname="$IFACE" $*<br />
<br />
sudo ip link set dev $IFACE down &> /dev/null<br />
sudo ip tuntap del $IFACE mode tap &> /dev/null<br />
</nowiki>}}<br />
<br />
Para ejecutar una VM, haz algo como esto:<br />
<br />
$ run-qemu -hda ''myvm.img'' -m 512 -vga std<br />
<br />
* Se recomienda, por motivos de rendimiento y seguridad, deshabilitar el firewall [http://ebtables.netfilter.org/documentation/bridge-nf.html en el puente]:<br />
{{hc|/etc/sysctl.d/10-disable-firewall-on-bridge.conf|<nowiki><br />
net.bridge.bridge-nf-call-ip6tables = 0<br />
net.bridge.bridge-nf-call-iptables = 0<br />
net.bridge.bridge-nf-call-arptables = 0<br />
</nowiki>}}<br />
Ejecute {{ic|sysctl -p /etc/sysctl.d/10-disable-firewall-on-bridge.conf}} para aplicar los cambios inmediatamente.<br />
<br />
Ver [https://wiki.libvirt.org/page/Networking#Creating_network_initscripts libvirt wiki] y [https://bugzilla.redhat.com/show_bug.cgi?id=512206 Fedora bug 512206]. Si obtiene errores de sysctl durante el inicio de archivos no existentes, haga que el módulo {{ic|bridge}} se cargue al arrancar. Véase [[Kernel module (Español)#systemd]].<br />
<br />
Como alternativa, puede configurar [[iptables]] para permitir que todo el tráfico se reenvíe a través del puente mediante la adición de una regla como esta:<br />
<br />
-I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Compartición de red entre dispositivo físico y un dispositivo de toque a través de iptables ====<br />
<br />
La conexión en puente funciona bien entre una interfaz cableada (por ejemplo, eth0), y es fácil de configurar. Sin embargo, si el host se conecta a la red a través de un dispositivo inalámbrico, el puente no es posible.<br />
<br />
Consulte [[Network bridge#Wireless interface on a bridge]] como referencia.<br />
<br />
Una forma de superar esto es configurar un dispositivo de derivación con una IP estática, haciendo que linux maneje automáticamente el enrutamiento para ella y, a continuación, reenvíe el tráfico entre la interfaz de derivación y el dispositivo conectado a la red a través de las reglas de iptables.<br />
<br />
Consulte [[Internet sharing]] como referencia.<br />
<br />
Allí puede encontrar lo que se necesita para compartir la red entre dispositivos, incluidos los de tap y tun. Lo siguiente sólo indica algunas de las configuraciones de host requeridas. Como se indica en la referencia anterior, el cliente debe configurarse para una IP estática, utilizando la IP asignada a la interfaz de derivación como puerta de enlace. La advertencia es que los servidores DNS del cliente pueden necesitar ser editados manualmente si cambian al cambiar de un dispositivo host conectado a la red a otro.<br />
<br />
Para permitir el reenvío de IP en cada inicio, es necesario agregar las siguientes líneas al archivo de configuración de sysctl dentro de /etc/sysctl.d:<br />
<br />
net.ipv4.ip_forward = 1<br />
net.ipv6.conf.default.forwarding = 1<br />
net.ipv6.conf.all.forwarding = 1<br />
<br />
Las reglas de iptables pueden verse así:<br />
<br />
# Forwarding from/to outside<br />
iptables -A FORWARD -i ${INT} -o ${EXT_0} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_1} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_2} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_0} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_1} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_2} -o ${INT} -j ACCEPT<br />
# NAT/Masquerade (network address translation)<br />
iptables -t nat -A POSTROUTING -o ${EXT_0} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_1} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_2} -j MASQUERADE<br />
<br />
El anterior supone que hay 3 dispositivos conectados a la red compartiendo tráfico con un dispositivo interno, donde por ejemplo:<br />
<br />
INT=tap0<br />
EXT_0=eth0<br />
EXT_1=wlan0<br />
EXT_2=tun0<br />
<br />
El anterior muestra un reenvío que permitiría compartir conexiones cableadas e inalámbricas con el dispositivo de derivación (tap).<br />
<br />
Las reglas de reenvío que se muestran son apátridas y para el reenvío puro. Se podría pensar en restringir el tráfico específico, poniendo un cortafuegos en el lugar para proteger al huésped y otros. Sin embargo, esto reduciría el rendimiento de la red, mientras que un simple puente no incluye nada de eso.<br />
<br />
Bonus: Si la conexión es cableada o inalámbrica, si se conecta a través de VPN a un sitio remoto con un dispositivo tun, suponiendo que el dispositivo tun abierto para esa conexión es tun0, y las reglas iptables anteriores se aplican, entonces la conexión remota se obtiene también Compartido con el huésped. Esto evita la necesidad de que el invitado también abra una conexión VPN. Una vez más, como la red de invitados debe ser estática, entonces si la conexión del host de forma remota de esta manera, uno probablemente tendrá que editar los servidores DNS en el invitado.<br />
<br />
=== Trabajo en red con VDE2 ===<br />
<br />
==== ¿Qué es VDE? ====<br />
<br />
VDE significa Virtual Distributed Ethernet. Comenzó como una mejora del interruptor [[User-mode Linux|uml]] _. Es una caja de herramientas para administrar redes virtuales.<br />
<br />
La idea es crear interruptores virtuales, que son básicamente sockets, y "conectar" tanto máquinas físicas como máquinas virtuales en ellas. La configuración que mostramos aquí es bastante simple; Sin embargo, VDE es mucho más potente que esto, puede conectar conmutadores virtuales juntos, ejecutarlos en diferentes hosts y supervisar el tráfico en los switches. Usted está invitado a leer [https://web.archive.org/web/20190821040940/http://wiki.virtualsquare.org/wiki/index.php/Main_Page la documentación del proyecto].<br />
<br />
La ventaja de este método es que no tienes que agregar privilegios de sudo a tus usuarios. No se debe permitir que los usuarios regulares ejecuten modprobe.<br />
<br />
==== Basics ====<br />
<br />
El soporte de VDE puede ser [[pacman|instalado]] a través del paquete {{Pkg|vde2}} en los [[repositorios oficiales]].<br />
<br />
En nuestra configuración, usamos tun/tap para crear una interfaz virtual en el host. Cargue el módulo {{ic|tun}} (véase [[kernel modules (Español)]] para obtener más detalles):<br />
<br />
# modprobe tun<br />
<br />
Ahora crea el conmutador virtual:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
<br />
Esta línea crea el switch, crea {{ic|tap0}}, lo "enchufa" y permite a los usuarios del grupo {{ic|users}} usarlo.<br />
<br />
La interfaz está conectada pero no está configurada todavía. Para configurarlo, ejecute este comando:<br />
<br />
# ip addr add 192.168.100.254/24 dev tap0<br />
<br />
Ahora, sólo tiene que ejecutar KVM con estas opciones {{ic|-net}} como usuario normal:<br />
<br />
$ qemu-system-i386 -net nic -net vde -hda ''[...]''<br />
<br />
Configure la red para su invitado como lo haría en una red física.<br />
<br />
{{Tip (Español)|Es posible que desee configurar NAT en dispositivo de toque para acceder a Internet desde la máquina virtual. Consulte [[Internet sharing#Enable NAT]] para obtener más información.}}<br />
<br />
==== Startup scripts ====<br />
<br />
Ejemplo de script principal que inicia VDE:<br />
<br />
{{hc|/etc/systemd/scripts/qemu-network-env|<nowiki><br />
#!/bin/sh<br />
# Preparación del entorno de red QEMU/VDE<br />
<br />
# La configuración IP del dispositivo de derivación que se utilizará para<br />
# La red de la máquina virtual:<br />
<br />
TAP_DEV=tap0<br />
TAP_IP=192.168.100.254<br />
TAP_MASK=24<br />
TAP_NETWORK=192.168.100.0<br />
<br />
# Host interface<br />
NIC=eth0<br />
<br />
case "$1" in<br />
start)<br />
echo -n "Starting VDE network for QEMU: "<br />
<br />
# If you want tun kernel module to be loaded by script uncomment here<br />
#modprobe tun 2>/dev/null<br />
## Wait for the module to be loaded<br />
#while ! lsmod | grep -q "^tun"; do echo "Waiting for tun device"; sleep 1; done<br />
<br />
# Start tap switch<br />
vde_switch -tap "$TAP_DEV" -daemon -mod 660 -group users<br />
<br />
# Bring tap interface up<br />
ip address add "$TAP_IP"/"$TAP_MASK" dev "$TAP_DEV"<br />
ip link set "$TAP_DEV" up<br />
<br />
# Start IP Forwarding<br />
echo "1" > /proc/sys/net/ipv4/ip_forward<br />
iptables -t nat -A POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
;;<br />
stop)<br />
echo -n "Stopping VDE network for QEMU: "<br />
# Delete the NAT rules<br />
iptables -t nat -D POSTROUTING "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
<br />
# Bring tap interface down<br />
ip link set "$TAP_DEV" down<br />
<br />
# Kill VDE switch<br />
pgrep -f vde_switch | xargs kill -TERM<br />
;;<br />
restart|reload)<br />
$0 stop<br />
sleep 1<br />
$0 start<br />
;;<br />
*)<br />
echo "Usage: $0 {start|stop|restart|reload}"<br />
exit 1<br />
esac<br />
exit 0<br />
</nowiki>}}<br />
<br />
Ejemplo de servicio systemd utilizando el script anterior:<br />
<br />
{{hc|/etc/systemd/system/qemu-network-env.service|<nowiki><br />
[Unit]<br />
Description=Manage VDE Switch<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/etc/systemd/scripts/qemu-network-env start<br />
ExecStop=/etc/systemd/scripts/qemu-network-env stop<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
Cambiar permisos de {{ic|qemu-network-env}} para ser ejecutable<br />
<br />
# chmod u+x /etc/systemd/scripts/qemu-network-env<br />
<br />
Puede iniciar {{ic|qemu-network-env.service}} como de costumbre.<br />
<br />
==== Método alternativo ====<br />
<br />
Si el método anterior no funciona o no quiere meterse con las configuraciones del kernel, TUN, dnsmasq e iptables, puede hacer lo siguiente para obtener el mismo resultado.<br />
<br />
# vde_switch -daemon -mod 660 -group users<br />
# slirpvde --dhcp --daemon<br />
<br />
A continuación, para iniciar la VM con una conexión a la red del host:<br />
<br />
$ qemu-system-i386 -net nic,macaddr=52:54:00:00:EE:03 -net vde ''disk_image''<br />
<br />
=== Puente VDE2 ===<br />
<br />
Basado en [https://selamatpagicikgu.wordpress.com/2011/06/08/quickhowto-qemu-networking-using-vde-tuntap-and-bridge/ quickhowto: qemu networking using vde, tun/tap, and bridge] gráfico. Cualquier máquina virtual conectada a vde está expuesta externamente. Por ejemplo, cada máquina virtual puede recibir la configuración DHCP directamente desde su enrutador ADSL.<br />
<br />
==== Conceptos básicos ====<br />
<br />
Recuerde que necesita el módulo {{ic|tun}} y el paquete {{Pkg|bridge-utils}}.<br />
<br />
Cree el dispositivo vde2/tap:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
# ip link set tap0 up<br />
<br />
Cree el puente:<br />
<br />
# brctl addbr br0<br />
<br />
Agregue dispositivos:<br />
<br />
# brctl addif br0 eth0<br />
# brctl addif br0 tap0<br />
<br />
Y configure la interfaz del puente:<br />
<br />
# dhcpcd br0<br />
<br />
==== Startup scripts ====<br />
<br />
Todos los dispositivos deben estar configurados. Y sólo el puente necesita una dirección IP. Para dispositivos físicos en el puente (por ejemplo, {{ic|eth0}}), esto puede hacerse con [[netctl]] utilizando un perfil Ethernet personalizado con:<br />
<br />
{{hc|/etc/netctl/ethernet-noip|<nowiki><br />
Description='A more versatile static Ethernet connection'<br />
Interface=eth0<br />
Connection=ethernet<br />
IP=no<br />
</nowiki>}}<br />
<br />
El siguiente servicio systemd personalizado puede utilizarse para crear y activar una interfaz de toma VDE2 para su uso en el grupo de usuarios {{ic|users}}.<br />
<br />
{{hc|/etc/systemd/system/vde2@.service|<nowiki><br />
[Unit]<br />
Description=Network Connectivity for %i<br />
Wants=network.target<br />
Before=network.target<br />
<br />
[Service]<br />
Type=oneshot<br />
RemainAfterExit=yes<br />
ExecStart=/usr/bin/vde_switch -tap %i -daemon -mod 660 -group users<br />
ExecStart=/usr/bin/ip link set dev %i up<br />
ExecStop=/usr/bin/ip addr flush dev %i<br />
ExecStop=/usr/bin/ip link set dev %i down<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
Y, por último, puede crear el puente interfaz con netctl.<br />
<br />
== Gráficos ==<br />
<br />
QEMU puede utilizar las siguientes salidas gráficas diferentes: {{ic|std}}, {{ic|qxl}}, {{ic|vmware}}, {{ic|virtio}}, {{ic|cirrus}} y {{ic|none}}.<br />
<br />
=== std ===<br />
<br />
Con {{ic|-vga std}} puede obtener una resolución de hasta 2560 x 1600 píxeles sin necesidad de controladores invitados. Este es el valor predeterminado desde QEMU 2.2.<br />
<br />
=== qxl ===<br />
<br />
QXL Es un controlador de gráficos paravirtual con soporte 2D. Para usarlo, pase la opción {{ic|-vga qxl}} e instale los controladores en el invitado. Es posible que desee utilizar SPICE para mejorar el rendimiento gráfico al utilizar QXL.<br />
<br />
En los invitados de Linux, los módulos del kernel {{ic|qxl}} y {{ic|bochs_drm}} deben ser inicializados para poder tener un rendimiento decente.<br />
<br />
==== SPICE ====<br />
<br />
El proyecto [https://www.spice-space.org/ SPICE] tiene como objetivo proporcionar una solución completa de código abierto para el acceso remoto a máquinas virtuales de una manera transparente.<br />
<br />
SPICE sólo se puede utilizar cuando se utiliza QXL como la salida gráfica.<br />
<br />
El siguiente es un ejemplo de arranque con SPICE como protocolo de escritorio remoto:<br />
<br />
$ qemu-system-i386 -vga qxl -spice port=5930,disable-ticketing -chardev spicevm <br />
<br />
Conéctese al invitado utilizando un cliente SPICE. En este momento se recomienda {{Pkg|spice-gtk}}, sin embargo otros [https://www.spice-space.org/download.html clientes], incluyendo otras plataformas, están disponibles:<br />
<br />
$ spicy -h 127.0.0.1 -p 5930<br />
<br />
El uso de [[wikipedia:Unix_socket|Unix sockets]] en lugar de los puertos TCP no implica el uso de pila de red en el sistema host, por lo que es [https://unix.stackexchange.com/questions/91774/performance-of-unix- Sockets-vs-tcp-ports según se informa] mejor para el rendimiento. Ejemplo:<br />
$ qemu-system-x86_64 -vga qxl -device virtio-serial-pci -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent -spice unix,addr=/tmp/vm_spice.socket,disable-ticketing<br />
$ spicy --uri="spice+unix:///tmp/vm_spice.socket"<br />
<br />
Para una mejor compatibilidad con varios monitores, compartir el portapapeles, etc., los paquetes siguientes deben estar instalados en el invitado:<br />
* {{Pkg|spice-vdagent}}: Spice agent xorg cliente que permite copiar y pegar entre el cliente y X-session y más<br />
* {{Pkg|xf86-video-qxl}} {{AUR|xf86-video-qxl-git}}: Xorg X11 qxl controlador de vídeo<br />
* Para otros sistemas operativos, mire la sección Guest de la página [https://www.spice-space.org/download.html SPICE-Space download].<br />
<br />
=== vmware ===<br />
<br />
Aunque tiene pocos errores, tiene mejor rendimiento que std y cirrus. Instale los controladores de VMware {{Pkg|xf86-video-vmware}} y {{Pkg|xf86-input-vmmouse}} para los invitados de Arch Linux.<br />
<br />
=== virtio ===<br />
<br />
{{ic|virtio-vga}} / {{ic|virtio-gpu}} Es un controlador de gráficos 3D paravirtual basado en [https://virgil3d.github.io/ virgl]. Actualmente un trabajo en curso, que sólo admite a invitados Linux (>= 4.4) con {{Pkg|mesa}} (>= 11.2) compilados con la opción {{ic|1=--with-gallium-drivers=virgl}}.<br />
<br />
Para activar la aceleración 3D en el sistema invitado, seleccione vga con {{ic|-vga virtio}} y habilitar el contexto opengl en el dispositivo de visualización con {{ic|1=-display sdl,gl=on}} ó {{ic|1=-display gtk,gl=on}} Para la salida de pantalla sdl y gtk respectivamente. La configuración correcta se puede confirmar mirando el registro del kernel en el invitado:<br />
<br />
{{hc|# dmesg {{!}} grep drm |<br />
[drm] pci: virtio-vga detected<br />
[drm] virgl 3d acceleration enabled<br />
}}<br />
<br />
A partir de septiembre de 2016, el soporte para el protocolo de especias está en desarrollo y se puede probar la instalación de la versión de desarrollo de {{Pkg|spice}} (>= 0.13.2) y la recompilación de qemu.<br />
<br />
Para más información visite [https://web.archive.org/web/20171216170334/https://www.kraxel.org/blog/tag/virgl/ blog de kraxel].<br />
<br />
=== cirrus ===<br />
<br />
El adaptador gráfico cirrus fue el predeterminado [https://wiki.qemu.org/ChangeLog/2.2#VGA before 2.2]. [Https://www.kraxel.org/blog/2014/10/qemu-using-cirrus-considered-harmful/ no debería] utilizarse en sistemas modernos.<br />
<br />
=== none ===<br />
<br />
Esto es como un PC que no tiene tarjeta VGA en absoluto. Ni siquiera podrías acceder a ella con la opción {{ic|-vnc}}. Además, esto es diferente de la opción {{ic|-nographic}} que permite a QEMU emular una tarjeta VGA, pero deshabilita la visualización SDL.<br />
<br />
=== vnc ===<br />
<br />
Dado que usó la opción {{ic|-nographic}}, puede agregar la opción {{ic|-vnc display}} para que QEMU escuche en {{ic|display}} y redirigir la pantalla VGA a la sesión VNC . Hay un ejemplo de esto en las configuraciones de ejemplo de la sección [[#Inicio de las máquinas virtuales QEMU en el arranque]].<br />
<br />
$ qemu-system-i386 -vga std -nographic -vnc :0<br />
$ gvncviewer :0<br />
<br />
Al usar VNC, puede experimentar problemas de teclado descritos (en detalles gory) [https://www.berrange.com/posts/2010/07/04/more-than-you-or-i-ever-wanted-to-know-about-virtual-keyboard-handling/ aquí]. La solución es "no" usar la opción {{ic|-k}} en QEMU y usar {{ic|gvncviewer}} de {{Pkg|gtk-vnc}}. Ver también [https://www.mail-archive.com/libvir-list@redhat.com/msg13340.html este] mensaje publicado en la lista de correo de libvirt.<br />
<br />
== Audio ==<br />
<br />
=== Host ===<br />
<br />
El controlador de audio utilizado por QEMU se establece con la variable de entorno {{ic|QEMU_AUDIO_DRV}}:<br />
<br />
$ export QEMU_AUDIO_DRV=pa<br />
<br />
Ejecute el siguiente comando para obtener las opciones de configuración de QEMU relacionadas con PulseAudio:<br />
<br />
$ qemu-system-x86_64 -audio-help | awk '/Name: pa/' RS=<br />
<br />
Las opciones listadas se pueden exportar como variables de entorno, por ejemplo:<br />
<br />
{{bc|1=<br />
$ export QEMU_PA_SINK=alsa_output.pci-0000_04_01.0.analog-stereo.monitor<br />
$ export QEMU_PA_SOURCE=input<br />
}}<br />
<br />
=== Invitado ===<br />
<br />
Para obtener la lista de los controladores de audio de emulación compatibles:<br />
<br />
$ qemu-system-x86_64 -soundhw help<br />
<br />
Para usar (ej. {{ic|hda}}) para el invitado utilice el comando {{ic|-soundhw hda}} con QEMU.<br />
<br />
{{Note (Español)| Los controladores emulados con tarjeta gráfica de vídeo para la máquina invitada también pueden causar un problema con la calidad del sonido. Pruebe uno por uno para que funcione. Puede listar las opciones posibles con {{ic|qemu-system-x86_64 -h | grep vga}}.}}<br />
<br />
=== VirtIO sound ===<br />
<br />
VirtIO sound está disponible desde la versión QEMU 8.2.0. El uso es:<br />
<br />
-device virtio-sound-pci,audiodev=my_audiodev -audiodev alsa,id=my_audiodev<br />
<br />
Más información puede ser encontrada en [https://qemu-project.gitlab.io/qemu/system/devices/virtio-snd.html documentación QEMU].<br />
<br />
== Instalación de controladores virtio ==<br />
<br />
QEMU ofrece a los clientes la posibilidad de utilizar dispositivos bloqueados y de red paravirtualizados utilizando los controladores [https://wiki.libvirt.org/page/Virtio virtio], que proporcionan un mejor rendimiento y menores gastos generales.<br />
<br />
Un dispositivo virtio bloque requiere la opción {{ic|-drive}} en lugar del simple {{ic|-hd *}} más {{ic|1=if=virtio}}:<br />
<br />
$ qemu-system-i386 -boot order=c -drive file=''disk_image'',if=virtio<br />
<br />
{{Note (Español)|{{Ic|1=-boot order=c}} es absolutamente necesario cuando se desea arrancar desde él. No hay detección automática como con {{Ic|-hd*}}.}}<br />
<br />
* Casi de la misma manera para la red:<br />
<br />
$ qemu-system-i386 -net nic,model=virtio<br />
<br />
{{Note (Español)| Esto sólo funcionará si la máquina invitada tiene controladores para dispositivos virtio. Linux lo hace, y los controladores necesarios están incluidos en Arch Linux, pero no hay garantía de que los dispositivos virtio funcionen con otros sistemas operativos.}}<br />
<br />
=== Preparando a Arch Linux como invitado ===<br />
<br />
Para utilizar los dispositivos virtio después de instalar un invitado de Arch Linux, se deben cargar en el invitado los siguientes módulos: {{Ic|virtio}}, {{Ic|virtio_pci}}, {{Ic|virtio_blk}}, {{Ic|Virtio_net}}, y {{Ic|virtio_ring}}. Para los huéspedes de 32 bits, no es necesario el módulo "virtio" específico.<br />
<br />
Si desea arrancar desde un disco virtio, el disco ramd inicial debe contener los módulos necesarios. De forma predeterminada, esto es manejado por el gancho {{ic|autodetect}} de [[mkinitcpio]]. De lo contrario, utilice la matriz {{ic|MODULES}} en {{ic|/etc/mkinitcpio.conf}} para incluir los módulos necesarios y reconstruir el disco ramd inicial.<br />
<br />
{{hc|/etc/mkinitcpio.conf|2=<br />
MODULES="virtio virtio_blk virtio_pci virtio_net"}}<br />
<br />
Los discos Virtio se reconocen con el prefijo {{ic|'''v'''}} (ej. {{ic|'''v''' da}}, {{ic|'''v''' db}}, etc.); Por lo tanto, los cambios deben realizarse al menos en {{ic|/etc/fstab}} y {{ic|/boot/grub/grub.cfg}} al arrancar desde un disco virtio.<br />
<br />
{{Note (Español)|Cuando se hace referencia a discos por [[UUID]] en {{ic|/etc/fstab}} y bootloader, no hay nada que hacer.}}<br />
<br />
Se puede encontrar más información sobre la paravirtualización con KVM [https://www.linux-kvm.org/page/Boot_from_virtio_block_device aquí].<br />
<br />
También puede instalar {{Pkg|qemu-guest-agent}} para implementar la compatibilidad con los comandos QMP que mejorarán las capacidades de administración del hipervisor. Después de instalar el paquete, puedes habilitar e iniciar el {{ic|qemu-ga.service}}.<br />
<br />
=== Preparar un invitado de Windows ===<br />
<br />
{{Note (Español)|1=La única forma (fiable) de actualizar un cliente de Windows 8.1 a Windows 10 parece que es elegir temporalmente cpu core2duo, nx para la instalación [https://ubuntuforums.org/showthread.php?t=2289210]. Después de la instalación, puede volver a otros ajustes de la CPU (8/8/2015).}}<br />
<br />
==== Bloquear controladores de dispositivo ====<br />
<br />
===== Nueva instalación de Windows =====<br />
<br />
Windows no viene con los controladores virtio. Por lo tanto, tendrá que cargarlos durante la instalación. Hay básicamente dos maneras de hacer esto: vía disco blando o vía archivos de ISO. Ambas imágenes se pueden descargar desde el repositorio [https://fedoraproject.org/wiki/Windows_Virtio_Drivers Fedora].<br />
<br />
La opción del disquete es difícil porque necesitará presionar F6 (Shift-F6 en Windows más reciente) al inicio de la alimentación del QEMU. Esto es difícil ya que necesitas tiempo para conectar tu ventana de consola VNC. Puede intentar agregar un retardo a la secuencia de arranque. Consulte {{ic|man qemu-system}} para obtener más detalles sobre la aplicación de un retardo en el arranque.<br />
<br />
La opción ISO para cargar los controladores es la forma preferida, pero está disponible sólo en Windows Vista y Windows Server 2008 y versiones posteriores. El procedimiento consiste en cargar la imagen con controladores virtio en un dispositivo de cdrom adicional junto con el dispositivo de disco principal y el instalador de Windows:<br />
<br />
$ qemu-system-i386 ... \<br />
-drive file=''/path/to/primary/disk.img'',index=0,media=disk,if=virtio \<br />
-drive file=''/path/to/installer.iso'',index=2,media=cdrom \<br />
-drive file=''/path/to/virtio.iso'',index=3,media=cdrom \<br />
...<br />
<br />
Durante la instalación, el instalador de Windows le pedirá su clave de producto y realizará algunas comprobaciones adicionales. Cuando llegue a la "¿Dónde desea instalar Windows?" Pantalla, dará una advertencia de que no se encuentran discos. Siga las instrucciones de ejemplo siguientes (basadas en Windows Server 2012 R2 con Actualización).<br />
<br />
* Seleccione la opción {{ic|Load Drivers}}.<br />
* Desactive la casilla de "Ocultar los controladores que no son compatibles con el hardware de este equipo".<br />
* Haga clic en el botón Examinar y abra el CDROM para la virtio iso, normalmente llamada "virtio-win-XX".<br />
* Ahora vaya a {{ic|E:\viostor\[your-os]\amd64}}, seleccione y pulse OK.<br />
* Click Next<br />
<br />
Ahora debería ver sus discos virtio listados aquí, listos para ser seleccionados, formateados e instalados.<br />
<br />
===== Cambiar la máquina virtual existente de Windows para utilizar virtio =====<br />
<br />
Modificar un invitado de Windows existente para arrancar desde disco virtio es un poco difícil.<br />
<br />
Puede descargar el controlador de disco virtio desde el [https://fedoraproject.org/wiki/Windows_Virtio_Drivers repositorio de Fedora].<br />
<br />
Ahora necesita crear una nueva imagen de disco, que llene la fuerza de Windows para buscar el controlador. Por ejemplo:<br />
<br />
$ qemu-img create -f qcow2 ''fake.qcow2'' 1G<br />
<br />
Ejecute el invitado original de Windows (con el disco de inicio todavía en modo IDE) con el disco falso (en modo virtio) y un CD-ROM con el controlador.<br />
<br />
$ qemu-system-i386 -m 512 -vga std -drive file=''windows_disk_image'',if=ide -drive file=''fake.qcow2'',if=virtio -cdrom virtio-win-0.1-81.iso<br />
<br />
Windows detectará el disco falso y tratará de encontrar un controlador para ello. Si falla, vaya al '' Administrador de dispositivos '', busque la unidad SCSI con un icono de signo de exclamación (debe estar abierto), haga clic en '' Actualizar controlador '' y seleccione el CD-ROM virtual. No olvide seleccionar la casilla de verificación que dice que debe buscar directorios recursivamente.<br />
<br />
Cuando la instalación se realiza correctamente, puede apagar la máquina virtual y volver a iniciarla, ahora con el disco de arranque conectado en modo virtio:<br />
<br />
$ qemu-system-i386 -m 512 -vga std -drive file=''windows_disk_image'',if=virtio<br />
<br />
{{Note (Español)|Si encuentra la pantalla azul de Death, asegúrese de no olvidar el parámetro {{ic|-m}} y de que no arranca con virtio en lugar de ide para la unidad del sistema antes de instalar los controladores.}}<br />
<br />
==== Controladores de red ====<br />
<br />
La instalación de los controladores de red virtio es un poco más fácil, simplemente agregue el argumento {{ic|-net}} como se explicó anteriormente.<br />
<br />
$ qemu-system-i386 -m 512 -vga std -drive file=''windows_disk_image'',if=virtio -net nic,model=virtio -cdrom virtio-win-0.1-74.iso<br />
<br />
Windows detectará el adaptador de red y tratará de encontrar un controlador para ello. Si falla, vaya al ''Administrador de dispositivos'', localice el adaptador de red con un icono de signo de exclamación (debe estar abierto), haga clic en ''Actualizar controlador'' y seleccione el CD-ROM virtual. No olvide seleccionar la casilla de verificación que dice que debe buscar directorios recursivamente.<br />
<br />
=== Preparación de FreeBSD como invitado ===<br />
<br />
Instale el puerto {{ic|emulators/virtio-kmod}} si está utilizando FreeBSD 8.3 o posterior hasta 10.0-CURRENT donde están incluidos en el kernel. Después de la instalación, añada lo siguiente a su archivo {{ic|/boot/loader.conf}}:<br />
<br />
{{bc|<nowiki><br />
virtio_loader="YES"<br />
virtio_pci_load="YES"<br />
virtio_blk_load="YES"<br />
if_vtnet_load="YES"<br />
virtio_balloon_load="YES"<br />
</nowiki>}}<br />
<br />
A continuación, modifique su {{ic|/etc/fstab}} haciendo lo siguiente:<br />
<br />
{{bc|<nowiki><br />
sed -i bak "s/ada/vtbd/g" /etc/fstab<br />
</nowiki>}}<br />
<br />
Y verificar que {{ic|/etc/fstab}} es consistente. Si algo sale mal, sólo arranque en un CD de rescate y copie {{ic|/etc/fstab.bak}} de vuelta a {{ic|/etc/fstab}}.<br />
<br />
== Consejos y trucos ==<br />
<br />
=== Inicio de las máquinas virtuales QEMU en el arranque ===<br />
<br />
==== Con libvirt ====<br />
<br />
Si se configura una máquina virtual con [[libvirt]], se puede configurar a través de la interfaz gráfica de usuario de virt-manager para iniciar en el arranque de host, accediendo a las Opciones de arranque de la máquina virtual y seleccionando "Inicio de la máquina virtual en el arranque del host".<br />
<br />
==== Script personalizado ====<br />
<br />
Para ejecutar QEMU VMs al arrancar, puede usar las siguientes unidades systemd y config.<br />
<br />
{{hc|/etc/systemd/system/qemu@.service|<nowiki><br />
[Unit]<br />
Description=QEMU virtual machine<br />
<br />
[Service]<br />
Environment="type=system-x86_64" "haltcmd=kill -INT $MAINPID"<br />
EnvironmentFile=/etc/conf.d/qemu.d/%i<br />
ExecStart=/usr/bin/env qemu-${type} -name %i -nographic $args<br />
ExecStop=/bin/sh -c ${haltcmd}<br />
TimeoutStopSec=30<br />
KillMode=none<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
{{Note (Español)|De acuerdo con {{ic|systemd.service (5)}} y {{ic|systemd.kill (5)}} man, es necesario utilizar {{ic|1=KillMode=none}} opción. De lo contrario, el proceso qemu principal se eliminará inmediatamente después de que se cierre el comando {{ic|ExecStop}} (simplemente hace eco de una cadena) y su sistema de búsqueda no podrá apagarse correctamente.}}<br />
<br />
A continuación, cree archivos de configuración por-VM, denominados {{ic|/etc/conf.d/qemu.d/''vm_name''}}, con las siguientes variables establecidas:<br />
<br />
; type<br />
: QEMU binary to call. If specified, will be prepended with {{ic|/usr/bin/qemu-}} and that binary will be used to start the VM. I.e. you can boot e.g. {{ic|qemu-system-arm}} images with {{ic|1=type="system-arm"}}.<br />
; args<br />
: QEMU command line to start with. Will always be prepended with {{ic|-name ${vm} -nographic}}.<br />
; haltcmd<br />
: Command to shut down a VM safely. I am using {{ic|-monitor telnet:..}} and power off my VMs via ACPI by sending {{ic|system_powerdown}} to monitor. You can use SSH or some other ways.<br />
<br />
Ejemplo de configuración:<br />
<br />
{{hc|/etc/conf.d/qemu.d/one|<nowiki><br />
type="system-x86_64"<br />
<br />
args="-enable-kvm -m 512 -hda /dev/mapper/vg0-vm1 -net nic,macaddr=DE:AD:BE:EF:E0:00 \<br />
-net tap,ifname=tap0 -serial telnet:localhost:7000,server,nowait,nodelay \<br />
-monitor telnet:localhost:7100,server,nowait,nodelay -vnc :0"<br />
<br />
haltcmd="echo 'system_powerdown' | nc localhost 7100" # or netcat/ncat<br />
<br />
# You can use other ways to shut down your VM correctly<br />
#haltcmd="ssh powermanager@vm1 sudo poweroff"<br />
</nowiki>}}<br />
<br />
{{hc|/etc/conf.d/qemu.d/two|<nowiki><br />
args="-enable-kvm -m 512 -hda /srv/kvm/vm2.img -net nic,macaddr=DE:AD:BE:EF:E0:01 \<br />
-net tap,ifname=tap1 -serial telnet:localhost:7001,server,nowait,nodelay \<br />
-monitor telnet:localhost:7101,server,nowait,nodelay -vnc :1"<br />
<br />
haltcmd="echo 'system_powerdown' | nc localhost 7101"<br />
</nowiki>}}<br />
<br />
Para establecer qué máquinas virtuales se iniciarán al arrancar, habilite la unidad de [[systemd]] {{ic|qemu@''vm_name''.service}}.<br />
<br />
=== Integración del ratón ===<br />
<br />
Para evitar que el ratón sea agarrado al hacer clic en la ventana del sistema operativo invitado, agregue la opción {{ic|-usbdevice tablet}}. Esto significa que QEMU puede reportar la posición del ratón sin tener que agarrar el ratón. Esto también anula la emulación de ratón PS/2 cuando se activa. Por ejemplo:<br />
<br />
$ qemu-system-i386 -hda ''disk_image'' -m 512 -vga std -usbdevice tablet<br />
<br />
If that does not work, try the tip at [[#El cursor del ratón está nervioso o errático]].<br />
<br />
=== Dispositivo USB del host de paso ===<br />
<br />
Para acceder al dispositivo físico USB conectado al host desde la VM, puede utilizar la opción: {{ic|-usbdevice host:''vendor_id'':''product_id''}}.<br />
<br />
Puedes encontrar {{ic|vendor_id}} y {{ic|product_id}} de tu dispositivo con el comando {{ic|lsusb}}.<br />
<br />
Puesto que el chipset I440FX por defecto emulado por qemu cuentan con un solo controlador UHCI (USB 1), la opción {{ic|-usbdevice}} intentará conectar su dispositivo físico a él. En algunos casos esto puede causar problemas con los dispositivos más nuevos. Una posible solución es emular el chipset [https://wiki.qemu.org/Features/Q35 ICH9], que ofrece un controlador EHCI que soporta hasta 12 dispositivos, usando la opción {{ic|1=-machine type=q35}}.<br />
<br />
Una solución menos invasiva es emular un controlador EHCI (USB 2) o XHCI (USB 3) con la opción {{ic | 1 = -device usb-ehci, id = ehci}} o {{ic|1=-device nec -usb-xhci, id=xhci}} respectivamente y luego adjuntar su dispositivo físico con la opción {{ic|1=-device usb-host,..}} como sigue:<br />
<br />
-device usb-host,bus='''controller_id'''.0,vendorid=0x'''vendor_id''',productid=0x'''product_id'''<br />
<br />
También puede agregar la configuración {{ic|1=..., port =''<n>''}} a la opción anterior para especificar en qué puerto físico del controlador virtual que desea conectar su dispositivo, útil en El caso que desea agregar varios dispositivos usb a la VM.<br />
<br />
{{Note (Español)|Si encuentra errores de permisos al ejecutar QEMU, consulte [[udev#About udev rules]] para obtener información sobre cómo establecer permisos del dispositivo.}}<br />
<br />
=== Habilitar KSM ===<br />
<br />
Kernel Samepage Merging (KSM) es una característica del kernel de Linux que permite que una aplicación se registre con el kernel para que sus páginas se combinen con otros procesos que también se registren para que sus páginas se fusionen. El mecanismo KSM permite a las máquinas virtuales invitadas compartir páginas entre sí. En un entorno donde muchos de los sistemas operativos invitados son similares, esto puede resultar en ahorros significativos de memoria.<br />
<br />
Para activar KSM, simplemente ejecute:<br />
<br />
# echo 1 > /sys/kernel/mm/ksm/run<br />
<br />
Para hacerlo permanente, puede utilizar [[Systemd#systemd-tmpfiles - temporary files|archivos temporales de systemd]]:<br />
<br />
{{hc|/etc/tmpfiles.d/ksm.conf|<br />
w /sys/kernel/mm/ksm/run - - - - 1<br />
}}<br />
<br />
Si KSM está en ejecución y hay páginas que se van a fusionar (es decir, al menos dos máquinas virtuales similares se están ejecutando), entonces {{ic|/sys/kernel/mm/ksm/pages_shared}} debería ser distinto de cero. Consulte https://docs.kernel.org/vm/ksm.html{{Dead link (Español)|2022|09|22|status=404}} para obtener más información.<br />
<br />
{{Tip (Español)|Una manera fácil de ver lo bien que KSM está realizando es simplemente imprimir el contenido de todos los archivos de ese directorio: {{bc|$ grep./Sys/kernel/mm/ksm/*}}}}<br />
<br />
=== Multi-monitor support ===<br />
<br />
El controlador QXL de Linux soporta cuatro cabezas (pantallas virtuales) de forma predeterminada. Esto se puede cambiar a través del parámetro kernel {{ic | 1 = qxl.heads = N}}.<br />
<br />
El tamaño de memoria VGA predeterminado para los dispositivos QXL es de 16M (el tamaño de la VRAM es de 64M). Esto no es suficiente si desea habilitar dos monitores 1920x1200 ya que requiere 2 × 1920 × 4 (profundidad de color) × 1200 = 17.6 MiB memoria VGA. Esto se puede cambiar reemplazando {{ic|-vga qxl}} por {{ic|1=-vga none -device qxl-vga, vgamem_mb=32}}. Si alguna vez incrementas vgamem_mb más allá de 64M, también debes aumentar la opción {{ic|vram_size_mb}}.<br />
<br />
=== Copiar y pegar ===<br />
<br />
Para poder copiar y pegar entre el host y el invitado, debe habilitar el canal de comunicación del agente de especias. Requiere agregar un dispositivo virtio-serial al huésped, y abrir un puerto para el vdagent de la especia. También es necesario instalar el spice vdagent en invitado ({{Pkg|spice-vdagent}} para invitados de Arch, [https://www.spice-space.org/download.html Herramientas para invitados de Windows] para invitados de Windows). Asegúrese de que el agente se está ejecutando (y para el futuro, se iniciará automáticamente).<br />
<br />
Inicie QEMU con las siguientes opciones:<br />
<br />
$ qemu-system-i386 -vga qxl -spice port=5930,disable-ticketing -device virtio-serial-pci -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
La opción {{ic|-device virtio-serial-pci}} añade el dispositivo virtio-serial, {{ic|1=-device virtserialport, chardev=spicechannel0, nombre=com.redhat.spice.0}} abre un puerto Para spice vdagent en ese dispositivo y {{ic|1=-chardev spicevmc, id=spicechannel0, nombre=vdagent}} añade un spicevmc chardev para ese puerto.<br />
<br />
Es importante que la opción {{ic|1=chardev=}} del dispositivo {{ic|virtserialport}} coincida con la opción {{ic|1=id=}} dada a la opción {{ic | chardev}} ({{Ic|spicechannel0}} en este ejemplo). También es importante que el nombre del puerto sea {{ic|com.redhat.spice.0}}, ya que es el espacio de nombres donde vdagent está buscando en el invitado. Y finalmente, especifique {{ic|1=name=vdagent}} para que spice sepa para qué sirve este canal.<br />
<br />
=== Notas específicas de Windows ===<br />
<br />
QEMU puede ejecutar cualquier versión de Windows desde Windows 95 a través de Windows 10.<br />
<br />
Es posible ejecutar [[Windows PE]] en QEMU.<br />
<br />
==== Inicio rápido ====<br />
<br />
{{Note (Español)|Se requiere una cuenta de administrador para cambiar la configuración de energía.}}<br />
Para invitados de Windows 8 (o posteriores), es mejor desactivar "Activar inicio rápido (recomendado)" en Opciones de energía del Panel de control, ya que hace que el invitado se bloquee durante cada arranque.<br />
<br />
El inicio rápido también puede necesitar deshabilitarse para que los cambios en la opción {{ic|-smp}} se apliquen correctamente.<br />
<br />
==== Protocolo de escritorio remoto ====<br />
<br />
Si utiliza un invitado de MS Windows, puede utilizar RDP para conectarse a su VM invitada. Si está utilizando una VLAN o no está en la misma red que el invitado, utilice:<br />
<br />
$ qemu-system-i386 -nographic -net user,hostfwd=tcp::5555-:3389<br />
<br />
A continuación, conéctese con {{Pkg|rdesktop}} ó {{Pkg|freerdp}} al invitado. Por ejemplo:<br />
<br />
$ xfreerdp -g 2048x1152 localhost:5555 -z -x lan<br />
<br />
== Solución de problemas ==<br />
<br />
=== La máquina virtual virtual corre muy lento ===<br />
<br />
Hay algunas técnicas que se pueden usar para implementar rendimiento en la máquina virtual, por ejemplo:<br />
<br />
* Use la opción {{ic|-cpu host}} para hacer que QEMU emule la CPU del host. Si no se hace esto, podría intentar emular un CPU más genérico.<br />
* Especialmente para los invitados de Windows, habilite [https://blog.wikichoon.com/2014/07/enabling-hyper-v-enlightenments-with-kvm.html Iluminaciones de Hyper-V]: {{ic|1=-Host de la CPU, hv_relaxed, hv_spinlocks=0x1fff, hv_vapic, hv_time}}.<br />
* Si la máquina host tiene varias CPUs, asigne al invitado más CPUs usando la opción {{ic|-smp}}.<br />
* Asegúrese de haber asignado a la máquina virtual suficiente memoria. De forma predeterminada, QEMU sólo asigna 128 MiB de memoria a cada máquina virtual. Utilice la opción {{ic|-m}} para asignar más memoria. Por ejemplo, {{ic|-m 1024}} ejecuta una máquina virtual con 1024 MiB de memoria.<br />
* Utilice KVM si es posible: agregue {{ic|1=-machine type=pc, accel=kvm}} al comando de arranque QEMU que utilice.<br />
* Si es compatible con los controladores del sistema operativo invitado, utilice [https://wiki.libvirt.org/page/Virtio virtio] para dispositivos de red y/o bloque. Por ejemplo:<br />
$ qemu-system-i386 -net nic, model=virtio -net tap, if=tap0, script=no-drive file=''disk_image'',media=disco, if=virtio<br />
* Utilizar dispositivos TAP en lugar de redes en modo usuario. Consulte [[#Tap de red con QEMU]].<br />
* Si el sistema operativo invitado está haciendo escritura pesada en su disco, puede beneficiarse de ciertas opciones de montaje en el sistema de archivos del host. Por ejemplo, puede montar un [[Ext4|sistema de archivos ext4]] con la opción {{ic|1=barrier=0}}. Debe leer la documentación de las opciones que cambie porque a veces las opciones de mejora de rendimiento para los sistemas de archivos tienen el costo de integridad de los datos.<br />
* Si tiene una imagen de disco sin procesar, puede deshabilitar la caché:<br />
$ qemu-system-i386 -drive file=''disk_image'', if=virtio, cache=none<br />
* Utilice el nativo Linux AIO:<br />
$ qemu-system-i386 -drive file=''disk_image'', if=virtio, aio=native<br />
* Si utiliza una imagen de disco qcow2, el rendimiento de E/S se puede mejorar considerablemente al garantizar que el caché L2 es de tamaño suficiente. La fórmula [https://blogs.igalia.com/berto/2015/12/17/improving-disk-io-performance-in-qemu-2-5-with-the-qcow2-l2-cache/] para calcular La caché L2 es: l2_cache_size = disk_size * 8 / cluster_size. Suponiendo que la imagen qcow2 se creó con el tamaño de clúster predeterminado de 64 K, esto significa que para cada 8 GB de tamaño de la imagen qcow2, 1 MB de caché L2 es mejor para el rendimiento. QEMU utiliza sólo 1 MB por defecto; Especificar una caché más grande se hace en la línea de comandos QEMU. Por ejemplo, para especificar 4 MB de caché (adecuado para un disco de 32 GB con un tamaño de clúster de 64 KB):<br />
$ qemu-system-i386 -drive file=''disk_image'',format=qcow2, l2-cache-size=4M<br />
* Si está ejecutando varias máquinas virtuales al mismo tiempo que todas tienen el mismo sistema operativo instalado, puede ahorrar memoria al habilitar [[wikipedia: Kernel_SamePage_Merging_ (KSM)|kernel de la misma página de fusión]]. Consulte [[#Habilitar KSM]].<br />
* En algunos casos, la memoria se puede recuperar de correr máquinas virtuales ejecutando un controlador de globo de memoria en el sistema operativo invitado y lanzando QEMU con la opción {{ic|-balloon virtio}}.<br />
* Es posible utilizar una capa de emulación para un controlador ICH-9 AHCI (aunque puede ser inestable). La emulación AHCI soporta [[Wikipedia: Native_Command_Queuing|NCQ]], por lo que varias peticiones de lectura o escritura pueden estar pendientes al mismo tiempo:<br />
$ qemu-system-i386 -drive id=disc, file=''disk_image'', if=none -device ich9-ahci, id=ahci -device ide-drive, drive=disk, bus=ahci.0<br />
<br />
Mira https://www.linux-kvm.org/page/Tuning_KVM para más información.<br />
<br />
=== El cursor del ratón está nervioso o errático ===<br />
<br />
Si el cursor "brinca" descontroladamente, podría ayudar ingresar este comando en la terminal antes de iniciar QEMU<br />
<br />
$ export SDL_VIDEO_X11_DGAMOUSE=0<br />
<br />
Si funciono, puedes agregarlo a tu {{ic|~/.bashrc}} archivo.<br />
<br />
=== El cursor no es visible ===<br />
<br />
Añade {{ic|-show-cursor}} a las opciones de QEMU para poder ver el cursor.<br />
<br />
Si persiste, asegurate de configurar la pantalla apropiadamente<br />
<br />
Por ejemplo: {{ic|-vga qxl}}<br />
<br />
=== No se puede mover / adjuntar el cursor ===<br />
<br />
Reemplaza {{ic|-usbdevice tablet}} con {{ic|-usb}} como opción en QEMU.<br />
<br />
=== El teclado parece roto ó las teclas de flecha no funcionan ===<br />
<br />
Probablemente notarás que algunas de tus teclas no funcionan ó "presionan" la tecla equivocada (en particular, las flechas), preferentemente, necesitas especificar la distribución de tu teclado como una opción. La distribución del teclado puede encontrarse en {{ic|/usr/share/qemu/keymaps}}.<br />
<br />
$ qemu-system-i386 -k ''keymap'' ''disk_image''<br />
<br />
=== Pantalla de invitado estirada en el tamaño de la ventana ===<br />
<br />
Para restarurar el tamaño por defecto de la ventanta, presiona {{ic|Ctrl+Alt+u}}.<br />
<br />
=== ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy ===<br />
<br />
Si un mensaje de error como este es listado en el arranque de QEMU con la opción {{ic|-enable-kvm}}:<br />
<br />
ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy<br />
failed to initialize KVM: Device or resource busy<br />
<br />
Significa que otro [[hypervisor]] está actualmente activo. No se recomienda ó no es poible correr varios hypervisores en paralelo.<br />
<br />
=== Mensaje de error libgfapi ===<br />
<br />
El mensaje de error listado en el arranque:<br />
<br />
Failed to open module: libgfapi.so.0: cannot open shared object file: No such file or directory<br />
<br />
No es un problema, sólo significa que hace falta la dependencia opcional de GlusterFS<br />
<br />
=== Kernel panic en entornos live ===<br />
<br />
Si inicia un sistema en vivo (ó bootea uno) podría encontrar esto:<br />
<br />
end Kernel panic - not syncing: VFS: Unable to mount root fs on unknown block(0,0)<br />
<br />
Ó algún otro proceso de arranque (ej. no se puede desempaquetar initramfs, no puede iniciar un servicio foo).<br />
<br />
Intente iniciar la Máquina Virtual con el {{ic|-m VALOR}} switch y un tamaño apropiado de RAM, si la RAM es muy poca probablemente encontrará problemas similares a los anteriores.<br />
<br />
== Ver también ==<br />
<br />
* [https://qemu.org Sitio web oficial de QEMU]<br />
* [https://www.linux-kvm.org Sitio web oficial de KVM]<br />
* [https://web.archive.org/web/20200514080826/https://qemu.weilnetz.de/doc/qemu-doc.html Documentación para el usuario del emulador QEMU] (en inglés)<br />
* [https://en.wikibooks.org/wiki/QEMU Wikilibro de QEMU] (en inglés)<br />
* [http://alien.slackbook.org/dokuwiki/doku.php?id=slackware:qemu Virtualización de hardware con QEMU por AlienBOB (última actualización en 2008) (en inglés)<br />
* [http://blog.falconindy.com/articles/build-a-virtual-army.html Construyendo un ejército virtual] por Falconindy (en inglés)<br />
* [https://git.qemu.org/?p=qemu.git;a=tree;f=docs Últimos documentos]<br />
* [https://qemu.weilnetz.de/ QEMU en Windows]<br />
* [[wikipedia:Qemu|Wikipedia]]<br />
* [https://wiki.debian.org/QEMU QEMU - Wiki de Debian] (en inglés)<br />
* [https://people.gnome.org/~markmc/qemu-networking.html QEMU Networking on gnome.org]{{Dead link (Español)|2022|09|22|status=404}}<br />
* [http://bsdwiki.reedmedia.net/wiki/networking_qemu_virtual_bsd_systems.html Red virtual de QEMU en sistemas BSD] (en inglés)<br />
* [https://www.gnu.org/software/hurd/hurd/running/qemu.html QEMU on gnu.org]<br />
* [https://wiki.freebsd.org/qemu QEMU en FreeBSD como host] (en inglés)</div>Malcontenthttps://wiki.archlinux.org/index.php?title=QEMU_(Espa%C3%B1ol)&diff=796047QEMU (Español)2024-01-04T16:29:52Z<p>Malcontent: Add Spanish translation for VirtIO sound</p>
<hr />
<div>[[Category:Emulation (Español)]]<br />
[[Category:Hypervisors (Español)]]<br />
[[de:QEMU]]<br />
[[en:QEMU]]<br />
[[fr:QEMU]]<br />
[[ja:QEMU]]<br />
[[zh-hans:QEMU]]<br />
{{Bad translation (Español)|No updates since 2017-01-12, English page has seen major changes since.}}<br />
{{TranslationStatus (Español)|QEMU|2017-01-12|463282}}<br />
{{Related articles start (Español)}}<br />
{{Related|:Category:Hypervisors}}<br />
{{Related|Libvirt}}<br />
{{Related articles end}}<br />
<br />
De acuerdo con [https://wiki.qemu.org/Main_Page la wiki de QEMU], "QEMU es un emulador genérico y de código abierto de máquinas virtuales."<br />
<br />
Cuando se utiliza como un emulador de máquina, QEMU puede correr sistemas operativos y programas hechos para una máquina en particular (por ej. una placa ARM) en una máquina diferente (e.j. tu PC x86). Usando la traducción dinámica, se consigue un rendimiento muy bueno.<br />
<br />
QEMU puede usar hipervisores como [[Xen]] o [[KVM]] para utilizar las extensiones del procesador para la virtualización. Cuando se utiliza como virtualizador, QEMU alcanza un performance cercano a el rendimiento nativo ejecutando el código de invitado directamente en el CPU host.<br />
<br />
== Instalación ==<br />
<br />
[[Help:Reading (Español)#Instalación de paquetes|Instale]] el paquete {{Pkg|qemu-desktop}} (ó {{Pkg|qemu-base}} para la versión sin GUI) y los paquetes opcionales para tus necesidades:<br />
<br />
* {{Pkg|qemu-emulators-full}} - Soporte extra para arquitecturas<br />
* {{Pkg|qemu-block-gluster}} - Soporte para bloque glusterfs <br />
* {{Pkg|qemu-block-iscsi}} - Soporte para bloque iSCSI <br />
* {{Pkg|qemu-block-rbd}}{{Broken package link (Español)|package not found}} - Soporte para bloque RBD <br />
* {{Pkg|samba}} - SMB/ Soporte para servidor CIFS<br />
<br />
== front-ends para QEMU ==<br />
<br />
A diferencia de otros programas de virtualización como [[VirtualBox]] y [[VMware]], QEMU no proporciona una interfaz gráfica de usuario para administrar máquinas virtuales (a parte de la ventana que aparece cuando se ejecuta una máquina virtual), tampoco proporciona una forma de crear una máquina virtual persistente con valores guardados. Todos los parámetros para ejecutar una máquina virtual deben especificarse en la línea de comandos en cada puesta en marcha, a menos que haga un script personalizadp para iniciar su máquina(s) virtual. Sin embargo, hay varios front-end GUI para QEMU: <br />
<br />
* {{AUR|qemu-launcher}}<br />
* {{AUR|qtemu}}<br />
* {{AUR|aqemu}}<br />
<br />
front-ends con soporte para QEMU están disponibles por [[libvirt]].<br />
<br />
== Creando un nuevo sistema virtualizado ==<br />
<br />
=== Creando una imagen de disco duro ===<br />
<br />
{{Tip (Español)|Véase la [https://en.wikibooks.org/wiki/QEMU/Images Wiki de QEMU] para más información sobre imágenes de QEMU.}}<br />
<br />
Para ejecutar QMEU necesitarás una imagen de disco duro, a menos que estés cargando un sistema en vivo desde el CD-ROM ó la red (y no para instalar un sistema operativo en una imagen de disco duro). Una imagen de disco es un archivo que almacena los contenidos del disco duro emulado.<br />
<br />
Una imagen de disco puede ser en "crudo", de manera que, literalemte, byte por byte es lo mismo que el cliente ve, y siempre utilizará toda la capacidad del disco duro del disco duro invitado en el host. Este método proporciona la menor sobrecarga de Entrada / Salida, pero puede desperdiciar una gran cantidad de espacio, ya que el espacio no utilizado por el invitado no se puede utilizar en el host. <br />
<br />
Por otra parte, la imagen de disco duro puede estar en un formato tal como el de ''qcow2'' el cuál únicamente asigna espacio a el archivo de la imagen cuando el SO invitado está escribiendo en los sectores del disco virtual. La imagen aparece como el tamaño total del sistema operativo huésped, a pesar que puede tomar hasta una cantidad muy pequeña de espacio en el sistema host. El uso de este formato en lugar de el "crudo" probablemente afecte el rendimiento. <br />
<br />
QEMU proporciona el {{ic|qemu-img}} comando para crear imagenes de disco.<br />
Por ejemplo, para crear una imagen de 4GB en formato "crudo":<br />
<br />
$ qemu-img create -f raw ''image_file'' 4G<br />
<br />
Se puede uiltizar {{ic|-f qcow2}} para crear un disco ''qcow2'' en su lugar. <br />
<br />
{{Note (Español)|También puedes simplemente crear una imagen "cruda" meidante la creación de un archivo del tamaño necesitado usando {{ic|dd}} ó {{ic|fallocate}}.}}<br />
<br />
{{Warning (Español)|Si almacenas una imágen de disco en un sistema de archivos [[Btrfs (Español)|Btrfs]], deberías considerar deshabilitar [[Btrfs (Español)#Copy-on-Write (CoW)|Copy-on-Write]] para el directorio antes de crear imágenes.}}<br />
<br />
==== Superposición de imágenes de almacenamiento ====<br />
<br />
Puede crear una imagen de almacenamiento una vez (la imagen de respaldo) y hacer que QEMU mantenga mutaciones a esta imagen en una imagen de superposición. Esto le permite volver a un estado anterior de esta imagen de almacenamiento. Puede volver a crear una nueva imagen de superposición en el momento en que desea revertir en función de la imagen de respaldo original.<br />
<br />
Para crear una imagen de superposición, ingrese el comando:<br />
<br />
$ qemu-img create -o backing_file=''img1.raw'',backing_fmt=''raw'' -f ''qcow2'' ''img1.cow''<br />
<br />
Después de eso, puede ejecutar su máquina virtual como de costumbre (ver [[#Ejecución del sistema virtualizado]]):<br />
<br />
$ qemu-system-x86_64 ''img1.cow''<br />
<br />
La imagen de respaldo se dejará intacta y se registrarán mutaciones en este almacenamiento en el archivo de imagen de superposición.<br />
<br />
Cuando cambia la ruta de acceso a la imagen de respaldo, se requiere reparación.<br />
<br />
{{Warning (Español)|La ruta del sistema de archivos absoluto de la imagen de respaldo se almacena en el archivo de imagen de superposición (binario)). Cambiar el trayecto de la imagen de respaldo requiere un esfuerzo.}}<br />
<br />
Asegúrese de que la ruta de la imagen de respaldo original sigue conduciendo a esta imagen. Si es necesario, haga un enlace simbólico en la ruta original a la nueva ruta. A continuación, emita un comando como:<br />
<br />
$ qemu-img rebase -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
A su discreción, usted puede alternativamente realizar un rebase 'inseguro' donde no se comprueba la ruta anterior a la imagen de respaldo:<br />
<br />
$ qemu-img rebase -u -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
==== Cambiar el tamaño de una imagen ====<br />
<br />
{{Warning (Español)|Cambiar el tamaño de una imagen que contiene un sistema de arranque NTFS podría hacer el sistema operativo instalado '''no arrancable'''. Para una explicación completa y solucioón alternativa mira [https://web.archive.org/web/20180319230757/http://tjworld.net/wiki/Howto/ResizeQemuDiskImages].}}<br />
<br />
El ejecutable {{ic|qemu-img}} tiene la opción {{ic|resize}}, que permite redimensionar fácilmente una imagen de disco duro. Funciona tanto para ''raw'' como para ''qcow2''. Por ejemplo, para aumentar el espacio de imagen en 10GB, ingresa:<br />
<br />
$ qemu-img resize ''disk_image'' +10G<br />
<br />
Después de ampliar la imagen de disco, debe utilizar el sistema de archivos y las herramientas de particionamiento dentro de la máquina virtual para comenzar a utilizar el nuevo espacio. Al reducir una imagen de disco, primero debe reducir los sistemas de archivos y los tamaños de partición asignados usando el sistema de archivos y las herramientas de partición dentro de la máquina virtual y luego reducir la imagen del disco en consecuencia, de lo contrario reducir la imagen del disco resultará en ¡pérdida de datos!<br />
<br />
=== Preparando el medio de instalación ===<br />
<br />
Para instalar un sistema operativo en su imagen de disco, necesita el medio de instalación (por ejemplo, disco óptico, unidad USB o imagen ISO) para el sistema operativo. El soporte de instalación no debe montarse porque QEMU accede directamente al medio.<br />
<br />
{{Tip (Español)|Si utiliza un disco óptico, es una buena idea volcar primero los medios a un archivo porque esto mejora el rendimiento y no requiere que tenga acceso directo a los dispositivos (es decir, puede ejecutar QEMU como un usuario normal sin tener Para cambiar permisos de acceso en el archivo de dispositivo del medio). Por ejemplo, si el nodo de dispositivo de CD-ROM tiene el nombre {{ic|/dev/cdrom}}, puede volcarlo a un archivo de comandos: {{bc|1=$ dd if=/dev/cdrom of=''Cd_image.iso''}}}}<br />
<br />
=== Instalando el sistema operativo ===<br />
<br />
Esta es la primera vez que necesitará iniciar el emulador. Para instalar el sistema operativo en la imagen de disco, debe adjuntar la imagen de disco y el medio de instalación a la máquina virtual y hacer que arranque desde el soporte de instalación.<br />
<br />
Por ejemplo, en invitados i386, para instalar desde un archivo ISO de arranque como CD-ROM y una imagen de disco sin formato:<br />
<br />
$ qemu-system-x86_64 -cdrom ''iso_image'' -boot order=d -drive file=''disk_image'',format=raw<br />
<br />
Consulte {{ic | qemu (1)}} para obtener más información sobre cómo cargar otros tipos de medios (como disquetes, imágenes de disco o unidades físicas) y [[#Ejecución del sistema virtualizado]] para otras opciones útiles.<br />
<br />
Una vez que el sistema operativo haya finalizado de instalar, la imagen de QEMU se puede iniciar directamente (ver [[#Ejecución del sistema virtualizado]]).<br />
<br />
{{Warning (Español)|De forma predeterminada, sólo se asignan 128 MB de memoria a la máquina. La cantidad de memoria se puede ajustar con el interruptor {{ic | -m}}, por ejemplo {{ic | -m 512M}} o {{ic | -m 2G}}.}}<br />
<br />
{{Tip (Español)|<br />
* En lugar de especificar {{ic | 1 = -boot order = x}}, algunos usuarios pueden sentirse más cómodos usando un menú de arranque: {{ic | 1 = -boot menu = on}}, al menos durante la configuración y la experimentación.<br />
* Si necesita reemplazar disquetes o CD como parte del proceso de instalación, puede usar el monitor de la máquina QEMU (presione {{ic | Ctrl + Alt + 2}} en la ventana de la máquina virtual) para quitar y conectar dispositivos de almacenamiento a un máquina virtual. Escriba {{ic | info block}} para ver los dispositivos de bloque y use el comando {{ic | change}} para intercambiar un dispositivo. Pulse {{ic | Ctrl + Alt + 1}} para volver a la máquina virtual.}}<br />
<br />
== Ejecución del sistema virtualizado ==<br />
<br />
Los binarios {{ic|qemu-system-*}} (por e.j. {{ic|qemu-system-i386}} ó {{ic|qemu-system-x86_64}}, dependiendo de la arquitectura del huésped) se usan para ejecutar el sistema virtualizado. El uso es:<br />
<br />
$ qemu-system-x86_64 ''options'' ''disk_image''<br />
<br />
Las opciones son las mismas para todos los binarios {{ic|qemu-system-*}}, mira {{ic|qemu(1)}} para más información sobre todas las opciones.<br />
<br />
Por defecto, QEMU mostrará la salida de video de la máquina virtual en una ventana. Una cosa a considerar: al hacer click dentro de la ventana de QMEU, el puntero del cursor será capturado. Para liberarlo presione {{ic|Ctrl+Alt+g}}.<br />
<br />
{{Warning (Español)|QEMU nunca debe ejecutarse como root. Si se debe iniciar en root, deberá usar la opción {{ic|-runas}} para que QEMU utilice privilegios de root.}}<br />
<br />
=== Activar KVM ===<br />
<br />
KVM debe ser soportado por su procesador y kernel, y necesariamente los [[kernel modules (Español)|módulos del kernel]] deben ser cargados. Mira [[KVM]] para más información.<br />
<br />
Para iniciar QEMU en modo KVM, adjunta {{ic|-enable-kvm}} a las opciones de inicio adicionales. Para verificar si KVM está activado para ejecutar una máquina virtual, ingresa a la wiki de QEMU [https://en.wikibooks.org/wiki/QEMU/Monitor Monitor], usando {{ic|Ctrl+Alt+Shift+2}}, e ingresando {{ic|info kvm}}. <br />
<br />
{{Note (Español)|<br />
* Si inicia su máquina virtual con una herramienta GUI y experimenta un rendimiento muy malo, debe verificar el soporte adecuado de KVM. <br />
* KVM necesita activarse en orden de iniciar adecuadamente Windows 7 y Windows 8 sin ''pantallazo azul''.<br />
}}<br />
<br />
=== Habilitar soporte IOMMU (Intel VT-d/AMD-Vi) ===<br />
<br />
Usando IOMMU (unidad de gestión de memoria de entrada y salida) se abre a las caraterísticas como el paso del PCI y la protección de la memoria de dispositivos defectuosos o maliciosos, mira [[wikipedia:Input-output memory management unit#Advantages]] y [https://www.quora.com/Memory-Management-computer-programming/Could-you-explain-IOMMU-in-plain-English Memory Management (computer programming): Could you explain IOMMU in plain English?].<br />
<br />
Para habilitar IOMMU:<br />
#Asegure que AMD-Vi/Intel VT-d es soportado por el CPU y es habilitado en la configuración de BIOS.<br />
#Agregue {{ic|1=intel_iommu=on}} si tienes un procesador Intel ó {{ic|1=amd_iommu=on}} si tienes un procesador AMD en los parámetros del kernel ([[kernel parameters]])<br />
#Reinicie y asegure que IOMMU está habilitado verificando {{ic|dmesg}} para {{ic|DMAR}}: {{ic|[0.000000] DMAR: IOMMU enabled}}<br />
#Añade {{ic|-device intel-iommu}} para crear el dispositivo IOMMU:<br />
<br />
$ qemu-system-x86_64 '''-enable-kvm -machine q35 -device intel-iommu''' -cpu host ..<br />
<br />
== Mover datos entre el host y el Sistema Operativo huésped ==<br />
<br />
=== Red ===<br />
<br />
Los datos pueden compartirse entre el host y el sistema operativo huésped usando cualquier protocolo de red que pueda transferir archivos, como [[NFS]], [[SMB]], [[Wikipedia:Network Block Device|NBD]], HTTP, [[Very Secure FTP Daemon|FTP]], ó [[SSH]], siempre que haya configurado la red apropiadamente y haya habilitado los servicios apropiados. <br />
<br />
La red por defecto del modo de usuario permite al huésped acceder al sistema operativo host en la dirección IP 10.0.2.2. Todos los servidores que se estén ejecutando en el sistema operativo anfitrión, como un servidor SSH o un servidor SMB, estarán accesibles en esta dirección IP. Así que en los invitados, puede montar los directorios exportados en el host a través de [[SMB]] o [[NFS]], o puede acceder al servidor HTTP del host, etc.<br />
No será posible que el sistema operativo anfitrión acceda a los servidores que se ejecutan en el sistema operativo invitado, pero esto puede hacerse con otras configuraciones de red (consulte [[#Tap de red con QEMU]]).<br />
<br />
=== Servidor SMB incorporado de QEMU ===<br />
<br />
La documentación de QEMU dice que tiene un servidor SMB "incorporado", pero en realidad acaba de iniciar [[Samba]] con un archivo {{ic | smb.conf}} generado automáticamente ubicado en {{ic|/tmp/qemu- Smb.''Pid''-0/smb.conf}} y lo hace accesible para el invitado en una dirección IP diferente (10.0.2.4 por defecto). Esto sólo funciona para la red de usuarios, y esto no es necesariamente muy útil ya que el invitado también puede acceder al servicio normal [[Samba]] en el host si ha configurado acciones en él.<br />
<br />
Para habilitar esta característica, inicie QEMU con un comando como:<br />
<br />
$ qemu-system-x86_64 -nic user,id=nic0,smb=''shared_dir_path'' ''disk_image''<br />
<br />
donde {{ic|''shared_dir_path''}} es un directorio que quieres compartir entre huésped y el host.<br />
<br />
Luego, en el invitado, podrá acceder al directorio compartido del host 10.0.2.4 con el nombre de recurso "qemu". Por ejemplo, en el Explorador de Windows iría a {{ic | \\ 10.0.2.4 \ qemu}}.<br />
<br />
{{Note (Español)|<br />
* Si estás usando opciones de compartir varias veces como {{ic|1=-net user, smb='' shared_dir_path1 '' -net user, smb='' shared_dir_path2 ''}} ó {{ic | 1 = -net user , Smb = '' shared_dir_path1 '', smb = '' shared_dir_path2 ''}} entonces solo compartirá el último definido.<br />
* Si no puede acceder a la carpeta compartida y el sistema invitado es Windows, compruebe que está habilitado el protocolo [http://ecross.mvps.org/howto/enable-netbios-over-tcp-ip-with-windows.htm NetBIOS ]{{Dead link (Español)|2023|05|06|status=domain name not resolved}} Y que un cortafuegos no bloquea los puertos [https://technet.microsoft.com/en-us/library/cc940063.aspx] utilizados por el protocolo NetBIOS.<br />
}}<br />
<br />
=== Montaje de una partición dentro de una imagen de disco raw ===<br />
<br />
Cuando la máquina virtual no se está ejecutando, es posible montar las particiones que están dentro de un archivo de imagen de disco sin formato configurándolas como dispositivos de bucle invertido. Esto no funciona con imágenes de disco en formatos especiales, como qcow2, aunque se pueden montar usando {{ic|qemu-nbd}}.<br />
<br />
{{Warning (Español)| Debe asegurarse de desmontar las particiones antes de ejecutar la máquina virtual de nuevo. De lo contrario, es muy probable que ocurra la corrupción de datos.}}<br />
<br />
==== Con la especificación manual del desplazamiento de bytes ====<br />
<br />
Una forma de montar una partición de imagen de disco es montar la imagen de disco en un cierto desplazamiento usando un comando como el siguiente:<br />
<br />
$ mount -o loop, offset = 32256 ''disk_image'' ''mountpoint''<br />
<br />
La opción {{ic|1 = offset = 32256}} se pasa realmente al programa {{ic|losetup}} para configurar un dispositivo de bucle invertido que empieza en el desplazamiento de byte 32256 del archivo y continúa hasta el final. A continuación, se monta este dispositivo de bucle invertido. También puede utilizar la opción {{ic|sizelimit}} para especificar el tamaño exacto de la partición, pero esto normalmente no es necesario.<br />
<br />
Dependiendo de la imagen del disco, la partición necesaria no se puede iniciar en el desplazamiento 32256. Ejecute {{ic|fdisk -l '' disk_image ''}} para ver las particiones de la imagen. Fdisk da las compensaciones de inicio y fin en sectores de 512 bytes, así que multiplique por 512 para obtener el desplazamiento correcto para pasar a {{ic|mount}}.<br />
<br />
==== Con las particiones autodetecting del módulo de bucle (loop) ====<br />
<br />
El controlador de bucle de Linux realmente admite particiones en dispositivos de bucle invertido, pero está desactivado de forma predeterminada. Para habilitarlo, haga lo siguiente:<br />
<br />
* Deshacerse de todos los dispositivos de bucle invertido (desmontar todas las imágenes montadas, etc.).<br />
* [[Kernel modules (Español)#Manejo manual de módulos|Descargar]] el módulo del kernel {{ic|loop}} y cargarlo con el conjunto de parámetros {{ic|1 = max_part = 15}}. Además, el número máximo de dispositivos de bucle puede controlarse con el parámetro {{ic | max_loop}}.<br />
<br />
{{Tip (Español)|Puede poner una entrada en {{ic|/etc/modprobe.d}} para cargar el módulo de bucle con {{ic|1=max_part=15}} cada vez, o puede poner {{ic|1 = loop.max_part = 15}} en la línea de comandos del kernel, dependiendo de si tiene o no el módulo {{ic|loop.ko}} integrado en su kernel.}}<br />
<br />
Configure su imagen como un dispositivo de bucle invertido:<br />
<br />
$ losetup -f -P ''disk_image''<br />
<br />
Entonces, si el dispositivo creado fue {{ic|/dev/loop0}}, se habrán creado automáticamente dispositivos adicionales {{ic|/dev/loop0pX}}, donde X es el número de la partición. Estos dispositivos de loopback de partición se pueden montar directamente. Por ejemplo:<br />
<br />
$ mount /dev/loop0p1 ''punto de montaje''<br />
<br />
Para montar la imagen de disco con '' udisksctl '', vea [[Udisks#Mount loop devices]].<br />
<br />
==== Con kpartx ====<br />
<br />
'' 'Kpartx' '' del paquete {{Pkg|multipath-tools}} puede leer una tabla de particiones en un dispositivo y crear un nuevo dispositivo para cada partición. Por ejemplo:<br />
# Kpartx -a '' disk_image ''<br />
<br />
Esto configurará el dispositivo de bucle invertido y creará los dispositivos de partición necesarios en {{ic|/dev/mapper/}}.<br />
<br />
=== Montar una partición dentro de una imagen qcow2 ===<br />
<br />
Puede montar una partición dentro de una imagen qcow2 usando {{ic|qemu-nbd}}. Mira [https://en.wikibooks.org/wiki/QEMU/Images#Mounting_an_image_on_the_host Wikibooks].<br />
<br />
=== Utilizar cualquier partición real como la única partición primaria de una imagen de disco duro ===<br />
<br />
A veces, puede que desee utilizar una de las particiones del sistema desde dentro de QEMU. El uso de una partición sin procesar para una máquina virtual mejorará el rendimiento, ya que las operaciones de lectura y escritura no pasan por la capa del sistema de archivos del host físico. Esta partición también proporciona una forma de compartir datos entre el host y el invitado.<br />
<br />
En Arch Linux, los archivos de dispositivo para las particiones sin procesar son, por defecto, propiedad de '' root '' y del grupo '' disk ''. Si desea que un usuario no root pueda leer y escribir en una partición en bruto, debe cambiar el propietario del archivo de dispositivo de la partición para ese usuario.<br />
<br />
{{Warning (Español)|<br />
* Aunque es posible, no se recomienda permitir que las máquinas virtuales alteren los datos críticos en el sistema host, como la partición raíz.<br />
* No debe montar un sistema de archivos en una partición de lectura-escritura en el host y el invitado al mismo tiempo. De lo contrario, se producirá corrupción de datos.<br />
}}<br />
<br />
Después de hacerlo, puede adjuntar la partición a una máquina virtual QEMU como un disco virtual.<br />
<br />
Sin embargo, las cosas son un poco más complicadas si desea tener la máquina virtual ''completa'' contenida en una partición. En ese caso, no habría ningún archivo de imagen de disco para arrancar realmente la máquina virtual, ya que no se puede instalar un cargador de arranque en una partición que está formateada como un sistema de archivos y no como un dispositivo particionado con un MBR. Una máquina virtual de este tipo se puede iniciar especificando el kernel y el initramfs manualmente o simulando un disco con un MBR usando RAID lineal.<br />
<br />
==== Especificar el kernel y el initrd manualmente ====<br />
<br />
QEMU es compatible con cargar [[Kernels|Linux kernels]] e [[initramfs|init ramdisks]] directamente, evitando así los cargadores de arranque como [[GRUB]]. A continuación, se puede iniciar con la partición física que contiene el sistema de archivos raíz como el disco virtual, que no parecen ser particionados. Esto se hace emitiendo un comando similar al siguiente:<br />
<br />
{{Note (Español)| En este ejemplo, se trata de las imágenes del '''host''' que se están utilizando, no del invitado. Si desea utilizar las imágenes del huésped, monte {{ic|/dev/sda3}} de sólo lectura (para proteger el sistema de archivos del host) y especifique {{ic|/full/path/to/images}} ó usar algún truco kexec en el invitado para recargar el kernel del invitado (extiende el tiempo de arranque).}}<br />
<br />
$ Qemu-system-i386 -kernel /boot/vmlinuz-linux -initrd /boot/initramfs-linux.img -append root=/dev/sda/dev/sda3<br />
<br />
En el ejemplo anterior, la partición física que se utiliza para el sistema de archivos raíz del huésped es {{ic|/dev/sda3}} en el host, pero aparece como {{ic|/dev/sda}} en el invitado.<br />
<br />
Por supuesto, puede especificar cualquier kernel e initrd que desee, y no sólo los que vienen con Arch Linux.<br />
<br />
Cuando hay varios [[kernel parameters]] que se pasan a la opción {{ic|-append}}, necesitan ser citados usando comillas simples o dobles. Por ejemplo:<br />
<br />
$ ... -append 'root=/dev/sda1 console=ttyS0'<br />
<br />
==== Simular disco virtual con MBR usando RAID lineal ====<br />
<br />
Una forma más complicada de tener una máquina virtual usar una partición física, mientras que mantener esa partición formateada como un sistema de archivos y no sólo tener la partición invitado la partición como si fuera un disco, es simular un MBR para que pueda Arranque utilizando un gestor de arranque tal como GRUB.<br />
<br />
Puede hacerlo utilizando el RAID del software en modo lineal (necesita el controlador de kernel {{ic|linear.ko}}) y un dispositivo de loopback: el truco consiste en añadir previamente un registro maestro de arranque (MBR) Real que desea incrustar en una imagen de disco RAEM QEMU.<br />
<br />
Suponga que tiene una partición simple {{ic|/|hdaN}} con algún sistema de archivos en la que desea formar parte de una imagen de disco QEMU. En primer lugar, crear un pequeño archivo para mantener el MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=32<br />
<br />
Aquí, se crea un archivo de 16 KB (32 * 512 bytes). Es importante no hacerlo demasiado pequeño (incluso si el MBR sólo necesita un bloque de 512 bytes), ya que cuanto menor sea, menor será el tamaño del chasis del dispositivo RAID de software, lo que podría tener un impacto En el rendimiento. A continuación, configura un dispositivo de bucle invertido en el archivo MBR:<br />
<br />
# losetup -f ''/path/to/mbr''<br />
<br />
Supongamos que el dispositivo resultante es {{ic|/dev/loop0}}, porque ya no habríamos estado usando otros bucle. El siguiente paso es crear la imagen de disco "fusionada" MBR + {{ic|/dev/hda''N''}} utilizando RAID de software:<br />
<br />
# modprobe lineal<br />
<br />
# mdadm --build --verbose /dev/md0 --chunk=16 --level=linear --raid-devices=2 /dev/loop0/dev/hda''N''<br />
<br />
El resultante {{ic|/dev/md0}} es lo que utilizará como una imagen de disco cruda QEMU (no olvide establecer los permisos para que el emulador pueda acceder a él). El último paso (y algo complicado) es configurar la configuración del disco (geometría del disco y tabla de particiones) para que el punto de inicio de la partición primaria en el MBR coincida con el de {{ic|/dev/hda''N''}}} Dentro {{ic|/dev/md0}} (un desplazamiento de exactamente 16 * 512 = 16384 bytes en este ejemplo). Hacer esto usando {{ic|fdisk}} en la máquina host, no en el emulador: la rutina de detección de disco crudo predeterminada de QEMU a menudo da lugar a offsets redondeados no kilobyte (como 31.5 KB, como en la sección anterior) que No puede ser administrado por el código RAID de software. Por lo tanto, desde el anfitrión:<br />
<br />
$ fdisk /dev/md0<br />
<br />
Pulse {{ic|X}} para entrar en el menú de expertos. Establezca el número de sectores por pista para que el tamaño de un cilindro coincida con el tamaño de su archivo MBR. Para dos cabezas y un tamaño de sector de 512, el número de sectores por pista debe ser 16, por lo que obtenemos cilindros de tamaño 2x16x512 = 16k.<br />
<br />
Ahora, presione {{ic|R}} para regresar al menú principal.<br />
<br />
Presione {{ic|P}} y compruebe que el tamaño del cilindro es ahora 16k.<br />
<br />
Ahora, cree una única partición primaria correspondiente a {{ic|/dev/hda''N''}}. Debe comenzar en el cilindro 2 y terminar en el extremo del disco (tenga en cuenta que el número de cilindros ahora difiere de lo que era cuando se introdujo fdisk.<br />
<br />
Finalmente, escribe el resultado al archivo: ya está. Ahora tiene una partición que puede montar directamente desde su host, así como parte de una imagen de disco QEMU:<br />
<br />
$ Qemu-system-i386 -hdc /dev/md0 ''[...]''<br />
<br />
Por supuesto, puede configurar con seguridad cualquier cargador de arranque en esta imagen de disco utilizando QEMU, siempre que la partición original {{ic|/dev/hda''N''}} contenga las herramientas necesarias.<br />
<br />
== Redes ==<br />
<br />
El rendimiento de la red virtual debería ser mejor con los dispositivos de derivación (tap) y puentes que con la red en modo de usuario o vde porque los dispositivos de derivación y los puentes se implementan en el kernel.<br />
<br />
Además, el rendimiento de la red se puede mejorar asignando a las máquinas virtuales un dispositivo de red [https://wiki.libvirt.org/page/Virtio virtio] en lugar de la emulación predeterminada de una NIC e1000. Consulte [[#Instalación de controladores virtio]] para obtener más información.<br />
<br />
=== Advertencia de dirección a nivel de enlace ===<br />
<br />
Al asignar el argumento {{ic|-net nic}} a QEMU, asignará por defecto a una máquina virtual una interfaz de red con la dirección de enlace {{ic|52:54:00:12:34:56}}. Sin embargo, cuando se utiliza la creación de redes puenteadas con varias máquinas virtuales, es esencial que cada máquina virtual tenga una dirección única de nivel de enlace (MAC) en el lado de la máquina virtual del dispositivo de derivación. De lo contrario, el puente no funcionará correctamente, ya que recibirá paquetes de varias fuentes que tienen la misma dirección de nivel de enlace. Este problema se produce incluso si los propios dispositivos de derivación tienen direcciones de nivel de enlace únicas porque la dirección de nivel de enlace de origen no se vuelve a escribir a medida que los paquetes pasan a través del dispositivo de derivación.<br />
<br />
Asegúrese de que cada máquina virtual tiene una dirección única de nivel de enlace, pero siempre debe comenzar con {{ic|52:54:}}. Utilice la opción siguiente, reemplazar ''X'' por un dígito hexadecimal arbitrario:<br />
<br />
$ qemu-system-i386 -net nic,macaddr=52:54:''XX:XX:XX:XX'' -net vde ''disk_image''<br />
<br />
Generar direcciones únicas de nivel de enlace se puede realizar de varias maneras:<br />
<br />
<ol><br />
<li>Especificar manualmente la dirección única de nivel de enlace para cada NIC. El beneficio es que el servidor DHCP asignará la misma dirección IP cada vez que se ejecute la máquina virtual, pero es inutilizable para un gran número de máquinas virtuales.<br />
</li><br />
<li>Generar dirección de nivel de enlace aleatoria cada vez que se ejecuta la máquina virtual. Prácticamente cero probabilidad de colisiones, pero la desventaja es que el servidor DHCP asignará una dirección IP diferente cada vez. Puede utilizar el siguiente comando en una secuencia de comandos para generar una dirección de nivel de enlace aleatoria en una variable {{ic|macaddr}}:<br />
<br />
{{bc|1=<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
qemu-system-i386 -net nic,macaddr="$macaddr" -net vde ''disk_image''<br />
}}<br />
<br />
</li><br />
<li>Utilice el siguiente script {{ic|qemu-mac-hasher.py}} para generar la dirección de nivel de enlace desde el nombre de la máquina virtual mediante una función de hash. Dado que los nombres de las máquinas virtuales son únicos, este método combina los beneficios de los métodos antes mencionados: genera la misma dirección de nivel de enlace cada vez que se ejecuta el script, aunque preserva la probabilidad prácticamente nula de colisiones.<br />
<br />
{{hc|qemu-mac-hasher.py|<nowiki><br />
#!/usr/bin/env python<br />
<br />
import sys<br />
import zlib<br />
<br />
if len(sys.argv) != 2:<br />
print("usage: %s <VM Name>" % sys.argv[0])<br />
sys.exit(1)<br />
<br />
crc = zlib.crc32(sys.argv[1].encode("utf-8")) & 0xffffffff<br />
crc = str(hex(crc))[2:]<br />
print("52:54:%s%s:%s%s:%s%s:%s%s" % tuple(crc))<br />
</nowiki>}}<br />
<br />
En un script, puede utilizar por ejemplo:<br />
<br />
vm_name="''VM Name''"<br />
qemu-system-i386 -name "$vm_name" -net nic,macaddr=$(qemu-mac-hasher.py "$vm_name") -net vde ''disk_image''<br />
</li><br />
</ol><br />
<br />
=== Redes en modo de usuario ===<br />
<br />
De forma predeterminada, sin ningún argumento {{ic|-netdev}}, QEMU utilizará la red en modo usuario con un servidor DHCP incorporado. A sus máquinas virtuales se les asignará una dirección IP cuando ejecuten su cliente DHCP, y podrán acceder a la red del host físico a través de la mascarada de IP realizada por QEMU.<br />
<br />
{{Warning (Español)| Esto sólo funciona con los protocolos TCP y UDP, por lo que ICMP, incluido {{ic|ping}}, no funcionará. No utilice {{ic|ping}} para probar la conectividad de red.}}<br />
<br />
Esta configuración predeterminada permite que sus máquinas virtuales accedan fácilmente a Internet, siempre que el host esté conectado a él, pero las máquinas virtuales no estarán directamente visibles en la red externa ni las máquinas virtuales podrán comunicarse entre sí si empieza Más de uno simultáneamente.<br />
<br />
La red de usuario en modo QEMU puede ofrecer más capacidades, como servidores TFTP o SMB incorporados, redirigir los puertos del host al huésped (por ejemplo, para permitir conexiones SSH al invitado) o conectar invitados a las VLAN para que puedan hablar entre sí. Consulte la documentación de QEMU en el indicador {{ic|-net user}} para obtener más detalles.<br />
<br />
Sin embargo, la conexión en red en modo usuario tiene limitaciones tanto en la utilidad como en el rendimiento. Las configuraciones de red más avanzadas requieren el uso de dispositivos de derivación u otros métodos.<br />
<br />
=== Tap de red con QEMU ===<br />
<br />
Los [[wikipedia:TUN/TAP|dispositivos tap]] Son una característica del kernel de Linux que le permite crear interfaces de red virtuales que aparecen como interfaces de red reales. Los paquetes enviados a una interfaz de derivación se entregan a un programa de espacio de usuario, tal como QEMU, que se ha enlazado a la interfaz.<br />
<br />
QEMU puede utilizar la red de derivación para una máquina virtual de modo que los paquetes enviados a la interfaz de derivación se envíen a la máquina virtual y aparezcan como procedentes de una interfaz de red (normalmente una interfaz Ethernet) en la máquina virtual. Por el contrario, todo lo que la máquina virtual envía a través de su interfaz de red aparecerá en la interfaz de tap.<br />
<br />
Los dispositivos de toque son soportados por los controladores de puente de Linux, por lo que es posible conectar entre sí los dispositivos entre sí y posiblemente con otras interfaces de host como {{ic|eth0}}. Esto es deseable si desea que sus máquinas virtuales puedan hablar entre sí, o si desea que otras máquinas en su LAN puedan hablar con las máquinas virtuales.<br />
<br />
{{Warning (Español)|Si conectas el dispositivo de toque y alguna interfaz de host, como {{ic|eth0}}, las máquinas virtuales aparecerán directamente en la red externa, lo que los exponerá a posibles ataques. Dependiendo de los recursos a los que tengan acceso sus máquinas virtuales, es posible que tenga que tomar todas las [[Firewalls|precauciones]] que normalmente tomaría al asegurar una computadora para proteger sus máquinas virtuales. Si el riesgo es demasiado grande, las máquinas virtuales tienen pocos recursos o se configuran varias máquinas virtuales, una solución mejor podría ser utilizar [[#Red de host solamente]] y configurar NAT. En este caso sólo necesitará un firewall en el host en lugar de múltiples firewalls para cada huésped.}}<br />
<br />
Como se indica en la sección de conexión en red de modo de usuario, los dispositivos de derivación ofrecen un rendimiento de red más alto que el modo de usuario. Si el OS invitado admite el controlador de red virtio, el rendimiento de la red se incrementará considerablemente también. Suponiendo el uso del dispositivo tap0, que el controlador virtio se utiliza en el invitado, y que no se utilizan scripts para ayudar a iniciar / detener la creación de redes, a continuación es parte del comando qemu se debe ver:<br />
<br />
-net nic, model=virtio -net tap, ifname=tap0, script=no, downscript=no<br />
<br />
Pero si ya está utilizando un dispositivo de tap con virtio controlador de red, uno puede incluso aumentar el rendimiento de la red mediante la activación de vhost, como:<br />
<br />
-net nic, model=virtio -net tap, ifname=tap0, script=no, downscript=no, vhost=on<br />
<br />
Ver http://www.linux-kvm.com/content/how-maximize-virtio-net-performance-vhost-net para obtener más información.<br />
<br />
==== Red de host solamente ====<br />
<br />
Si al puente se le da una dirección IP y se permite el tráfico destinado a ello, pero no hay una interfaz real (por ejemplo, {{ic|eth0}}) conectada al puente, las máquinas virtuales podrán hablar entre sí y la Sistema anfitrión. Sin embargo, no podrán hablar con nada en la red externa, siempre y cuando no configure IP enmascarada en el host físico. Esta configuración se llama '' red de host solamente '' por otro software de virtualización como [[VirtualBox]].<br />
<br />
{{Tip (Español)|<br />
* Si desea configurar IP masquerading, ej. NAT para máquinas virtuales, consulte la página [[Internet sharing#Enable NAT]].<br />
* Es posible que desee tener un servidor DHCP que se ejecute en la interfaz de puente para dar servicio a la red virtual. Por ejemplo, para usar la subred {{ic|172.20.0.1/16}} con [[dnsmasq]] como servidor DHCP:<br />
# ip addr add 172.20.0.1/16 dev br0<br />
# ip link set br0 up<br />
# dnsmasq --interface&#61;br0 --bind-interfaces --dhcp-range&#61;172.20.0.2,172.20.255.254<br />
}}<br />
<br />
==== Red interna ====<br />
<br />
Si no le da al puente una dirección IP y agrega una regla [[iptables]] para eliminar todo el tráfico al puente en la cadena INPUT, las máquinas virtuales podrán hablar entre sí, pero no con el host físico ó la red exterior. Esta configuración se llama "red interna" por otro software de virtualización como [[VirtualBox]]. Deberá asignar direcciones IP estáticas a las máquinas virtuales o ejecutar un servidor DHCP en una de ellas.<br />
<br />
De forma predeterminada, iptables eliminaría los paquetes de la red de bridge. Es posible que necesite utilizar dicha regla iptables para permitir paquetes en una red puenteada:<br />
<br />
# iptables -I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Redes puenteadas usando qemu-bridge-helper ====<br />
<br />
{{Note (Español)| Este método está disponible desde QEMU 1.1, consulte https://wiki.qemu.org/Features/HelperNetworking.}}<br />
<br />
Este método no requiere una secuencia de comandos de inicio y acepta fácilmente múltiples tomas y puentes múltiples. Utiliza el binario {{ic|/usr/lib/qemu/qemu-bridge-helper}}, que permite crear dispositivos de derivación en un puente existente.<br />
<br />
{{Tip (Español)|Véase [[Network bridge]] para obtener información sobre cómo crear un puente.}}<br />
<br />
En primer lugar, cree un archivo de configuración que contenga los nombres de todos los puentes que QEMU utilizará:<br />
<br />
{{hc|/etc/qemu/bridge.conf|<br />
allow ''bridge0''<br />
allow ''bridge1''<br />
...}}<br />
<br />
Ahora inicie la VM. El uso más básico sería:<br />
<br />
$ qemu-system-i386 -net nic -net bridge,br=''bridge0'' ''[...]''<br />
<br />
Con múltiples taps, el uso más básico requiere especificar la VLAN para todos los NIC adicionales:<br />
<br />
$ qemu-system-i386 -net nic -net bridge,br=''bridge0'' -net nic,vlan=1 -net bridge,vlan=1,br=''bridge1'' ''[...]''<br />
<br />
==== Creación manual del puente ====<br />
<br />
{{Tip (Español)|Desde QEMU 1.1, el [https://wiki.qemu.org/Features/HelperNetworking puente de red ayudante] puede establecer tun / tap up para usted sin necesidad de secuencias de comandos adicionales. Consulte [[#Redes puenteadas usando qemu-bridge-helper]].}}<br />
<br />
A continuación se describe cómo conectar una máquina virtual con una interfaz de host como {{ic | eth0}}, que es probablemente la configuración más común. Esta configuración hace que parezca que la máquina virtual está ubicada directamente en la red externa, en el mismo segmento Ethernet que la máquina host física.<br />
<br />
Vamos a reemplazar el adaptador Ethernet normal con un adaptador de puente y enlazar el adaptador Ethernet normal a él.<br />
<br />
* Instale {{Pkg|bridge-utils}}, que proporciona {{ic|brctl}} para manipular puentes.<br />
<br />
* Habilitar el reenvío IPv4:<br />
<br />
# sysctl net.ipv4.ip_forward=1<br />
<br />
Para hacer el cambio permanente, cambie {{ic|1=net.ipv4.ip_forward = 0}} a {{ic|1=net.ipv4.ip_forward = 1}} en {{ic|/etc/sysctl.d/99-sysctl.conf}}.<br />
<br />
* Cargue el módulo {{ic|tun}} y configurelo para cargarlo en el arranque. Véase [[Kernel modules (Español)]] para más detalles.<br />
<br />
* Ahora cree el puente. Ver [[Bridge with netctl]] para más detalles. Recuerde nombrar su puente como {{ic|br0}}, o modifique lo scripts a continuación del nombre del puente.<br />
<br />
* Cree el script que QEMU utiliza para abrir el adaptador de toma con los permisos {{ic|root:kvm}} 750:<br />
{{hc|/etc/qemu-ifup|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifup"<br />
echo "Bringing up $1 for bridged mode..."<br />
sudo /usr/bin/ip link set $1 up promisc on<br />
echo "Adding $1 to br0..."<br />
sudo /usr/bin/brctl addif br0 $1<br />
sleep 2<br />
</nowiki>}}<br />
<br />
* Cree el guión que QEMU utiliza para derribar el adaptador de toma en {{ic|/etc/qemu-ifdown}} con los permisos {{ic|root:kvm}} 750:<br />
{{hc|/etc/qemu-ifdown|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifdown"<br />
sudo /usr/bin/ip link set $1 down<br />
sudo /usr/bin/brctl delif br0 $1<br />
sudo /usr/bin/ip link delete dev $1<br />
</nowiki>}}<br />
<br />
* Use {{ic|visudo}} para añadir lo siguiente a el archivo {{ic|sudoers}}:<br />
{{bc|<nowiki><br />
Cmnd_Alias QEMU=/usr/bin/ip,/usr/bin/modprobe,/usr/bin/brctl<br />
%kvm ALL=NOPASSWD: QEMU<br />
</nowiki>}}<br />
<br />
* Se inicia QEMU con el siguiente script {{ic|run-qemu}}:<br />
{{hc|run-qemu|<nowiki><br />
#!/bin/bash<br />
USERID=$(whoami)<br />
<br />
# Get name of newly created TAP device; see https://bbs.archlinux.org/viewtopic.php?pid=1285079#p1285079<br />
precreationg=$(/usr/bin/ip tuntap list | /usr/bin/cut -d: -f1 | /usr/bin/sort)<br />
sudo /usr/bin/ip tuntap add user $USERID mode tap<br />
postcreation=$(/usr/bin/ip tuntap list | /usr/bin/cut -d: -f1 | /usr/bin/sort)<br />
IFACE=$(comm -13 <(echo "$precreationg") <(echo "$postcreation"))<br />
<br />
# This line creates a random MAC address. The downside is the DHCP server will assign a different IP address each time<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
# Instead, uncomment and edit this line to set a static MAC address. The benefit is that the DHCP server will assign the same IP address.<br />
# macaddr='52:54:be:36:42:a9'<br />
<br />
qemu-system-i386 -net nic,macaddr=$macaddr -net tap,ifname="$IFACE" $*<br />
<br />
sudo ip link set dev $IFACE down &> /dev/null<br />
sudo ip tuntap del $IFACE mode tap &> /dev/null<br />
</nowiki>}}<br />
<br />
Para ejecutar una VM, haz algo como esto:<br />
<br />
$ run-qemu -hda ''myvm.img'' -m 512 -vga std<br />
<br />
* Se recomienda, por motivos de rendimiento y seguridad, deshabilitar el firewall [http://ebtables.netfilter.org/documentation/bridge-nf.html en el puente]:<br />
{{hc|/etc/sysctl.d/10-disable-firewall-on-bridge.conf|<nowiki><br />
net.bridge.bridge-nf-call-ip6tables = 0<br />
net.bridge.bridge-nf-call-iptables = 0<br />
net.bridge.bridge-nf-call-arptables = 0<br />
</nowiki>}}<br />
Ejecute {{ic|sysctl -p /etc/sysctl.d/10-disable-firewall-on-bridge.conf}} para aplicar los cambios inmediatamente.<br />
<br />
Ver [https://wiki.libvirt.org/page/Networking#Creating_network_initscripts libvirt wiki] y [https://bugzilla.redhat.com/show_bug.cgi?id=512206 Fedora bug 512206]. Si obtiene errores de sysctl durante el inicio de archivos no existentes, haga que el módulo {{ic|bridge}} se cargue al arrancar. Véase [[Kernel module (Español)#systemd]].<br />
<br />
Como alternativa, puede configurar [[iptables]] para permitir que todo el tráfico se reenvíe a través del puente mediante la adición de una regla como esta:<br />
<br />
-I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Compartición de red entre dispositivo físico y un dispositivo de toque a través de iptables ====<br />
<br />
La conexión en puente funciona bien entre una interfaz cableada (por ejemplo, eth0), y es fácil de configurar. Sin embargo, si el host se conecta a la red a través de un dispositivo inalámbrico, el puente no es posible.<br />
<br />
Consulte [[Network bridge#Wireless interface on a bridge]] como referencia.<br />
<br />
Una forma de superar esto es configurar un dispositivo de derivación con una IP estática, haciendo que linux maneje automáticamente el enrutamiento para ella y, a continuación, reenvíe el tráfico entre la interfaz de derivación y el dispositivo conectado a la red a través de las reglas de iptables.<br />
<br />
Consulte [[Internet sharing]] como referencia.<br />
<br />
Allí puede encontrar lo que se necesita para compartir la red entre dispositivos, incluidos los de tap y tun. Lo siguiente sólo indica algunas de las configuraciones de host requeridas. Como se indica en la referencia anterior, el cliente debe configurarse para una IP estática, utilizando la IP asignada a la interfaz de derivación como puerta de enlace. La advertencia es que los servidores DNS del cliente pueden necesitar ser editados manualmente si cambian al cambiar de un dispositivo host conectado a la red a otro.<br />
<br />
Para permitir el reenvío de IP en cada inicio, es necesario agregar las siguientes líneas al archivo de configuración de sysctl dentro de /etc/sysctl.d:<br />
<br />
net.ipv4.ip_forward = 1<br />
net.ipv6.conf.default.forwarding = 1<br />
net.ipv6.conf.all.forwarding = 1<br />
<br />
Las reglas de iptables pueden verse así:<br />
<br />
# Forwarding from/to outside<br />
iptables -A FORWARD -i ${INT} -o ${EXT_0} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_1} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_2} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_0} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_1} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_2} -o ${INT} -j ACCEPT<br />
# NAT/Masquerade (network address translation)<br />
iptables -t nat -A POSTROUTING -o ${EXT_0} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_1} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_2} -j MASQUERADE<br />
<br />
El anterior supone que hay 3 dispositivos conectados a la red compartiendo tráfico con un dispositivo interno, donde por ejemplo:<br />
<br />
INT=tap0<br />
EXT_0=eth0<br />
EXT_1=wlan0<br />
EXT_2=tun0<br />
<br />
El anterior muestra un reenvío que permitiría compartir conexiones cableadas e inalámbricas con el dispositivo de derivación (tap).<br />
<br />
Las reglas de reenvío que se muestran son apátridas y para el reenvío puro. Se podría pensar en restringir el tráfico específico, poniendo un cortafuegos en el lugar para proteger al huésped y otros. Sin embargo, esto reduciría el rendimiento de la red, mientras que un simple puente no incluye nada de eso.<br />
<br />
Bonus: Si la conexión es cableada o inalámbrica, si se conecta a través de VPN a un sitio remoto con un dispositivo tun, suponiendo que el dispositivo tun abierto para esa conexión es tun0, y las reglas iptables anteriores se aplican, entonces la conexión remota se obtiene también Compartido con el huésped. Esto evita la necesidad de que el invitado también abra una conexión VPN. Una vez más, como la red de invitados debe ser estática, entonces si la conexión del host de forma remota de esta manera, uno probablemente tendrá que editar los servidores DNS en el invitado.<br />
<br />
=== Trabajo en red con VDE2 ===<br />
<br />
==== ¿Qué es VDE? ====<br />
<br />
VDE significa Virtual Distributed Ethernet. Comenzó como una mejora del interruptor [[User-mode Linux|uml]] _. Es una caja de herramientas para administrar redes virtuales.<br />
<br />
La idea es crear interruptores virtuales, que son básicamente sockets, y "conectar" tanto máquinas físicas como máquinas virtuales en ellas. La configuración que mostramos aquí es bastante simple; Sin embargo, VDE es mucho más potente que esto, puede conectar conmutadores virtuales juntos, ejecutarlos en diferentes hosts y supervisar el tráfico en los switches. Usted está invitado a leer [https://web.archive.org/web/20190821040940/http://wiki.virtualsquare.org/wiki/index.php/Main_Page la documentación del proyecto].<br />
<br />
La ventaja de este método es que no tienes que agregar privilegios de sudo a tus usuarios. No se debe permitir que los usuarios regulares ejecuten modprobe.<br />
<br />
==== Basics ====<br />
<br />
El soporte de VDE puede ser [[pacman|instalado]] a través del paquete {{Pkg|vde2}} en los [[repositorios oficiales]].<br />
<br />
En nuestra configuración, usamos tun/tap para crear una interfaz virtual en el host. Cargue el módulo {{ic|tun}} (véase [[kernel modules (Español)]] para obtener más detalles):<br />
<br />
# modprobe tun<br />
<br />
Ahora crea el conmutador virtual:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
<br />
Esta línea crea el switch, crea {{ic|tap0}}, lo "enchufa" y permite a los usuarios del grupo {{ic|users}} usarlo.<br />
<br />
La interfaz está conectada pero no está configurada todavía. Para configurarlo, ejecute este comando:<br />
<br />
# ip addr add 192.168.100.254/24 dev tap0<br />
<br />
Ahora, sólo tiene que ejecutar KVM con estas opciones {{ic|-net}} como usuario normal:<br />
<br />
$ qemu-system-i386 -net nic -net vde -hda ''[...]''<br />
<br />
Configure la red para su invitado como lo haría en una red física.<br />
<br />
{{Tip (Español)|Es posible que desee configurar NAT en dispositivo de toque para acceder a Internet desde la máquina virtual. Consulte [[Internet sharing#Enable NAT]] para obtener más información.}}<br />
<br />
==== Startup scripts ====<br />
<br />
Ejemplo de script principal que inicia VDE:<br />
<br />
{{hc|/etc/systemd/scripts/qemu-network-env|<nowiki><br />
#!/bin/sh<br />
# Preparación del entorno de red QEMU/VDE<br />
<br />
# La configuración IP del dispositivo de derivación que se utilizará para<br />
# La red de la máquina virtual:<br />
<br />
TAP_DEV=tap0<br />
TAP_IP=192.168.100.254<br />
TAP_MASK=24<br />
TAP_NETWORK=192.168.100.0<br />
<br />
# Host interface<br />
NIC=eth0<br />
<br />
case "$1" in<br />
start)<br />
echo -n "Starting VDE network for QEMU: "<br />
<br />
# If you want tun kernel module to be loaded by script uncomment here<br />
#modprobe tun 2>/dev/null<br />
## Wait for the module to be loaded<br />
#while ! lsmod | grep -q "^tun"; do echo "Waiting for tun device"; sleep 1; done<br />
<br />
# Start tap switch<br />
vde_switch -tap "$TAP_DEV" -daemon -mod 660 -group users<br />
<br />
# Bring tap interface up<br />
ip address add "$TAP_IP"/"$TAP_MASK" dev "$TAP_DEV"<br />
ip link set "$TAP_DEV" up<br />
<br />
# Start IP Forwarding<br />
echo "1" > /proc/sys/net/ipv4/ip_forward<br />
iptables -t nat -A POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
;;<br />
stop)<br />
echo -n "Stopping VDE network for QEMU: "<br />
# Delete the NAT rules<br />
iptables -t nat -D POSTROUTING "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
<br />
# Bring tap interface down<br />
ip link set "$TAP_DEV" down<br />
<br />
# Kill VDE switch<br />
pgrep -f vde_switch | xargs kill -TERM<br />
;;<br />
restart|reload)<br />
$0 stop<br />
sleep 1<br />
$0 start<br />
;;<br />
*)<br />
echo "Usage: $0 {start|stop|restart|reload}"<br />
exit 1<br />
esac<br />
exit 0<br />
</nowiki>}}<br />
<br />
Ejemplo de servicio systemd utilizando el script anterior:<br />
<br />
{{hc|/etc/systemd/system/qemu-network-env.service|<nowiki><br />
[Unit]<br />
Description=Manage VDE Switch<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/etc/systemd/scripts/qemu-network-env start<br />
ExecStop=/etc/systemd/scripts/qemu-network-env stop<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
Cambiar permisos de {{ic|qemu-network-env}} para ser ejecutable<br />
<br />
# chmod u+x /etc/systemd/scripts/qemu-network-env<br />
<br />
Puede iniciar {{ic|qemu-network-env.service}} como de costumbre.<br />
<br />
==== Método alternativo ====<br />
<br />
Si el método anterior no funciona o no quiere meterse con las configuraciones del kernel, TUN, dnsmasq e iptables, puede hacer lo siguiente para obtener el mismo resultado.<br />
<br />
# vde_switch -daemon -mod 660 -group users<br />
# slirpvde --dhcp --daemon<br />
<br />
A continuación, para iniciar la VM con una conexión a la red del host:<br />
<br />
$ qemu-system-i386 -net nic,macaddr=52:54:00:00:EE:03 -net vde ''disk_image''<br />
<br />
=== Puente VDE2 ===<br />
<br />
Basado en [https://selamatpagicikgu.wordpress.com/2011/06/08/quickhowto-qemu-networking-using-vde-tuntap-and-bridge/ quickhowto: qemu networking using vde, tun/tap, and bridge] gráfico. Cualquier máquina virtual conectada a vde está expuesta externamente. Por ejemplo, cada máquina virtual puede recibir la configuración DHCP directamente desde su enrutador ADSL.<br />
<br />
==== Conceptos básicos ====<br />
<br />
Recuerde que necesita el módulo {{ic|tun}} y el paquete {{Pkg|bridge-utils}}.<br />
<br />
Cree el dispositivo vde2/tap:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
# ip link set tap0 up<br />
<br />
Cree el puente:<br />
<br />
# brctl addbr br0<br />
<br />
Agregue dispositivos:<br />
<br />
# brctl addif br0 eth0<br />
# brctl addif br0 tap0<br />
<br />
Y configure la interfaz del puente:<br />
<br />
# dhcpcd br0<br />
<br />
==== Startup scripts ====<br />
<br />
Todos los dispositivos deben estar configurados. Y sólo el puente necesita una dirección IP. Para dispositivos físicos en el puente (por ejemplo, {{ic|eth0}}), esto puede hacerse con [[netctl]] utilizando un perfil Ethernet personalizado con:<br />
<br />
{{hc|/etc/netctl/ethernet-noip|<nowiki><br />
Description='A more versatile static Ethernet connection'<br />
Interface=eth0<br />
Connection=ethernet<br />
IP=no<br />
</nowiki>}}<br />
<br />
El siguiente servicio systemd personalizado puede utilizarse para crear y activar una interfaz de toma VDE2 para su uso en el grupo de usuarios {{ic|users}}.<br />
<br />
{{hc|/etc/systemd/system/vde2@.service|<nowiki><br />
[Unit]<br />
Description=Network Connectivity for %i<br />
Wants=network.target<br />
Before=network.target<br />
<br />
[Service]<br />
Type=oneshot<br />
RemainAfterExit=yes<br />
ExecStart=/usr/bin/vde_switch -tap %i -daemon -mod 660 -group users<br />
ExecStart=/usr/bin/ip link set dev %i up<br />
ExecStop=/usr/bin/ip addr flush dev %i<br />
ExecStop=/usr/bin/ip link set dev %i down<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
Y, por último, puede crear el puente interfaz con netctl.<br />
<br />
== Gráficos ==<br />
<br />
QEMU puede utilizar las siguientes salidas gráficas diferentes: {{ic|std}}, {{ic|qxl}}, {{ic|vmware}}, {{ic|virtio}}, {{ic|cirrus}} y {{ic|none}}.<br />
<br />
=== std ===<br />
<br />
Con {{ic|-vga std}} puede obtener una resolución de hasta 2560 x 1600 píxeles sin necesidad de controladores invitados. Este es el valor predeterminado desde QEMU 2.2.<br />
<br />
=== qxl ===<br />
<br />
QXL Es un controlador de gráficos paravirtual con soporte 2D. Para usarlo, pase la opción {{ic|-vga qxl}} e instale los controladores en el invitado. Es posible que desee utilizar SPICE para mejorar el rendimiento gráfico al utilizar QXL.<br />
<br />
En los invitados de Linux, los módulos del kernel {{ic|qxl}} y {{ic|bochs_drm}} deben ser inicializados para poder tener un rendimiento decente.<br />
<br />
==== SPICE ====<br />
<br />
El proyecto [https://www.spice-space.org/ SPICE] tiene como objetivo proporcionar una solución completa de código abierto para el acceso remoto a máquinas virtuales de una manera transparente.<br />
<br />
SPICE sólo se puede utilizar cuando se utiliza QXL como la salida gráfica.<br />
<br />
El siguiente es un ejemplo de arranque con SPICE como protocolo de escritorio remoto:<br />
<br />
$ qemu-system-i386 -vga qxl -spice port=5930,disable-ticketing -chardev spicevm <br />
<br />
Conéctese al invitado utilizando un cliente SPICE. En este momento se recomienda {{Pkg|spice-gtk}}, sin embargo otros [https://www.spice-space.org/download.html clientes], incluyendo otras plataformas, están disponibles:<br />
<br />
$ spicy -h 127.0.0.1 -p 5930<br />
<br />
El uso de [[wikipedia:Unix_socket|Unix sockets]] en lugar de los puertos TCP no implica el uso de pila de red en el sistema host, por lo que es [https://unix.stackexchange.com/questions/91774/performance-of-unix- Sockets-vs-tcp-ports según se informa] mejor para el rendimiento. Ejemplo:<br />
$ qemu-system-x86_64 -vga qxl -device virtio-serial-pci -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent -spice unix,addr=/tmp/vm_spice.socket,disable-ticketing<br />
$ spicy --uri="spice+unix:///tmp/vm_spice.socket"<br />
<br />
Para una mejor compatibilidad con varios monitores, compartir el portapapeles, etc., los paquetes siguientes deben estar instalados en el invitado:<br />
* {{Pkg|spice-vdagent}}: Spice agent xorg cliente que permite copiar y pegar entre el cliente y X-session y más<br />
* {{Pkg|xf86-video-qxl}} {{AUR|xf86-video-qxl-git}}: Xorg X11 qxl controlador de vídeo<br />
* Para otros sistemas operativos, mire la sección Guest de la página [https://www.spice-space.org/download.html SPICE-Space download].<br />
<br />
=== vmware ===<br />
<br />
Aunque tiene pocos errores, tiene mejor rendimiento que std y cirrus. Instale los controladores de VMware {{Pkg|xf86-video-vmware}} y {{Pkg|xf86-input-vmmouse}} para los invitados de Arch Linux.<br />
<br />
=== virtio ===<br />
<br />
{{ic|virtio-vga}} / {{ic|virtio-gpu}} Es un controlador de gráficos 3D paravirtual basado en [https://virgil3d.github.io/ virgl]. Actualmente un trabajo en curso, que sólo admite a invitados Linux (>= 4.4) con {{Pkg|mesa}} (>= 11.2) compilados con la opción {{ic|1=--with-gallium-drivers=virgl}}.<br />
<br />
Para activar la aceleración 3D en el sistema invitado, seleccione vga con {{ic|-vga virtio}} y habilitar el contexto opengl en el dispositivo de visualización con {{ic|1=-display sdl,gl=on}} ó {{ic|1=-display gtk,gl=on}} Para la salida de pantalla sdl y gtk respectivamente. La configuración correcta se puede confirmar mirando el registro del kernel en el invitado:<br />
<br />
{{hc|# dmesg {{!}} grep drm |<br />
[drm] pci: virtio-vga detected<br />
[drm] virgl 3d acceleration enabled<br />
}}<br />
<br />
A partir de septiembre de 2016, el soporte para el protocolo de especias está en desarrollo y se puede probar la instalación de la versión de desarrollo de {{Pkg|spice}} (>= 0.13.2) y la recompilación de qemu.<br />
<br />
Para más información visite [https://web.archive.org/web/20171216170334/https://www.kraxel.org/blog/tag/virgl/ blog de kraxel].<br />
<br />
=== cirrus ===<br />
<br />
El adaptador gráfico cirrus fue el predeterminado [https://wiki.qemu.org/ChangeLog/2.2#VGA before 2.2]. [Https://www.kraxel.org/blog/2014/10/qemu-using-cirrus-considered-harmful/ no debería] utilizarse en sistemas modernos.<br />
<br />
=== none ===<br />
<br />
Esto es como un PC que no tiene tarjeta VGA en absoluto. Ni siquiera podrías acceder a ella con la opción {{ic|-vnc}}. Además, esto es diferente de la opción {{ic|-nographic}} que permite a QEMU emular una tarjeta VGA, pero deshabilita la visualización SDL.<br />
<br />
=== vnc ===<br />
<br />
Dado que usó la opción {{ic|-nographic}}, puede agregar la opción {{ic|-vnc display}} para que QEMU escuche en {{ic|display}} y redirigir la pantalla VGA a la sesión VNC . Hay un ejemplo de esto en las configuraciones de ejemplo de la sección [[#Inicio de las máquinas virtuales QEMU en el arranque]].<br />
<br />
$ qemu-system-i386 -vga std -nographic -vnc :0<br />
$ gvncviewer :0<br />
<br />
Al usar VNC, puede experimentar problemas de teclado descritos (en detalles gory) [https://www.berrange.com/posts/2010/07/04/more-than-you-or-i-ever-wanted-to-know-about-virtual-keyboard-handling/ aquí]. La solución es "no" usar la opción {{ic|-k}} en QEMU y usar {{ic|gvncviewer}} de {{Pkg|gtk-vnc}}. Ver también [https://www.mail-archive.com/libvir-list@redhat.com/msg13340.html este] mensaje publicado en la lista de correo de libvirt.<br />
<br />
== Audio ==<br />
<br />
=== Host ===<br />
<br />
El controlador de audio utilizado por QEMU se establece con la variable de entorno {{ic|QEMU_AUDIO_DRV}}:<br />
<br />
$ export QEMU_AUDIO_DRV=pa<br />
<br />
Ejecute el siguiente comando para obtener las opciones de configuración de QEMU relacionadas con PulseAudio:<br />
<br />
$ qemu-system-x86_64 -audio-help | awk '/Name: pa/' RS=<br />
<br />
Las opciones listadas se pueden exportar como variables de entorno, por ejemplo:<br />
<br />
{{bc|1=<br />
$ export QEMU_PA_SINK=alsa_output.pci-0000_04_01.0.analog-stereo.monitor<br />
$ export QEMU_PA_SOURCE=input<br />
}}<br />
<br />
=== Invitado ===<br />
<br />
Para obtener la lista de los controladores de audio de emulación compatibles:<br />
<br />
$ qemu-system-x86_64 -soundhw help<br />
<br />
Para usar (ej. {{ic|hda}}) para el invitado utilice el comando {{ic|-soundhw hda}} con QEMU.<br />
<br />
{{Note (Español)| Los controladores emulados con tarjeta gráfica de vídeo para la máquina invitada también pueden causar un problema con la calidad del sonido. Pruebe uno por uno para que funcione. Puede listar las opciones posibles con {{ic|qemu-system-x86_64 -h | grep vga}}.}}<br />
<br />
==== VirtIO sound ====<br />
<br />
VirtIO sound está disponible desde la versión QEMU 8.2.0. El uso es:<br />
<br />
-device virtio-sound-pci,audiodev=my_audiodev -audiodev alsa,id=my_audiodev<br />
<br />
Más información puede ser encontrada en [https://qemu-project.gitlab.io/qemu/system/devices/virtio-snd.html documentación QEMU].<br />
<br />
== Instalación de controladores virtio ==<br />
<br />
QEMU ofrece a los clientes la posibilidad de utilizar dispositivos bloqueados y de red paravirtualizados utilizando los controladores [https://wiki.libvirt.org/page/Virtio virtio], que proporcionan un mejor rendimiento y menores gastos generales.<br />
<br />
Un dispositivo virtio bloque requiere la opción {{ic|-drive}} en lugar del simple {{ic|-hd *}} más {{ic|1=if=virtio}}:<br />
<br />
$ qemu-system-i386 -boot order=c -drive file=''disk_image'',if=virtio<br />
<br />
{{Note (Español)|{{Ic|1=-boot order=c}} es absolutamente necesario cuando se desea arrancar desde él. No hay detección automática como con {{Ic|-hd*}}.}}<br />
<br />
* Casi de la misma manera para la red:<br />
<br />
$ qemu-system-i386 -net nic,model=virtio<br />
<br />
{{Note (Español)| Esto sólo funcionará si la máquina invitada tiene controladores para dispositivos virtio. Linux lo hace, y los controladores necesarios están incluidos en Arch Linux, pero no hay garantía de que los dispositivos virtio funcionen con otros sistemas operativos.}}<br />
<br />
=== Preparando a Arch Linux como invitado ===<br />
<br />
Para utilizar los dispositivos virtio después de instalar un invitado de Arch Linux, se deben cargar en el invitado los siguientes módulos: {{Ic|virtio}}, {{Ic|virtio_pci}}, {{Ic|virtio_blk}}, {{Ic|Virtio_net}}, y {{Ic|virtio_ring}}. Para los huéspedes de 32 bits, no es necesario el módulo "virtio" específico.<br />
<br />
Si desea arrancar desde un disco virtio, el disco ramd inicial debe contener los módulos necesarios. De forma predeterminada, esto es manejado por el gancho {{ic|autodetect}} de [[mkinitcpio]]. De lo contrario, utilice la matriz {{ic|MODULES}} en {{ic|/etc/mkinitcpio.conf}} para incluir los módulos necesarios y reconstruir el disco ramd inicial.<br />
<br />
{{hc|/etc/mkinitcpio.conf|2=<br />
MODULES="virtio virtio_blk virtio_pci virtio_net"}}<br />
<br />
Los discos Virtio se reconocen con el prefijo {{ic|'''v'''}} (ej. {{ic|'''v''' da}}, {{ic|'''v''' db}}, etc.); Por lo tanto, los cambios deben realizarse al menos en {{ic|/etc/fstab}} y {{ic|/boot/grub/grub.cfg}} al arrancar desde un disco virtio.<br />
<br />
{{Note (Español)|Cuando se hace referencia a discos por [[UUID]] en {{ic|/etc/fstab}} y bootloader, no hay nada que hacer.}}<br />
<br />
Se puede encontrar más información sobre la paravirtualización con KVM [https://www.linux-kvm.org/page/Boot_from_virtio_block_device aquí].<br />
<br />
También puede instalar {{Pkg|qemu-guest-agent}} para implementar la compatibilidad con los comandos QMP que mejorarán las capacidades de administración del hipervisor. Después de instalar el paquete, puedes habilitar e iniciar el {{ic|qemu-ga.service}}.<br />
<br />
=== Preparar un invitado de Windows ===<br />
<br />
{{Note (Español)|1=La única forma (fiable) de actualizar un cliente de Windows 8.1 a Windows 10 parece que es elegir temporalmente cpu core2duo, nx para la instalación [https://ubuntuforums.org/showthread.php?t=2289210]. Después de la instalación, puede volver a otros ajustes de la CPU (8/8/2015).}}<br />
<br />
==== Bloquear controladores de dispositivo ====<br />
<br />
===== Nueva instalación de Windows =====<br />
<br />
Windows no viene con los controladores virtio. Por lo tanto, tendrá que cargarlos durante la instalación. Hay básicamente dos maneras de hacer esto: vía disco blando o vía archivos de ISO. Ambas imágenes se pueden descargar desde el repositorio [https://fedoraproject.org/wiki/Windows_Virtio_Drivers Fedora].<br />
<br />
La opción del disquete es difícil porque necesitará presionar F6 (Shift-F6 en Windows más reciente) al inicio de la alimentación del QEMU. Esto es difícil ya que necesitas tiempo para conectar tu ventana de consola VNC. Puede intentar agregar un retardo a la secuencia de arranque. Consulte {{ic|man qemu-system}} para obtener más detalles sobre la aplicación de un retardo en el arranque.<br />
<br />
La opción ISO para cargar los controladores es la forma preferida, pero está disponible sólo en Windows Vista y Windows Server 2008 y versiones posteriores. El procedimiento consiste en cargar la imagen con controladores virtio en un dispositivo de cdrom adicional junto con el dispositivo de disco principal y el instalador de Windows:<br />
<br />
$ qemu-system-i386 ... \<br />
-drive file=''/path/to/primary/disk.img'',index=0,media=disk,if=virtio \<br />
-drive file=''/path/to/installer.iso'',index=2,media=cdrom \<br />
-drive file=''/path/to/virtio.iso'',index=3,media=cdrom \<br />
...<br />
<br />
Durante la instalación, el instalador de Windows le pedirá su clave de producto y realizará algunas comprobaciones adicionales. Cuando llegue a la "¿Dónde desea instalar Windows?" Pantalla, dará una advertencia de que no se encuentran discos. Siga las instrucciones de ejemplo siguientes (basadas en Windows Server 2012 R2 con Actualización).<br />
<br />
* Seleccione la opción {{ic|Load Drivers}}.<br />
* Desactive la casilla de "Ocultar los controladores que no son compatibles con el hardware de este equipo".<br />
* Haga clic en el botón Examinar y abra el CDROM para la virtio iso, normalmente llamada "virtio-win-XX".<br />
* Ahora vaya a {{ic|E:\viostor\[your-os]\amd64}}, seleccione y pulse OK.<br />
* Click Next<br />
<br />
Ahora debería ver sus discos virtio listados aquí, listos para ser seleccionados, formateados e instalados.<br />
<br />
===== Cambiar la máquina virtual existente de Windows para utilizar virtio =====<br />
<br />
Modificar un invitado de Windows existente para arrancar desde disco virtio es un poco difícil.<br />
<br />
Puede descargar el controlador de disco virtio desde el [https://fedoraproject.org/wiki/Windows_Virtio_Drivers repositorio de Fedora].<br />
<br />
Ahora necesita crear una nueva imagen de disco, que llene la fuerza de Windows para buscar el controlador. Por ejemplo:<br />
<br />
$ qemu-img create -f qcow2 ''fake.qcow2'' 1G<br />
<br />
Ejecute el invitado original de Windows (con el disco de inicio todavía en modo IDE) con el disco falso (en modo virtio) y un CD-ROM con el controlador.<br />
<br />
$ qemu-system-i386 -m 512 -vga std -drive file=''windows_disk_image'',if=ide -drive file=''fake.qcow2'',if=virtio -cdrom virtio-win-0.1-81.iso<br />
<br />
Windows detectará el disco falso y tratará de encontrar un controlador para ello. Si falla, vaya al '' Administrador de dispositivos '', busque la unidad SCSI con un icono de signo de exclamación (debe estar abierto), haga clic en '' Actualizar controlador '' y seleccione el CD-ROM virtual. No olvide seleccionar la casilla de verificación que dice que debe buscar directorios recursivamente.<br />
<br />
Cuando la instalación se realiza correctamente, puede apagar la máquina virtual y volver a iniciarla, ahora con el disco de arranque conectado en modo virtio:<br />
<br />
$ qemu-system-i386 -m 512 -vga std -drive file=''windows_disk_image'',if=virtio<br />
<br />
{{Note (Español)|Si encuentra la pantalla azul de Death, asegúrese de no olvidar el parámetro {{ic|-m}} y de que no arranca con virtio en lugar de ide para la unidad del sistema antes de instalar los controladores.}}<br />
<br />
==== Controladores de red ====<br />
<br />
La instalación de los controladores de red virtio es un poco más fácil, simplemente agregue el argumento {{ic|-net}} como se explicó anteriormente.<br />
<br />
$ qemu-system-i386 -m 512 -vga std -drive file=''windows_disk_image'',if=virtio -net nic,model=virtio -cdrom virtio-win-0.1-74.iso<br />
<br />
Windows detectará el adaptador de red y tratará de encontrar un controlador para ello. Si falla, vaya al ''Administrador de dispositivos'', localice el adaptador de red con un icono de signo de exclamación (debe estar abierto), haga clic en ''Actualizar controlador'' y seleccione el CD-ROM virtual. No olvide seleccionar la casilla de verificación que dice que debe buscar directorios recursivamente.<br />
<br />
=== Preparación de FreeBSD como invitado ===<br />
<br />
Instale el puerto {{ic|emulators/virtio-kmod}} si está utilizando FreeBSD 8.3 o posterior hasta 10.0-CURRENT donde están incluidos en el kernel. Después de la instalación, añada lo siguiente a su archivo {{ic|/boot/loader.conf}}:<br />
<br />
{{bc|<nowiki><br />
virtio_loader="YES"<br />
virtio_pci_load="YES"<br />
virtio_blk_load="YES"<br />
if_vtnet_load="YES"<br />
virtio_balloon_load="YES"<br />
</nowiki>}}<br />
<br />
A continuación, modifique su {{ic|/etc/fstab}} haciendo lo siguiente:<br />
<br />
{{bc|<nowiki><br />
sed -i bak "s/ada/vtbd/g" /etc/fstab<br />
</nowiki>}}<br />
<br />
Y verificar que {{ic|/etc/fstab}} es consistente. Si algo sale mal, sólo arranque en un CD de rescate y copie {{ic|/etc/fstab.bak}} de vuelta a {{ic|/etc/fstab}}.<br />
<br />
== Consejos y trucos ==<br />
<br />
=== Inicio de las máquinas virtuales QEMU en el arranque ===<br />
<br />
==== Con libvirt ====<br />
<br />
Si se configura una máquina virtual con [[libvirt]], se puede configurar a través de la interfaz gráfica de usuario de virt-manager para iniciar en el arranque de host, accediendo a las Opciones de arranque de la máquina virtual y seleccionando "Inicio de la máquina virtual en el arranque del host".<br />
<br />
==== Script personalizado ====<br />
<br />
Para ejecutar QEMU VMs al arrancar, puede usar las siguientes unidades systemd y config.<br />
<br />
{{hc|/etc/systemd/system/qemu@.service|<nowiki><br />
[Unit]<br />
Description=QEMU virtual machine<br />
<br />
[Service]<br />
Environment="type=system-x86_64" "haltcmd=kill -INT $MAINPID"<br />
EnvironmentFile=/etc/conf.d/qemu.d/%i<br />
ExecStart=/usr/bin/env qemu-${type} -name %i -nographic $args<br />
ExecStop=/bin/sh -c ${haltcmd}<br />
TimeoutStopSec=30<br />
KillMode=none<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
{{Note (Español)|De acuerdo con {{ic|systemd.service (5)}} y {{ic|systemd.kill (5)}} man, es necesario utilizar {{ic|1=KillMode=none}} opción. De lo contrario, el proceso qemu principal se eliminará inmediatamente después de que se cierre el comando {{ic|ExecStop}} (simplemente hace eco de una cadena) y su sistema de búsqueda no podrá apagarse correctamente.}}<br />
<br />
A continuación, cree archivos de configuración por-VM, denominados {{ic|/etc/conf.d/qemu.d/''vm_name''}}, con las siguientes variables establecidas:<br />
<br />
; type<br />
: QEMU binary to call. If specified, will be prepended with {{ic|/usr/bin/qemu-}} and that binary will be used to start the VM. I.e. you can boot e.g. {{ic|qemu-system-arm}} images with {{ic|1=type="system-arm"}}.<br />
; args<br />
: QEMU command line to start with. Will always be prepended with {{ic|-name ${vm} -nographic}}.<br />
; haltcmd<br />
: Command to shut down a VM safely. I am using {{ic|-monitor telnet:..}} and power off my VMs via ACPI by sending {{ic|system_powerdown}} to monitor. You can use SSH or some other ways.<br />
<br />
Ejemplo de configuración:<br />
<br />
{{hc|/etc/conf.d/qemu.d/one|<nowiki><br />
type="system-x86_64"<br />
<br />
args="-enable-kvm -m 512 -hda /dev/mapper/vg0-vm1 -net nic,macaddr=DE:AD:BE:EF:E0:00 \<br />
-net tap,ifname=tap0 -serial telnet:localhost:7000,server,nowait,nodelay \<br />
-monitor telnet:localhost:7100,server,nowait,nodelay -vnc :0"<br />
<br />
haltcmd="echo 'system_powerdown' | nc localhost 7100" # or netcat/ncat<br />
<br />
# You can use other ways to shut down your VM correctly<br />
#haltcmd="ssh powermanager@vm1 sudo poweroff"<br />
</nowiki>}}<br />
<br />
{{hc|/etc/conf.d/qemu.d/two|<nowiki><br />
args="-enable-kvm -m 512 -hda /srv/kvm/vm2.img -net nic,macaddr=DE:AD:BE:EF:E0:01 \<br />
-net tap,ifname=tap1 -serial telnet:localhost:7001,server,nowait,nodelay \<br />
-monitor telnet:localhost:7101,server,nowait,nodelay -vnc :1"<br />
<br />
haltcmd="echo 'system_powerdown' | nc localhost 7101"<br />
</nowiki>}}<br />
<br />
Para establecer qué máquinas virtuales se iniciarán al arrancar, habilite la unidad de [[systemd]] {{ic|qemu@''vm_name''.service}}.<br />
<br />
=== Integración del ratón ===<br />
<br />
Para evitar que el ratón sea agarrado al hacer clic en la ventana del sistema operativo invitado, agregue la opción {{ic|-usbdevice tablet}}. Esto significa que QEMU puede reportar la posición del ratón sin tener que agarrar el ratón. Esto también anula la emulación de ratón PS/2 cuando se activa. Por ejemplo:<br />
<br />
$ qemu-system-i386 -hda ''disk_image'' -m 512 -vga std -usbdevice tablet<br />
<br />
If that does not work, try the tip at [[#El cursor del ratón está nervioso o errático]].<br />
<br />
=== Dispositivo USB del host de paso ===<br />
<br />
Para acceder al dispositivo físico USB conectado al host desde la VM, puede utilizar la opción: {{ic|-usbdevice host:''vendor_id'':''product_id''}}.<br />
<br />
Puedes encontrar {{ic|vendor_id}} y {{ic|product_id}} de tu dispositivo con el comando {{ic|lsusb}}.<br />
<br />
Puesto que el chipset I440FX por defecto emulado por qemu cuentan con un solo controlador UHCI (USB 1), la opción {{ic|-usbdevice}} intentará conectar su dispositivo físico a él. En algunos casos esto puede causar problemas con los dispositivos más nuevos. Una posible solución es emular el chipset [https://wiki.qemu.org/Features/Q35 ICH9], que ofrece un controlador EHCI que soporta hasta 12 dispositivos, usando la opción {{ic|1=-machine type=q35}}.<br />
<br />
Una solución menos invasiva es emular un controlador EHCI (USB 2) o XHCI (USB 3) con la opción {{ic | 1 = -device usb-ehci, id = ehci}} o {{ic|1=-device nec -usb-xhci, id=xhci}} respectivamente y luego adjuntar su dispositivo físico con la opción {{ic|1=-device usb-host,..}} como sigue:<br />
<br />
-device usb-host,bus='''controller_id'''.0,vendorid=0x'''vendor_id''',productid=0x'''product_id'''<br />
<br />
También puede agregar la configuración {{ic|1=..., port =''<n>''}} a la opción anterior para especificar en qué puerto físico del controlador virtual que desea conectar su dispositivo, útil en El caso que desea agregar varios dispositivos usb a la VM.<br />
<br />
{{Note (Español)|Si encuentra errores de permisos al ejecutar QEMU, consulte [[udev#About udev rules]] para obtener información sobre cómo establecer permisos del dispositivo.}}<br />
<br />
=== Habilitar KSM ===<br />
<br />
Kernel Samepage Merging (KSM) es una característica del kernel de Linux que permite que una aplicación se registre con el kernel para que sus páginas se combinen con otros procesos que también se registren para que sus páginas se fusionen. El mecanismo KSM permite a las máquinas virtuales invitadas compartir páginas entre sí. En un entorno donde muchos de los sistemas operativos invitados son similares, esto puede resultar en ahorros significativos de memoria.<br />
<br />
Para activar KSM, simplemente ejecute:<br />
<br />
# echo 1 > /sys/kernel/mm/ksm/run<br />
<br />
Para hacerlo permanente, puede utilizar [[Systemd#systemd-tmpfiles - temporary files|archivos temporales de systemd]]:<br />
<br />
{{hc|/etc/tmpfiles.d/ksm.conf|<br />
w /sys/kernel/mm/ksm/run - - - - 1<br />
}}<br />
<br />
Si KSM está en ejecución y hay páginas que se van a fusionar (es decir, al menos dos máquinas virtuales similares se están ejecutando), entonces {{ic|/sys/kernel/mm/ksm/pages_shared}} debería ser distinto de cero. Consulte https://docs.kernel.org/vm/ksm.html{{Dead link (Español)|2022|09|22|status=404}} para obtener más información.<br />
<br />
{{Tip (Español)|Una manera fácil de ver lo bien que KSM está realizando es simplemente imprimir el contenido de todos los archivos de ese directorio: {{bc|$ grep./Sys/kernel/mm/ksm/*}}}}<br />
<br />
=== Multi-monitor support ===<br />
<br />
El controlador QXL de Linux soporta cuatro cabezas (pantallas virtuales) de forma predeterminada. Esto se puede cambiar a través del parámetro kernel {{ic | 1 = qxl.heads = N}}.<br />
<br />
El tamaño de memoria VGA predeterminado para los dispositivos QXL es de 16M (el tamaño de la VRAM es de 64M). Esto no es suficiente si desea habilitar dos monitores 1920x1200 ya que requiere 2 × 1920 × 4 (profundidad de color) × 1200 = 17.6 MiB memoria VGA. Esto se puede cambiar reemplazando {{ic|-vga qxl}} por {{ic|1=-vga none -device qxl-vga, vgamem_mb=32}}. Si alguna vez incrementas vgamem_mb más allá de 64M, también debes aumentar la opción {{ic|vram_size_mb}}.<br />
<br />
=== Copiar y pegar ===<br />
<br />
Para poder copiar y pegar entre el host y el invitado, debe habilitar el canal de comunicación del agente de especias. Requiere agregar un dispositivo virtio-serial al huésped, y abrir un puerto para el vdagent de la especia. También es necesario instalar el spice vdagent en invitado ({{Pkg|spice-vdagent}} para invitados de Arch, [https://www.spice-space.org/download.html Herramientas para invitados de Windows] para invitados de Windows). Asegúrese de que el agente se está ejecutando (y para el futuro, se iniciará automáticamente).<br />
<br />
Inicie QEMU con las siguientes opciones:<br />
<br />
$ qemu-system-i386 -vga qxl -spice port=5930,disable-ticketing -device virtio-serial-pci -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
La opción {{ic|-device virtio-serial-pci}} añade el dispositivo virtio-serial, {{ic|1=-device virtserialport, chardev=spicechannel0, nombre=com.redhat.spice.0}} abre un puerto Para spice vdagent en ese dispositivo y {{ic|1=-chardev spicevmc, id=spicechannel0, nombre=vdagent}} añade un spicevmc chardev para ese puerto.<br />
<br />
Es importante que la opción {{ic|1=chardev=}} del dispositivo {{ic|virtserialport}} coincida con la opción {{ic|1=id=}} dada a la opción {{ic | chardev}} ({{Ic|spicechannel0}} en este ejemplo). También es importante que el nombre del puerto sea {{ic|com.redhat.spice.0}}, ya que es el espacio de nombres donde vdagent está buscando en el invitado. Y finalmente, especifique {{ic|1=name=vdagent}} para que spice sepa para qué sirve este canal.<br />
<br />
=== Notas específicas de Windows ===<br />
<br />
QEMU puede ejecutar cualquier versión de Windows desde Windows 95 a través de Windows 10.<br />
<br />
Es posible ejecutar [[Windows PE]] en QEMU.<br />
<br />
==== Inicio rápido ====<br />
<br />
{{Note (Español)|Se requiere una cuenta de administrador para cambiar la configuración de energía.}}<br />
Para invitados de Windows 8 (o posteriores), es mejor desactivar "Activar inicio rápido (recomendado)" en Opciones de energía del Panel de control, ya que hace que el invitado se bloquee durante cada arranque.<br />
<br />
El inicio rápido también puede necesitar deshabilitarse para que los cambios en la opción {{ic|-smp}} se apliquen correctamente.<br />
<br />
==== Protocolo de escritorio remoto ====<br />
<br />
Si utiliza un invitado de MS Windows, puede utilizar RDP para conectarse a su VM invitada. Si está utilizando una VLAN o no está en la misma red que el invitado, utilice:<br />
<br />
$ qemu-system-i386 -nographic -net user,hostfwd=tcp::5555-:3389<br />
<br />
A continuación, conéctese con {{Pkg|rdesktop}} ó {{Pkg|freerdp}} al invitado. Por ejemplo:<br />
<br />
$ xfreerdp -g 2048x1152 localhost:5555 -z -x lan<br />
<br />
== Solución de problemas ==<br />
<br />
=== La máquina virtual virtual corre muy lento ===<br />
<br />
Hay algunas técnicas que se pueden usar para implementar rendimiento en la máquina virtual, por ejemplo:<br />
<br />
* Use la opción {{ic|-cpu host}} para hacer que QEMU emule la CPU del host. Si no se hace esto, podría intentar emular un CPU más genérico.<br />
* Especialmente para los invitados de Windows, habilite [https://blog.wikichoon.com/2014/07/enabling-hyper-v-enlightenments-with-kvm.html Iluminaciones de Hyper-V]: {{ic|1=-Host de la CPU, hv_relaxed, hv_spinlocks=0x1fff, hv_vapic, hv_time}}.<br />
* Si la máquina host tiene varias CPUs, asigne al invitado más CPUs usando la opción {{ic|-smp}}.<br />
* Asegúrese de haber asignado a la máquina virtual suficiente memoria. De forma predeterminada, QEMU sólo asigna 128 MiB de memoria a cada máquina virtual. Utilice la opción {{ic|-m}} para asignar más memoria. Por ejemplo, {{ic|-m 1024}} ejecuta una máquina virtual con 1024 MiB de memoria.<br />
* Utilice KVM si es posible: agregue {{ic|1=-machine type=pc, accel=kvm}} al comando de arranque QEMU que utilice.<br />
* Si es compatible con los controladores del sistema operativo invitado, utilice [https://wiki.libvirt.org/page/Virtio virtio] para dispositivos de red y/o bloque. Por ejemplo:<br />
$ qemu-system-i386 -net nic, model=virtio -net tap, if=tap0, script=no-drive file=''disk_image'',media=disco, if=virtio<br />
* Utilizar dispositivos TAP en lugar de redes en modo usuario. Consulte [[#Tap de red con QEMU]].<br />
* Si el sistema operativo invitado está haciendo escritura pesada en su disco, puede beneficiarse de ciertas opciones de montaje en el sistema de archivos del host. Por ejemplo, puede montar un [[Ext4|sistema de archivos ext4]] con la opción {{ic|1=barrier=0}}. Debe leer la documentación de las opciones que cambie porque a veces las opciones de mejora de rendimiento para los sistemas de archivos tienen el costo de integridad de los datos.<br />
* Si tiene una imagen de disco sin procesar, puede deshabilitar la caché:<br />
$ qemu-system-i386 -drive file=''disk_image'', if=virtio, cache=none<br />
* Utilice el nativo Linux AIO:<br />
$ qemu-system-i386 -drive file=''disk_image'', if=virtio, aio=native<br />
* Si utiliza una imagen de disco qcow2, el rendimiento de E/S se puede mejorar considerablemente al garantizar que el caché L2 es de tamaño suficiente. La fórmula [https://blogs.igalia.com/berto/2015/12/17/improving-disk-io-performance-in-qemu-2-5-with-the-qcow2-l2-cache/] para calcular La caché L2 es: l2_cache_size = disk_size * 8 / cluster_size. Suponiendo que la imagen qcow2 se creó con el tamaño de clúster predeterminado de 64 K, esto significa que para cada 8 GB de tamaño de la imagen qcow2, 1 MB de caché L2 es mejor para el rendimiento. QEMU utiliza sólo 1 MB por defecto; Especificar una caché más grande se hace en la línea de comandos QEMU. Por ejemplo, para especificar 4 MB de caché (adecuado para un disco de 32 GB con un tamaño de clúster de 64 KB):<br />
$ qemu-system-i386 -drive file=''disk_image'',format=qcow2, l2-cache-size=4M<br />
* Si está ejecutando varias máquinas virtuales al mismo tiempo que todas tienen el mismo sistema operativo instalado, puede ahorrar memoria al habilitar [[wikipedia: Kernel_SamePage_Merging_ (KSM)|kernel de la misma página de fusión]]. Consulte [[#Habilitar KSM]].<br />
* En algunos casos, la memoria se puede recuperar de correr máquinas virtuales ejecutando un controlador de globo de memoria en el sistema operativo invitado y lanzando QEMU con la opción {{ic|-balloon virtio}}.<br />
* Es posible utilizar una capa de emulación para un controlador ICH-9 AHCI (aunque puede ser inestable). La emulación AHCI soporta [[Wikipedia: Native_Command_Queuing|NCQ]], por lo que varias peticiones de lectura o escritura pueden estar pendientes al mismo tiempo:<br />
$ qemu-system-i386 -drive id=disc, file=''disk_image'', if=none -device ich9-ahci, id=ahci -device ide-drive, drive=disk, bus=ahci.0<br />
<br />
Mira https://www.linux-kvm.org/page/Tuning_KVM para más información.<br />
<br />
=== El cursor del ratón está nervioso o errático ===<br />
<br />
Si el cursor "brinca" descontroladamente, podría ayudar ingresar este comando en la terminal antes de iniciar QEMU<br />
<br />
$ export SDL_VIDEO_X11_DGAMOUSE=0<br />
<br />
Si funciono, puedes agregarlo a tu {{ic|~/.bashrc}} archivo.<br />
<br />
=== El cursor no es visible ===<br />
<br />
Añade {{ic|-show-cursor}} a las opciones de QEMU para poder ver el cursor.<br />
<br />
Si persiste, asegurate de configurar la pantalla apropiadamente<br />
<br />
Por ejemplo: {{ic|-vga qxl}}<br />
<br />
=== No se puede mover / adjuntar el cursor ===<br />
<br />
Reemplaza {{ic|-usbdevice tablet}} con {{ic|-usb}} como opción en QEMU.<br />
<br />
=== El teclado parece roto ó las teclas de flecha no funcionan ===<br />
<br />
Probablemente notarás que algunas de tus teclas no funcionan ó "presionan" la tecla equivocada (en particular, las flechas), preferentemente, necesitas especificar la distribución de tu teclado como una opción. La distribución del teclado puede encontrarse en {{ic|/usr/share/qemu/keymaps}}.<br />
<br />
$ qemu-system-i386 -k ''keymap'' ''disk_image''<br />
<br />
=== Pantalla de invitado estirada en el tamaño de la ventana ===<br />
<br />
Para restarurar el tamaño por defecto de la ventanta, presiona {{ic|Ctrl+Alt+u}}.<br />
<br />
=== ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy ===<br />
<br />
Si un mensaje de error como este es listado en el arranque de QEMU con la opción {{ic|-enable-kvm}}:<br />
<br />
ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy<br />
failed to initialize KVM: Device or resource busy<br />
<br />
Significa que otro [[hypervisor]] está actualmente activo. No se recomienda ó no es poible correr varios hypervisores en paralelo.<br />
<br />
=== Mensaje de error libgfapi ===<br />
<br />
El mensaje de error listado en el arranque:<br />
<br />
Failed to open module: libgfapi.so.0: cannot open shared object file: No such file or directory<br />
<br />
No es un problema, sólo significa que hace falta la dependencia opcional de GlusterFS<br />
<br />
=== Kernel panic en entornos live ===<br />
<br />
Si inicia un sistema en vivo (ó bootea uno) podría encontrar esto:<br />
<br />
end Kernel panic - not syncing: VFS: Unable to mount root fs on unknown block(0,0)<br />
<br />
Ó algún otro proceso de arranque (ej. no se puede desempaquetar initramfs, no puede iniciar un servicio foo).<br />
<br />
Intente iniciar la Máquina Virtual con el {{ic|-m VALOR}} switch y un tamaño apropiado de RAM, si la RAM es muy poca probablemente encontrará problemas similares a los anteriores.<br />
<br />
== Ver también ==<br />
<br />
* [https://qemu.org Sitio web oficial de QEMU]<br />
* [https://www.linux-kvm.org Sitio web oficial de KVM]<br />
* [https://web.archive.org/web/20200514080826/https://qemu.weilnetz.de/doc/qemu-doc.html Documentación para el usuario del emulador QEMU] (en inglés)<br />
* [https://en.wikibooks.org/wiki/QEMU Wikilibro de QEMU] (en inglés)<br />
* [http://alien.slackbook.org/dokuwiki/doku.php?id=slackware:qemu Virtualización de hardware con QEMU por AlienBOB (última actualización en 2008) (en inglés)<br />
* [http://blog.falconindy.com/articles/build-a-virtual-army.html Construyendo un ejército virtual] por Falconindy (en inglés)<br />
* [https://git.qemu.org/?p=qemu.git;a=tree;f=docs Últimos documentos]<br />
* [https://qemu.weilnetz.de/ QEMU en Windows]<br />
* [[wikipedia:Qemu|Wikipedia]]<br />
* [https://wiki.debian.org/QEMU QEMU - Wiki de Debian] (en inglés)<br />
* [https://people.gnome.org/~markmc/qemu-networking.html QEMU Networking on gnome.org]{{Dead link (Español)|2022|09|22|status=404}}<br />
* [http://bsdwiki.reedmedia.net/wiki/networking_qemu_virtual_bsd_systems.html Red virtual de QEMU en sistemas BSD] (en inglés)<br />
* [https://www.gnu.org/software/hurd/hurd/running/qemu.html QEMU on gnu.org]<br />
* [https://wiki.freebsd.org/qemu QEMU en FreeBSD como host] (en inglés)</div>Malcontenthttps://wiki.archlinux.org/index.php?title=QEMU&diff=796034QEMU2024-01-04T14:16:05Z<p>Malcontent: Add missing punctuation</p>
<hr />
<div>[[Category:Emulation]]<br />
[[Category:Hypervisors]]<br />
[[de:QEMU]]<br />
[[es:QEMU]]<br />
[[fr:QEMU]]<br />
[[ja:QEMU]]<br />
[[zh-hans:QEMU]]<br />
{{Related articles start}}<br />
{{Related|:Category:Hypervisors}}<br />
{{Related|Libvirt}}<br />
{{Related|QEMU/Guest graphics acceleration}}<br />
{{Related|PCI passthrough via OVMF}}<br />
{{Related articles end}}<br />
<br />
According to the [https://wiki.qemu.org/Main_Page QEMU about page], "QEMU is a generic and open source machine emulator and virtualizer."<br />
<br />
When used as a machine emulator, QEMU can run OSes and programs made for one machine (e.g. an ARM board) on a different machine (e.g. your x86 PC). By using dynamic translation, it achieves very good performance.<br />
<br />
QEMU can use other hypervisors like [[Xen]] or [[KVM]] to use CPU extensions ([[Wikipedia:Hardware-assisted virtualization|HVM]]) for virtualization. When used as a virtualizer, QEMU achieves near native performances by executing the guest code directly on the host CPU.<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|qemu-full}} package (or {{Pkg|qemu-base}} for the version without GUI) and below optional packages for your needs:<br />
<br />
* {{Pkg|qemu-block-gluster}} - [[Glusterfs]] block support<br />
* {{Pkg|qemu-block-iscsi}} - [[iSCSI]] block support<br />
* {{Pkg|samba}} - [[Samba|SMB/CIFS]] server support<br />
<br />
Alternatively, {{Pkg|qemu-user-static}} exists as a usermode and static variant.<br />
<br />
=== QEMU variants ===<br />
<br />
QEMU is offered in several variants suited for different use cases.<br />
<br />
As a first classification, QEMU is offered in full-system and usermode emulation modes:<br />
<br />
; Full-system emulation<br />
: In this mode, QEMU emulates a full system, including one or several processors and various peripherals. It is more accurate but slower, and does not require the emulated OS to be Linux.<br />
: QEMU commands for full-system emulation are named {{ic|qemu-system-''target_architecture''}}, e.g. {{ic|qemu-system-x86_64}} for emulating [[Wikipedia:x86_64|x86_64]] CPUs, {{ic|qemu-system-i386}} for Intel [[Wikipedia:i386|32-bit x86]] CPUs, {{ic|qemu-system-arm}} for [[Wikipedia:ARM architecture family#32-bit architecture|ARM (32 bits)]], {{ic|qemu-system-aarch64}} for [[Wikipedia:AArch64|ARM64]], etc.<br />
: If the target architecture matches the host CPU, this mode may still benefit from a significant speedup by using a hypervisor like [[#Enabling KVM|KVM]] or Xen.<br />
; [https://www.qemu.org/docs/master/user/main.html Usermode emulation]<br />
: In this mode, QEMU is able to invoke a Linux executable compiled for a (potentially) different architecture by leveraging the host system resources. There may be compatibility issues, e.g. some features may not be implemented, dynamically linked executables will not work out of the box (see [[#Chrooting into arm/arm64 environment from x86_64]] to address this) and only Linux is supported (although [https://wiki.winehq.org/Emulation Wine may be used] for running Windows executables).<br />
: QEMU commands for usermode emulation are named {{ic|qemu-''target_architecture''}}, e.g. {{ic|qemu-x86_64}} for emulating 64-bit CPUs.<br />
<br />
QEMU is offered in dynamically-linked and statically-linked variants:<br />
<br />
; Dynamically-linked (default): {{ic|qemu-*}} commands depend on the host OS libraries, so executables are smaller.<br />
; Statically-linked: {{ic|qemu-*}} commands can be copied to any Linux system with the same architecture.<br />
<br />
In the case of Arch Linux, full-system emulation is offered as:<br />
<br />
; Non-headless (default): This variant enables GUI features that require additional dependencies (like SDL or GTK).<br />
; Headless: This is a slimmer variant that does not require GUI (this is suitable e.g. for servers).<br />
<br />
Note that headless and non-headless versions install commands with the same name (e.g. {{ic|qemu-system-x86_64}}) and thus cannot be both installed at the same time.<br />
<br />
=== Details on packages available in Arch Linux ===<br />
<br />
* The {{Pkg|qemu-desktop}} package provides the {{ic|x86_64}} architecture emulators for full-system emulation ({{ic|qemu-system-x86_64}}). The {{Pkg|qemu-emulators-full}} package provides the {{ic|x86_64}} usermode variant ({{ic|qemu-x86_64}}) and also for the rest of supported architectures it includes both full-system and usermode variants (e.g. {{ic|qemu-system-arm}} and {{ic|qemu-arm}}).<br />
* The headless versions of these packages (only applicable to full-system emulation) are {{Pkg|qemu-base}} ({{ic|x86_64}}-only) and {{Pkg|qemu-emulators-full}} (rest of architectures).<br />
* Full-system emulation can be expanded with some QEMU modules present in separate packages: {{Pkg|qemu-block-gluster}}, {{Pkg|qemu-block-iscsi}} and {{Pkg|qemu-guest-agent}}.<br />
* {{Pkg|qemu-user-static}} provides a usermode and static variant for all target architectures supported by QEMU. The installed QEMU commands are named {{ic|qemu-''target_architecture''-static}}, for example, {{ic|qemu-x86_64-static}} for intel 64-bit CPUs.<br />
<br />
{{Note|At present, Arch does not offer a full-system mode and statically linked variant (neither officially nor via AUR), as this is usually not needed.}}<br />
<br />
=== Custom build ===<br />
<br />
{{Remove|Explaining how to use the [[Arch build system]] is out of scope here. There is no motivation for the customization in the first place.}}<br />
<br />
To obtain a customized version of QEMU, [[Git#Getting a Git repository|clone]] the package source of {{Pkg|qemu-common}} or {{AUR|qemu-git}}.<br />
<br />
The respective [[PKGBUILD]] file calls QEMU's [https://www.gnu.org/prep/standards/html_node/Configuration.html configure script] which accepts parameters obtainable by first manually running --help on it. <br />
To access this help beforehand, you may [[Makepkg#Usage|use makepkg]] to let it download and extract the QEMU source, canceling the build process as soon as the configure script begins.<br />
<br />
With the PKGBUILD file's configure script calls modified as desired, you may [[Makepkg#Usage|use makepkg]] (again) to let it build the packages, though it is inadvisable to let it install them as conflicting headless / static packages will be built as well and a typical user certainly won't need the additional system emulators for the other architectures.<br />
<br />
When the build process completes, it is advisable to instead copy your desired packages (see the [[#Removal|list for qemu-desktop in "Removal"]]{{Broken section link}}) to a different directory, [[Pacman#Additional commands|let pacman install them all]] and add them to the [[Pacman#Skip package from being upgraded|IgnorePkg]] list so you get to upgrade them manually.<br />
<br />
== Graphical front-ends for QEMU ==<br />
<br />
Unlike other virtualization programs such as [[VirtualBox]] and [[VMware]], QEMU does not provide a GUI to manage virtual machines (other than the window that appears when running a virtual machine), nor does it provide a way to create persistent virtual machines with saved settings. All parameters to run a virtual machine must be specified on the command line at every launch, unless you have created a custom script to start your virtual machine(s).<br />
<br />
[[Libvirt]] provides a convenient way to manage QEMU virtual machines. See [[Libvirt#Client|list of libvirt clients]] for available front-ends.<br />
<br />
== Creating new virtualized system ==<br />
<br />
=== Creating a hard disk image ===<br />
<br />
{{Accuracy|If I get the man page right the raw format only allocates the full size if the filesystem does not support "holes" or it is <br />
explicitly told to preallocate. See {{man|1|qemu-img|NOTES}}.}} <br />
<br />
{{Tip|See [[Wikibooks:QEMU/Images]] for more information on QEMU images.}}<br />
<br />
To run QEMU you will need a hard disk image, unless you are booting a live system from CD-ROM or the network (and not doing so to install an operating system to a hard disk image). A hard disk image is a file which stores the contents of the emulated hard disk.<br />
<br />
A hard disk image can be ''raw'', so that it is literally byte-by-byte the same as what the guest sees, and will always use the full capacity of the guest hard drive on the host. This method provides the least I/O overhead, but can waste a lot of space, as not-used space on the guest cannot be used on the host.<br />
<br />
Alternatively, the hard disk image can be in a format such as ''qcow2'' which only allocates space to the image file when the guest operating system actually writes to those sectors on its virtual hard disk. The image appears as the full size to the guest operating system, even though it may take up only a very small amount of space on the host system. This image format also supports QEMU snapshotting functionality (see [[#Creating and managing snapshots via the monitor console]] for details). However, using this format instead of ''raw'' will likely affect performance.<br />
<br />
QEMU provides the {{ic|qemu-img}} command to create hard disk images. For example to create a 4 GiB image in the ''raw'' format:<br />
<br />
$ qemu-img create -f raw ''image_file'' 4G<br />
<br />
You may use {{ic|-f qcow2}} to create a ''qcow2'' disk instead.<br />
<br />
{{Note|You can also simply create a ''raw'' image by creating a file of the needed size using {{ic|dd}} or {{ic|fallocate}}.}}<br />
<br />
{{Warning|If you store the hard disk images on a [[Btrfs]] file system, you should consider disabling [[Btrfs#Copy-on-Write (CoW)|Copy-on-Write]] for the directory before creating any images.}}<br />
<br />
==== Overlay storage images ====<br />
<br />
You can create a storage image once (the 'backing' image) and have QEMU keep mutations to this image in an overlay image. This allows you to revert to a previous state of this storage image. You could revert by creating a new overlay image at the time you wish to revert, based on the original backing image.<br />
<br />
To create an overlay image, issue a command like:<br />
<br />
$ qemu-img create -o backing_file=''img1.raw'',backing_fmt=''raw'' -f ''qcow2'' ''img1.cow''<br />
<br />
After that you can run your QEMU virtual machine as usual (see [[#Running virtualized system]]):<br />
<br />
$ qemu-system-x86_64 ''img1.cow''<br />
<br />
The backing image will then be left intact and mutations to this storage will be recorded in the overlay image file.<br />
<br />
When the path to the backing image changes, repair is required.<br />
<br />
{{Warning|The backing image's absolute filesystem path is stored in the (binary) overlay image file. Changing the backing image's path requires some effort.}}<br />
<br />
Make sure that the original backing image's path still leads to this image. If necessary, make a symbolic link at the original path to the new path. Then issue a command like:<br />
<br />
$ qemu-img rebase -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
At your discretion, you may alternatively perform an 'unsafe' rebase where the old path to the backing image is not checked:<br />
<br />
$ qemu-img rebase -u -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
==== Resizing an image ====<br />
<br />
{{Warning|Resizing an image containing an NTFS boot file system could make the operating system installed on it unbootable. It is recommended to create a backup first.}}<br />
<br />
The {{ic|qemu-img}} executable has the {{ic|resize}} option, which enables easy resizing of a hard drive image. It works for both ''raw'' and ''qcow2''. For example, to increase image space by 10 GiB, run:<br />
<br />
$ qemu-img resize ''disk_image'' +10G<br />
<br />
After enlarging the disk image, you must use file system and partitioning tools inside the virtual machine to actually begin using the new space. <br />
<br />
===== Shrinking an image =====<br />
<br />
When shrinking a disk image, you must first reduce the allocated file systems and partition sizes using the file system and partitioning tools inside the virtual machine and then shrink the disk image accordingly. For a Windows guest, this can be performed from the "create and format hard disk partitions" control panel.<br />
<br />
{{Warning|Proceeding to shrink the disk image without reducing the guest partition sizes will result in data loss.}}<br />
<br />
Then, to decrease image space by 10 GiB, run:<br />
<br />
$ qemu-img resize --shrink ''disk_image'' -10G<br />
<br />
==== Converting an image ====<br />
<br />
You can convert an image to other formats using {{ic|qemu-img convert}}. This example shows how to convert a ''raw'' image to ''qcow2'':<br />
<br />
$ qemu-img convert -f raw -O qcow2 ''input''.img ''output''.qcow2<br />
<br />
This will not remove the original input file.<br />
<br />
=== Preparing the installation media ===<br />
<br />
To install an operating system into your disk image, you need the installation medium (e.g. optical disc, USB-drive, or ISO image) for the operating system. The installation medium should not be mounted because QEMU accesses the media directly.<br />
<br />
{{Tip|If using an optical disc, it is a good idea to first dump the media to a file because this both improves performance and does not require you to have direct access to the devices (that is, you can run QEMU as a regular user without having to change access permissions on the media's device file). For example, if the CD-ROM device node is named {{ic|/dev/cdrom}}, you can dump it to a file with the command: {{bc|1=$ dd if=/dev/cdrom of=''cd_image.iso'' bs=4k}}}}<br />
<br />
=== Installing the operating system ===<br />
<br />
This is the first time you will need to start the emulator. To install the operating system on the disk image, you must attach both the disk image and the installation media to the virtual machine, and have it boot from the installation media.<br />
<br />
For example on i386 guests, to install from a bootable ISO file as CD-ROM and a raw disk image:<br />
<br />
$ qemu-system-x86_64 -cdrom ''iso_image'' -boot order=d -drive file=''disk_image'',format=raw<br />
<br />
See {{man|1|qemu}} for more information about loading other media types (such as floppy, disk images or physical drives) and [[#Running virtualized system]] for other useful options.<br />
<br />
After the operating system has finished installing, the QEMU image can be booted directly (see [[#Running virtualized system]]).<br />
<br />
{{Note|By default only 128 MiB of memory is assigned to the machine. The amount of memory can be adjusted with the {{ic|-m}} switch, for example {{ic|-m 512M}} or {{ic|-m 2G}}.}}<br />
<br />
{{Tip|<br />
* Instead of specifying {{ic|1=-boot order=x}}, some users may feel more comfortable using a boot menu: {{ic|1=-boot menu=on}}, at least during configuration and experimentation.<br />
* When running QEMU in headless mode, it starts a local VNC server on port 5900 per default. You can use [[TigerVNC]] to connect to the guest OS: {{ic|vncviewer :5900}}<br />
* If you need to replace floppies or CDs as part of the installation process, you can use the QEMU machine monitor (press {{ic|Ctrl+Alt+2}} in the virtual machine's window) to remove and attach storage devices to a virtual machine. Type {{ic|info block}} to see the block devices, and use the {{ic|change}} command to swap out a device. Press {{ic|Ctrl+Alt+1}} to go back to the virtual machine.<br />
}}<br />
<br />
== Running virtualized system ==<br />
<br />
{{ic|qemu-system-*}} binaries (for example {{ic|qemu-system-i386}} or {{ic|qemu-system-x86_64}}, depending on guest's architecture) are used to run the virtualized guest. The usage is:<br />
<br />
$ qemu-system-x86_64 ''options'' ''disk_image''<br />
<br />
Options are the same for all {{ic|qemu-system-*}} binaries, see {{man|1|qemu}} for documentation of all options.<br />
<br />
Usually, if an option has many possible values, you can use<br />
<br />
$ qemu-system-x86_64 ''option'' ''help''<br />
<br />
to list all possible values. If it supports properties, you can use<br />
<br />
$ qemu-system-x86_64 ''option'' ''value,help''<br />
<br />
to list all available properties.<br />
<br />
For example:<br />
$ qemu-system-x86_64 -machine help<br />
$ qemu-system-x86_64 -machine q35,help<br />
$ qemu-system-x86_64 -device help<br />
$ qemu-system-x86_64 -device qxl,help<br />
<br />
You can use these methods and the {{man|1|qemu}} documentation to understand the options used in follow sections.<br />
<br />
By default, QEMU will show the virtual machine's video output in a window. One thing to keep in mind: when you click inside the QEMU window, the mouse pointer is grabbed. To release it, press {{ic|Ctrl+Alt+g}}.<br />
<br />
{{Warning|QEMU should never be run as root. If you must launch it in a script as root, you should use the {{ic|-runas}} option to make QEMU drop root privileges.}}<br />
<br />
=== Enabling KVM ===<br />
<br />
KVM (''Kernel-based Virtual Machine'') full virtualization must be supported by your Linux kernel and your hardware, and necessary [[kernel modules]] must be loaded. See [[KVM]] for more information.<br />
<br />
To start QEMU in KVM mode, append {{ic|-accel kvm}} to the additional start options. To check if KVM is enabled for a running virtual machine, enter the [[#QEMU monitor]] and type {{ic|info kvm}}.<br />
<br />
{{Note|<br />
* The argument {{ic|1=accel=kvm}} of the {{ic|-machine}} option is equivalent to the {{ic|-enable-kvm}} or the {{ic|-accel kvm}} option.<br />
* CPU model {{ic|host}} requires KVM.<br />
* If you start your virtual machine with a GUI tool and experience very bad performance, you should check for proper KVM support, as QEMU may be falling back to software emulation.<br />
* KVM needs to be enabled in order to start Windows 7 or Windows 8 properly without a ''blue screen''.<br />
}}<br />
<br />
=== Enabling IOMMU (Intel VT-d/AMD-Vi) support ===<br />
<br />
First enable IOMMU, see [[PCI passthrough via OVMF#Setting up IOMMU]].<br />
<br />
Add {{ic|-device intel-iommu}} to create the IOMMU device:<br />
<br />
$ qemu-system-x86_64 '''-enable-kvm -machine q35 -device intel-iommu''' -cpu host ..<br />
<br />
{{Note|<br />
On Intel CPU based systems creating an IOMMU device in a QEMU guest with {{ic|-device intel-iommu}} will disable PCI passthrough with an error like: {{bc|Device at bus pcie.0 addr 09.0 requires iommu notifier which is currently not supported by intel-iommu emulation}} While adding the kernel parameter {{ic|1=intel_iommu=on}} is still needed for remapping IO (e.g. [[PCI passthrough via OVMF#Isolating the GPU|PCI passthrough with vfio-pci]]), {{ic|-device intel-iommu}} should not be set if PCI passthrough is required.<br />
}}<br />
<br />
=== Booting in UEFI mode ===<br />
<br />
The default firmware used by QEMU is [https://www.coreboot.org/SeaBIOS SeaBIOS], which is a Legacy BIOS implementation. QEMU uses {{ic|/usr/share/qemu/bios-256k.bin}} (provided by the {{Pkg|seabios}} package) as a default read-only (ROM) image. You can use the {{ic|-bios}} argument to select another firmware file. However, UEFI requires writable memory to work properly, so you need to emulate [https://wiki.qemu.org/Features/PC_System_Flash PC System Flash] instead.<br />
<br />
[https://github.com/tianocore/tianocore.github.io/wiki/OVMF OVMF] is a TianoCore project to enable UEFI support for Virtual Machines. It can be [[install]]ed with the {{Pkg|edk2-ovmf}} package.<br />
<br />
There are two ways to use OVMF as a firmware. The first is to copy {{ic|/usr/share/edk2/x64/OVMF.4m.fd}}, make it writable and use as a pflash drive:<br />
<br />
-drive if=pflash,format=raw,file=''/copy/of/OVMF.4m.fd''<br />
<br />
All changes to the UEFI settings will be saved directly to this file.<br />
<br />
Another and more preferable way is to split OVMF into two files. The first one will be read-only and store the firmware executable, and the second one will be used as a writable variable store. The advantage is that you can use the firmware file directly without copying, so it will be updated automatically by [[pacman]].<br />
<br />
Use {{ic|/usr/share/edk2/x64/OVMF_CODE.4m.fd}} as a first read-only pflash drive. Copy {{ic|/usr/share/edk2/x64/OVMF_VARS.4m.fd}}, make it writable and use as a second writable pflash drive:<br />
<br />
-drive if=pflash,format=raw,readonly=on,file=/usr/share/edk2/x64/OVMF_CODE.4m.fd \<br />
-drive if=pflash,format=raw,file=''/copy/of/OVMF_VARS.4m.fd''<br />
<br />
If secure boot is wanted, replace {{ic|/usr/share/edk2/x64/OVMF_CODE.4m.fd}} with {{ic|/usr/share/edk2/x64/OVMF_CODE.secboot.4m.fd}}.<br />
<br />
=== Trusted Platform Module emulation ===<br />
<br />
QEMU can emulate [[Trusted Platform Module]], which is required by some systems such as Windows 11 (which requires TPM 2.0).<br />
<br />
[[Install]] the {{Pkg|swtpm}} package, which provides a software TPM implementation. Create some directory for storing TPM data ({{ic|''/path/to/mytpm''}} will be used as an example). Run this command to start the emulator:<br />
<br />
$ swtpm socket --tpm2 --tpmstate dir=''/path/to/mytpm'' --ctrl type=unixio,path=''/path/to/mytpm/swtpm-sock''<br />
<br />
{{ic|''/path/to/mytpm/swtpm-sock''}} will be created by ''swtpm'': this is a UNIX socket to which QEMU will connect. You can put it in any directory.<br />
<br />
By default, ''swtpm'' starts a TPM version 1.2 emulator. The {{ic|--tpm2}} option enables TPM 2.0 emulation.<br />
<br />
Finally, add the following options to QEMU:<br />
<br />
-chardev socket,id=chrtpm,path=''/path/to/mytpm/swtpm-sock'' \<br />
-tpmdev emulator,id=tpm0,chardev=chrtpm \<br />
-device tpm-tis,tpmdev=tpm0<br />
<br />
and TPM will be available inside the virtual machine. After shutting down the virtual machine, ''swtpm'' will be automatically terminated.<br />
<br />
See [https://qemu-project.gitlab.io/qemu/specs/tpm.html the QEMU documentation] for more information. <br />
<br />
If guest OS still doesn't recognize the TPM device, try to adjust ''CPU Models and Topology'' options. It might cause problem.<br />
<br />
== Sharing data between host and guest ==<br />
<br />
=== Network ===<br />
<br />
Data can be shared between the host and guest OS using any network protocol that can transfer files, such as [[NFS]], [[SMB]], [[Wikipedia:Network block device|NBD]], HTTP, [[Very Secure FTP Daemon|FTP]], or [[SSH]], provided that you have set up the network appropriately and enabled the appropriate services.<br />
<br />
The default user-mode networking allows the guest to access the host OS at the IP address 10.0.2.2. Any servers that you are running on your host OS, such as a SSH server or SMB server, will be accessible at this IP address. So on the guests, you can mount directories exported on the host via [[SMB]] or [[NFS]], or you can access the host's HTTP server, etc.<br />
It will not be possible for the host OS to access servers running on the guest OS, but this can be done with other network configurations (see [[#Tap networking with QEMU]]).<br />
<br />
=== QEMU's port forwarding ===<br />
<br />
{{Note|QEMU's port forwarding is IPv4-only. IPv6 port forwarding is not implemented and the last patches were proposed in 2018.[https://lore.kernel.org/qemu-devel/1540512223-21199-1-git-send-email-max7255@yandex-team.ru/T/#u]}}<br />
<br />
QEMU can forward ports from the host to the guest to enable e.g. connecting from the host to an SSH server running on the guest.<br />
<br />
For example, to bind port 60022 on the host with port 22 (SSH) on the guest, start QEMU with a command like:<br />
<br />
$ qemu-system-x86_64 ''disk_image'' -nic user,hostfwd=tcp::60022-:22<br />
<br />
Make sure the sshd is running on the guest and connect with:<br />
<br />
$ ssh ''guest-user''@127.0.0.1 -p 60022<br />
<br />
You can use [[SSHFS]] to mount the guest's file system at the host for shared read and write access.<br />
<br />
To forward several ports, you just repeat the {{ic|hostfwd}} in the {{ic|-nic}} argument, e.g. for VNC's port:<br />
<br />
$ qemu-system-x86_64 ''disk_image'' -nic user,hostfwd=tcp::60022-:22,hostfwd=tcp::5900-:5900<br />
<br />
=== QEMU's built-in SMB server ===<br />
<br />
QEMU's documentation says it has a "built-in" SMB server, but actually it just starts up [[Samba]] on the host with an automatically generated {{ic|smb.conf}} file located in {{ic|/tmp/qemu-smb.''random_string''}} and makes it accessible to the guest at a different IP address (10.0.2.4 by default). This only works for user networking, and is useful when you do not want to start the normal [[Samba]] service on the host, which the guest can also access if you have set up shares on it.<br />
<br />
Only a single directory can be set as shared with the option {{ic|1=smb=}}, but adding more directories (even while the virtual machine is running) could be as easy as creating symbolic links in the shared directory if QEMU configured SMB to follow symbolic links. It does not do so, but the configuration of the running SMB server can be changed as described below.<br />
<br />
''Samba'' must be installed on the host. To enable this feature, start QEMU with a command like:<br />
<br />
$ qemu-system-x86_64 -nic user,id=nic0,smb=''shared_dir_path'' ''disk_image''<br />
<br />
where {{ic|''shared_dir_path''}} is a directory that you want to share between the guest and host.<br />
<br />
Then, in the guest, you will be able to access the shared directory on the host 10.0.2.4 with the share name "qemu". For example, in Windows Explorer you would go to {{ic|\\10.0.2.4\qemu}}.<br />
<br />
{{Note|<br />
* If you are using sharing options multiple times like {{ic|1=-net user,smb=''shared_dir_path1'' -net user,smb=''shared_dir_path2''}} or {{ic|1=-net user,smb=''shared_dir_path1'',smb=''shared_dir_path2''}} then it will share only the last defined one.<br />
* If you cannot access the shared folder and the guest system is Windows, check that the [http://ecross.mvps.org/howto/enable-netbios-over-tcp-ip-with-windows.htm NetBIOS protocol is enabled]{{Dead link|2023|05|06|status=domain name not resolved}} and that a firewall does not block [https://technet.microsoft.com/en-us/library/cc940063.aspx ports] used by the NetBIOS protocol.<br />
* If you cannot access the shared folder and the guest system is Windows 10 Enterprise or Education or Windows Server 2016, [https://support.microsoft.com/en-us/help/4046019 enable guest access].<br />
* If you use [[#Tap networking with QEMU]], use {{ic|1=-device virtio-net,netdev=vmnic -netdev user,id=vmnic,smb=''shared_dir_path''}} to get SMB.<br />
}}<br />
<br />
One way to share multiple directories and to add or remove them while the virtual machine is running, is to share an empty directory and create/remove symbolic links to the directories in the shared directory. For this to work, the configuration of the running SMB server can be changed with the following script, which also allows the execution of files on the guest that are not set executable on the host:<br />
<br />
#!/bin/sh<br />
eval $(ps h -C smbd -o pid,args | grep /tmp/qemu-smb | gawk '{print "pid="$1";conf="$6}')<br />
echo "[global]<br />
allow insecure wide links = yes<br />
[qemu]<br />
follow symlinks = yes<br />
wide links = yes<br />
acl allow execute always = yes" >> "$conf"<br />
# in case the change is not detected automatically:<br />
smbcontrol --configfile="$conf" "$pid" reload-config<br />
<br />
This can be applied to the running server started by qemu only after the guest has connected to the network drive the first time. An alternative to this method is to add additional shares to the configuration file like so:<br />
<br />
echo "[''myshare'']<br />
path=''another_path''<br />
read only=no<br />
guest ok=yes<br />
force user=''username''" >> $conf<br />
<br />
This share will be available on the guest as {{ic|\\10.0.2.4\''myshare''}}.<br />
<br />
=== Using filesystem passthrough and VirtFS ===<br />
<br />
See the [https://wiki.qemu.org/Documentation/9psetup QEMU documentation].<br />
<br />
=== Host file sharing with virtiofsd ===<br />
<br />
{{Style|See [[Help:Style/Formatting and punctuation]].}}<br />
<br />
virtiofsd is shipped with QEMU package. Documentation is available [https://qemu-stsquad.readthedocs.io/en/docs-next/tools/virtiofsd.html online]{{Dead link|2023|05|06|status=404}} or {{ic|/usr/share/doc/qemu/qemu/tools/virtiofsd.html}} on local file system with {{Pkg|qemu-docs}} installed.<br />
<br />
Add user that runs qemu to the 'kvm' [[user group]], because it needs to access the virtiofsd socket. You might have to logout for change to take effect.<br />
<br />
{{Accuracy|Running services as root is not secure. Also the process should be wrapped in a systemd service.}}<br />
<br />
Start as virtiofsd as root:<br />
<br />
# /usr/lib/virtiofsd --socket-path=/var/run/qemu-vm-001.sock --shared-dir /tmp/vm-001 --cache always<br />
<br />
where<br />
<br />
* {{ic|/var/run/qemu-vm-001.sock}} is a socket file,<br />
* {{ic|/tmp/vm-001}} is a shared directory between the host and the guest virtual machine.<br />
<br />
The created socket file has root only access permission. Give group kvm access to it with:<br />
<br />
# chgrp kvm qemu-vm-001.sock; chmod g+rxw qemu-vm-001.sock<br />
<br />
Add the following configuration options when starting the virtual machine:<br />
<br />
-object memory-backend-memfd,id=mem,size=4G,share=on \<br />
-numa node,memdev=mem \<br />
-chardev socket,id=char0,path=/var/run/qemu-vm-001.sock \<br />
-device vhost-user-fs-pci,chardev=char0,tag=myfs<br />
<br />
where<br />
<br />
{{Expansion|Explain the remaining options (or remove them if they are not necessary).}}<br />
<br />
* {{ic|1=size=4G}} shall match size specified with {{ic|-m 4G}} option,<br />
* {{ic|/var/run/qemu-vm-001.sock}} points to socket file started earlier,<br />
<br />
{{Style|The section should not be specific to Windows.}}<br />
<br />
Remember, that guest must be configured to enable sharing. For Windows there are [https://virtio-fs.gitlab.io/howto-windows.html instructions]. Once configured, Windows will have the {{ic|Z:}} drive mapped automatically with shared directory content.<br />
<br />
Your Windows 10 guest system is properly configured if it has:<br />
<br />
* VirtioFSSService windows service,<br />
* WinFsp.Launcher windows service,<br />
* VirtIO FS Device driver under "System devices" in Windows "Device Manager".<br />
<br />
If the above installed and {{ic|Z:}} drive is still not listed, try repairing "Virtio-win-guest-tools" in Windows ''Add/Remove programs''.<br />
<br />
=== Mounting a partition of the guest on the host ===<br />
<br />
It can be useful to mount a drive image under the host system, it can be a way to transfer files in and out of the guest. This should be done when the virtual machine is not running.<br />
<br />
The procedure to mount the drive on the host depends on the type of qemu image, ''raw'' or ''qcow2''. We detail thereafter the steps to mount a drive in the two formats in [[#Mounting a partition from a raw image]] and [[#Mounting a partition from a qcow2 image]]. For the full documentation see [[Wikibooks:QEMU/Images#Mounting an image on the host]].<br />
<br />
{{Warning|You must unmount the partitions before running the virtual machine again. Otherwise, data corruption is very likely to occur.}}<br />
<br />
==== Mounting a partition from a raw image ====<br />
<br />
It is possible to mount partitions that are inside a raw disk image file by setting them up as loopback devices.<br />
<br />
===== With manually specifying byte offset =====<br />
<br />
One way to mount a disk image partition is to mount the disk image at a certain offset using a command like the following:<br />
<br />
# mount -o loop,offset=32256 ''disk_image'' ''mountpoint''<br />
<br />
The {{ic|1=offset=32256}} option is actually passed to the {{ic|losetup}} program to set up a loopback device that starts at byte offset 32256 of the file and continues to the end. This loopback device is then mounted. You may also use the {{ic|sizelimit}} option to specify the exact size of the partition, but this is usually unnecessary.<br />
<br />
Depending on your disk image, the needed partition may not start at offset 32256. Run {{ic|fdisk -l ''disk_image''}} to see the partitions in the image. fdisk gives the start and end offsets in 512-byte sectors, so multiply by 512 to get the correct offset to pass to {{ic|mount}}.<br />
<br />
===== With loop module autodetecting partitions =====<br />
<br />
The Linux loop driver actually supports partitions in loopback devices, but it is disabled by default. To enable it, do the following:<br />
<br />
* Get rid of all your loopback devices (unmount all mounted images, etc.).<br />
* [[Kernel modules#Manual module handling|Unload]] the {{ic|loop}} kernel module, and load it with the {{ic|1=max_part=15}} parameter set. Additionally, the maximum number of loop devices can be controlled with the {{ic|max_loop}} parameter.<br />
<br />
{{Tip|You can put an entry in {{ic|/etc/modprobe.d}} to load the loop module with {{ic|1=max_part=15}} every time, or you can put {{ic|1=loop.max_part=15}} on the kernel command-line, depending on whether you have the {{ic|loop.ko}} module built into your kernel or not.}}<br />
<br />
Set up your image as a loopback device:<br />
<br />
# losetup -f -P ''disk_image''<br />
<br />
Then, if the device created was {{ic|/dev/loop0}}, additional devices {{ic|/dev/loop0p''X''}} will have been automatically created, where X is the number of the partition. These partition loopback devices can be mounted directly. For example:<br />
<br />
# mount /dev/loop0p1 ''mountpoint''<br />
<br />
To mount the disk image with ''udisksctl'', see [[Udisks#Mount loop devices]].<br />
<br />
===== With kpartx =====<br />
<br />
''kpartx'' from the {{Pkg|multipath-tools}} package can read a partition table on a device and create a new device for each partition. For example:<br />
<br />
# kpartx -a ''disk_image''<br />
<br />
This will setup the loopback device and create the necessary partition(s) device(s) in {{ic|/dev/mapper/}}.<br />
<br />
==== Mounting a partition from a qcow2 image ====<br />
<br />
We will use {{ic|qemu-nbd}}, which lets use the NBD (''network block device'') protocol to share the disk image.<br />
<br />
First, we need the ''nbd'' module loaded:<br />
<br />
# modprobe nbd max_part=16<br />
<br />
Then, we can share the disk and create the device entries:<br />
<br />
# qemu-nbd -c /dev/nbd0 ''/path/to/image.qcow2''<br />
<br />
Discover the partitions:<br />
<br />
# partprobe /dev/nbd0<br />
<br />
''fdisk'' can be used to get information regarding the different partitions in {{ic|''nbd0''}}:<br />
<br />
{{hc|# fdisk -l /dev/nbd0|2=<br />
Disk /dev/nbd0: 25.2 GiB, 27074281472 bytes, 52879456 sectors<br />
Units: sectors of 1 * 512 = 512 bytes<br />
Sector size (logical/physical): 512 bytes / 512 bytes<br />
I/O size (minimum/optimal): 512 bytes / 512 bytes<br />
Disklabel type: dos<br />
Disk identifier: 0xa6a4d542<br />
<br />
Device Boot Start End Sectors Size Id Type<br />
/dev/nbd0p1 * 2048 1026047 1024000 500M 7 HPFS/NTFS/exFAT<br />
/dev/nbd0p2 1026048 52877311 51851264 24.7G 7 HPFS/NTFS/exFAT}}<br />
<br />
Then mount any partition of the drive image, for example the partition 2:<br />
<br />
# mount /dev/nbd0'''p2''' ''mountpoint''<br />
<br />
After the usage, it is important to unmount the image and reverse previous steps, i.e. unmount the partition and disconnect the nbd device:<br />
<br />
# umount ''mountpoint''<br />
# qemu-nbd -d /dev/nbd0<br />
<br />
=== Using any real partition as the single primary partition of a hard disk image ===<br />
<br />
Sometimes, you may wish to use one of your system partitions from within QEMU. Using a raw partition for a virtual machine will improve performance, as the read and write operations do not go through the file system layer on the physical host. Such a partition also provides a way to share data between the host and guest.<br />
<br />
In Arch Linux, device files for raw partitions are, by default, owned by ''root'' and the ''disk'' group. If you would like to have a non-root user be able to read and write to a raw partition, you must either change the owner of the partition's device file to that user, add that user to the ''disk'' group, or use [[ACL]] for more fine-grained access control.<br />
<br />
{{Warning|<br />
* Although it is possible, it is not recommended to allow virtual machines to alter critical data on the host system, such as the root partition.<br />
* You must not mount a file system on a partition read-write on both the host and the guest at the same time. Otherwise, data corruption will result.<br />
}}<br />
<br />
After doing so, you can attach the partition to a QEMU virtual machine as a virtual disk.<br />
<br />
However, things are a little more complicated if you want to have the ''entire'' virtual machine contained in a partition. In that case, there would be no disk image file to actually boot the virtual machine since you cannot install a boot loader to a partition that is itself formatted as a file system and not as a partitioned device with an MBR. Such a virtual machine can be booted either by: [[#Specifying kernel and initrd manually]], [[#Simulating a virtual disk with MBR]], [[#Using the device-mapper]], [[#Using a linear RAID]] or [[#Using a Network Block Device]].<br />
<br />
==== Specifying kernel and initrd manually ====<br />
<br />
QEMU supports loading [[Kernels|Linux kernels]] and [[initramfs|init ramdisks]] directly, thereby circumventing boot loaders such as [[GRUB]]. It then can be launched with the physical partition containing the root file system as the virtual disk, which will not appear to be partitioned. This is done by issuing a command similar to the following:<br />
<br />
{{Note|In this example, it is the '''host's''' images that are being used, not the guest's. If you wish to use the guest's images, either mount {{ic|/dev/sda3}} read-only (to protect the file system from the host) and specify the {{ic|/full/path/to/images}} or use some kexec hackery in the guest to reload the guest's kernel (extends boot time). }}<br />
<br />
$ qemu-system-x86_64 -kernel /boot/vmlinuz-linux -initrd /boot/initramfs-linux.img -append root=/dev/sda /dev/sda3<br />
<br />
In the above example, the physical partition being used for the guest's root file system is {{ic|/dev/sda3}} on the host, but it shows up as {{ic|/dev/sda}} on the guest.<br />
<br />
You may, of course, specify any kernel and initrd that you want, and not just the ones that come with Arch Linux.<br />
<br />
When there are multiple [[kernel parameters]] to be passed to the {{ic|-append}} option, they need to be quoted using single or double quotes. For example:<br />
<br />
... -append 'root=/dev/sda1 console=ttyS0'<br />
<br />
==== Simulating a virtual disk with MBR ====<br />
<br />
A more complicated way to have a virtual machine use a physical partition, while keeping that partition formatted as a file system and not just having the guest partition the partition as if it were a disk, is to simulate an MBR for it so that it can boot using a boot loader such as GRUB.<br />
<br />
For the following, suppose you have a plain, unmounted {{ic|/dev/hda''N''}} partition with some file system on it you wish to make part of a QEMU disk image. The trick is to dynamically prepend a master boot record (MBR) to the real partition you wish to embed in a QEMU raw disk image. More generally, the partition can be any part of a larger simulated disk, in particular a block device that simulates the original physical disk but only exposes {{ic|/dev/hda''N''}} to the virtual machine.<br />
<br />
A virtual disk of this type can be represented by a VMDK file that contains references to (a copy of) the MBR and the partition, but QEMU does not support this VMDK format. For instance, a virtual disk [https://www.virtualbox.org/manual/ch09.html#rawdisk created by]<br />
<br />
$ VBoxManage internalcommands createrawvmdk -filename ''/path/to/file.vmdk'' -rawdisk /dev/hda<br />
<br />
will be rejected by QEMU with the error message<br />
<br />
Unsupported image type 'partitionedDevice'<br />
<br />
Note that {{ic|VBoxManage}} creates two files, {{ic|''file.vmdk''}} and {{ic|''file-pt.vmdk''}}, the latter being a copy of the MBR, to which the text file {{ic|file.vmdk}} points. Read operations outside the target partition or the MBR would give zeros, while written data would be discarded.<br />
<br />
===== Using the device-mapper =====<br />
<br />
A method that is similar to the use of a VMDK descriptor file uses the [https://docs.kernel.org/admin-guide/device-mapper/index.html device-mapper] to prepend a loop device attached to the MBR file to the target partition. In case we do not need our virtual disk to have the same size as the original, we first create a file to hold the MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=2048<br />
<br />
Here, a 1 MiB (2048 * 512 bytes) file is created in accordance with partition alignment policies used by modern disk partitioning tools. For compatibility with older partitioning software, 63 sectors instead of 2048 might be required. The MBR only needs a single 512 bytes block, the additional free space can be used for a BIOS boot partition and, in the case of a hybrid partitioning scheme, for a GUID Partition Table. Then, we attach a loop device to the MBR file:<br />
<br />
{{hc|# losetup --show -f ''/path/to/mbr''|/dev/loop0}}<br />
<br />
In this example, the resulting device is {{ic|/dev/loop0}}. The device mapper is now used to join the MBR and the partition:<br />
<br />
# echo "0 2048 linear /dev/loop0 0<br />
2048 `blockdev --getsz /dev/hda''N''` linear /dev/hda''N'' 0" | dmsetup create qemu<br />
<br />
The resulting {{ic|/dev/mapper/qemu}} is what we will use as a QEMU raw disk image. Additional steps are required to create a partition table (see the section that describes the use of a linear RAID for an example) and boot loader code on the virtual disk (which will be stored in {{ic|''/path/to/mbr''}}).<br />
<br />
The following setup is an example where the position of {{ic|/dev/hda''N''}} on the virtual disk is to be the same as on the physical disk and the rest of the disk is hidden, except for the MBR, which is provided as a copy:<br />
<br />
# dd if=/dev/hda count=1 of=''/path/to/mbr''<br />
# loop=`losetup --show -f ''/path/to/mbr''`<br />
# start=`blockdev --report /dev/hda''N'' | tail -1 | awk '{print $5}'`<br />
# size=`blockdev --getsz /dev/hda''N''`<br />
# disksize=`blockdev --getsz /dev/hda`<br />
# echo "0 1 linear $loop 0<br />
1 $((start-1)) zero<br />
$start $size linear /dev/hda''N'' 0<br />
$((start+size)) $((disksize-start-size)) zero" | dmsetup create qemu<br />
<br />
The table provided as standard input to {{ic|dmsetup}} has a similar format as the table in a VDMK descriptor file produced by {{ic|VBoxManage}} and can alternatively be loaded from a file with {{ic|dmsetup create qemu --table ''table_file''}}. To the virtual machine, only {{ic|/dev/hda''N''}} is accessible, while the rest of the hard disk reads as zeros and discards written data, except for the first sector. We can print the table for {{ic|/dev/mapper/qemu}} with {{ic|dmsetup table qemu}} (use {{ic|udevadm info -rq name /sys/dev/block/''major'':''minor''}} to translate {{ic|''major'':''minor''}} to the corresponding {{ic|/dev/''blockdevice''}} name). Use {{ic|dmsetup remove qemu}} and {{ic|losetup -d $loop}} to delete the created devices.<br />
<br />
A situation where this example would be useful is an existing Windows XP installation in a multi-boot configuration and maybe a hybrid partitioning scheme (on the physical hardware, Windows XP could be the only operating system that uses the MBR partition table, while more modern operating systems installed on the same computer could use the GUID Partition Table). Windows XP supports hardware profiles, so that that the same installation can be used with different hardware configurations alternatingly (in this case bare metal vs. virtual) with Windows needing to install drivers for newly detected hardware only once for every profile. Note that in this example the boot loader code in the copied MBR needs to be updated to directly load Windows XP from {{ic|/dev/hda''N''}} instead of trying to start the multi-boot capable boot loader (like GRUB) present in the original system. Alternatively, a copy of the boot partition containing the boot loader installation can be included in the virtual disk the same way as the MBR.<br />
<br />
===== Using a linear RAID =====<br />
<br />
{{Out of date|[[Wikipedia:Cylinder-head-sector|CHS]] has been obsolete for decades.}}<br />
<br />
You can also do this using software [[RAID]] in linear mode (you need the {{ic|linear.ko}} kernel driver) and a loopback device: <br />
<br />
First, you create some small file to hold the MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=32<br />
<br />
Here, a 16 KiB (32 * 512 bytes) file is created. It is important not to make it too small (even if the MBR only needs a single 512 bytes block), since the smaller it will be, the smaller the chunk size of the software RAID device will have to be, which could have an impact on performance. Then, you setup a loopback device to the MBR file:<br />
<br />
# losetup -f ''/path/to/mbr''<br />
<br />
Let us assume the resulting device is {{ic|/dev/loop0}}, because we would not already have been using other loopbacks. Next step is to create the "merged" MBR + {{ic|/dev/hda''N''}} disk image using software RAID:<br />
<br />
# modprobe linear<br />
# mdadm --build --verbose /dev/md0 --chunk=16 --level=linear --raid-devices=2 /dev/loop0 /dev/hda''N''<br />
<br />
The resulting {{ic|/dev/md0}} is what you will use as a QEMU raw disk image (do not forget to set the permissions so that the emulator can access it). The last (and somewhat tricky) step is to set the disk configuration (disk geometry and partitions table) so that the primary partition start point in the MBR matches the one of {{ic|/dev/hda''N''}} inside {{ic|/dev/md0}} (an offset of exactly 16 * 512 = 16384 bytes in this example). Do this using {{ic|fdisk}} on the host machine, not in the emulator: the default raw disc detection routine from QEMU often results in non-kibibyte-roundable offsets (such as 31.5 KiB, as in the previous section) that cannot be managed by the software RAID code. Hence, from the host:<br />
<br />
# fdisk /dev/md0<br />
<br />
Press {{ic|X}} to enter the expert menu. Set number of 's'ectors per track so that the size of one cylinder matches the size of your MBR file. For two heads and a sector size of 512, the number of sectors per track should be 16, so we get cylinders of size 2x16x512=16k.<br />
<br />
Now, press {{ic|R}} to return to the main menu.<br />
<br />
Press {{ic|P}} and check that the cylinder size is now 16k.<br />
<br />
Now, create a single primary partition corresponding to {{ic|/dev/hda''N''}}. It should start at cylinder 2 and end at the end of the disk (note that the number of cylinders now differs from what it was when you entered fdisk.<br />
<br />
Finally, 'w'rite the result to the file: you are done. You now have a partition you can mount directly from your host, as well as part of a QEMU disk image:<br />
<br />
$ qemu-system-x86_64 -hdc /dev/md0 ''[...]''<br />
<br />
You can, of course, safely set any boot loader on this disk image using QEMU, provided the original {{ic|/dev/hda''N''}} partition contains the necessary tools.<br />
<br />
===== Using a Network Block Device =====<br />
<br />
With [https://docs.kernel.org/admin-guide/blockdev/nbd.html Network Block Device], Linux can use a remote server as one of its block device. You may use {{ic|nbd-server}} (from the {{Pkg|nbd}} package) to create an MBR wrapper for QEMU.<br />
<br />
Assuming you have already set up your MBR wrapper file like above, rename it to {{ic|wrapper.img.0}}. Then create a symbolic link named {{ic|wrapper.img.1}} in the same directory, pointing to your partition. Then put the following script in the same directory:<br />
<br />
{{bc|1=<br />
#!/bin/sh<br />
dir="$(realpath "$(dirname "$0")")"<br />
cat >wrapper.conf <<EOF<br />
[generic]<br />
allowlist = true<br />
listenaddr = 127.713705<br />
port = 10809<br />
<br />
[wrap]<br />
exportname = $dir/wrapper.img<br />
multifile = true<br />
EOF<br />
<br />
nbd-server \<br />
-C wrapper.conf \<br />
-p wrapper.pid \<br />
"$@"<br />
}}<br />
<br />
The {{ic|.0}} and {{ic|.1}} suffixes are essential; the rest can be changed. After running the above script (which you may need to do as root to make sure nbd-server is able to access the partition), you can launch QEMU with:<br />
<br />
qemu-system-x86_64 -drive file=nbd:127.713705:10809:exportname=wrap ''[...]''<br />
<br />
=== Using an entire physical disk device inside the virtual machine ===<br />
<br />
{{Style|Duplicates [[#Using any real partition as the single primary partition of a hard disk image]], libvirt instructions do not belong to this page.}}<br />
<br />
You may have a second disk with a different OS (like Windows) on it and may want to gain the ability to also boot it inside a virtual machine.<br />
Since the disk access is raw, the disk will perform quite well inside the virtual machine.<br />
<br />
==== Windows virtual machine boot prerequisites ====<br />
<br />
Be sure to install the [https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/archive-virtio/ virtio drivers] inside the OS on that disk before trying to boot it in the virtual machine.<br />
For Win 7 use version [https://askubuntu.com/questions/1310440/using-virtio-win-drivers-with-win7-sp1-x64 0.1.173-4].<br />
Some singular drivers from newer virtio builds may be used on Win 7 but you will have to install them manually via device manager.<br />
For Win 10 you can use the latest virtio build.<br />
<br />
===== Set up the windows disk interface drivers =====<br />
<br />
You may get a {{ic|0x0000007B}} bluescreen when trying to boot the virtual machine. This means Windows can not access the drive during the early boot stage because the disk interface driver it would need for that is not loaded / is set to start manually.<br />
<br />
The solution is to [https://superuser.com/a/1032769 enable these drivers to start at boot].<br />
<br />
In {{ic|HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services}}, find the folders {{ic|aliide, amdide, atapi, cmdide, iastor (may not exist), iastorV, intelide, LSI_SAS, msahci, pciide and viaide}}.<br />
Inside each of those, set all their "start" values to 0 in order to enable them at boot.<br />
If your drive is a PCIe NVMe drive, also enable that driver (should it exist).<br />
<br />
==== Find the unique path of your disk ====<br />
<br />
Run {{ic|ls /dev/disk/by-id/}}: tere you pick out the ID of the drive you want to insert into the virtual machine, for example {{ic|ata-TS512GMTS930L_C199211383}}.<br />
Now add that ID to {{ic|/dev/disk/by-id/}} so you get {{ic|/dev/disk/by-id/ata-TS512GMTS930L_C199211383}}.<br />
That is the unique path to that disk.<br />
<br />
==== Add the disk in QEMU CLI ====<br />
<br />
In QEMU CLI that would probably be:<br />
<br />
{{ic|1=-drive file=/dev/disk/by-id/ata-TS512GMTS930L_C199211383,format=raw,media=disk}}<br />
<br />
Just modify {{ic|file{{=}}}} to be the unique path of your drive.<br />
<br />
==== Add the disk in libvirt ====<br />
<br />
In libvirt XML that translates to<br />
<br />
{{hc|$ virsh edit ''vmname''|<nowiki><br />
...<br />
<disk type="block" device="disk"><br />
<driver name="qemu" type="raw" cache="none" io="native"/><br />
<source dev="/dev/disk/by-id/ata-TS512GMTS930L_C199211383"/><br />
<target dev="sda" bus="sata"/><br />
<address type="drive" controller="0" bus="0" target="0" unit="0"/><br />
</disk><br />
...<br />
</nowiki>}}<br />
<br />
Just modify "source dev" to be the unique path of your drive.<br />
<br />
==== Add the disk in virt-manager ====<br />
<br />
When creating a virtual machine, select "import existing drive" and just paste that unique path.<br />
If you already have the virtual machine, add a device, storage, then select or create custom storage.<br />
Now paste the unique path.<br />
<br />
== Networking ==<br />
<br />
{{Style|Network topologies (sections [[#Host-only networking]], [[#Internal networking]] and info spread out across other sections) should not be described alongside the various virtual interfaces implementations, such as [[#User-mode networking]], [[#Tap networking with QEMU]], [[#Networking with VDE2]].}}<br />
<br />
The performance of virtual networking should be better with tap devices and bridges than with user-mode networking or vde because tap devices and bridges are implemented in-kernel.<br />
<br />
In addition, networking performance can be improved by assigning virtual machines a [https://wiki.libvirt.org/page/Virtio virtio] network device rather than the default emulation of an e1000 NIC. See [[#Installing virtio drivers]] for more information.<br />
<br />
=== Link-level address caveat ===<br />
<br />
By giving the {{ic|-net nic}} argument to QEMU, it will, by default, assign a virtual machine a network interface with the link-level address {{ic|52:54:00:12:34:56}}. However, when using bridged networking with multiple virtual machines, it is essential that each virtual machine has a unique link-level (MAC) address on the virtual machine side of the tap device. Otherwise, the bridge will not work correctly, because it will receive packets from multiple sources that have the same link-level address. This problem occurs even if the tap devices themselves have unique link-level addresses because the source link-level address is not rewritten as packets pass through the tap device.<br />
<br />
Make sure that each virtual machine has a unique link-level address, but it should always start with {{ic|52:54:}}. Use the following option, replace ''X'' with arbitrary hexadecimal digit:<br />
<br />
$ qemu-system-x86_64 -net nic,macaddr=52:54:''XX:XX:XX:XX'' -net vde ''disk_image''<br />
<br />
Generating unique link-level addresses can be done in several ways:<br />
<br />
* Manually specify unique link-level address for each NIC. The benefit is that the DHCP server will assign the same IP address each time the virtual machine is run, but it is unusable for large number of virtual machines.<br />
* Generate random link-level address each time the virtual machine is run. Practically zero probability of collisions, but the downside is that the DHCP server will assign a different IP address each time. You can use the following command in a script to generate random link-level address in a {{ic|macaddr}} variable:<br />
<br />
{{bc|1=<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
qemu-system-x86_64 -net nic,macaddr="$macaddr" -net vde ''disk_image''<br />
}}<br />
<br />
* Use the following script {{ic|qemu-mac-hasher.py}} to generate the link-level address from the virtual machine name using a hashing function. Given that the names of virtual machines are unique, this method combines the benefits of the aforementioned methods: it generates the same link-level address each time the script is run, yet it preserves the practically zero probability of collisions.<br />
<br />
{{hc|qemu-mac-hasher.py|2=<br />
#!/usr/bin/env python<br />
# usage: qemu-mac-hasher.py <VMName><br />
<br />
import sys<br />
import zlib<br />
<br />
crc = str(hex(zlib.crc32(sys.argv[1].encode("utf-8")))).replace("x", "")[-8:]<br />
print("52:54:%s%s:%s%s:%s%s:%s%s" % tuple(crc))<br />
}}<br />
<br />
In a script, you can use for example:<br />
<br />
vm_name="''VM Name''"<br />
qemu-system-x86_64 -name "$vm_name" -net nic,macaddr=$(qemu-mac-hasher.py "$vm_name") -net vde ''disk_image''<br />
<br />
=== User-mode networking ===<br />
<br />
By default, without any {{ic|-netdev}} arguments, QEMU will use user-mode networking with a built-in DHCP server. Your virtual machines will be assigned an IP address when they run their DHCP client, and they will be able to access the physical host's network through IP masquerading done by QEMU.<br />
<br />
{{Note|ICMPv6 will not work, as support for it is not implemented: {{ic|Slirp: external icmpv6 not supported yet}}. [[Ping]]ing an IPv6 address will not work.}}<br />
<br />
This default configuration allows your virtual machines to easily access the Internet, provided that the host is connected to it, but the virtual machines will not be directly visible on the external network, nor will virtual machines be able to talk to each other if you start up more than one concurrently.<br />
<br />
QEMU's user-mode networking can offer more capabilities such as built-in TFTP or SMB servers, redirecting host ports to the guest (for example to allow SSH connections to the guest) or attaching guests to VLANs so that they can talk to each other. See the QEMU documentation on the {{ic|-net user}} flag for more details.<br />
<br />
However, user-mode networking has limitations in both utility and performance. More advanced network configurations require the use of tap devices or other methods.<br />
<br />
{{Note|If the host system uses [[systemd-networkd]], make sure to symlink the {{ic|/etc/resolv.conf}} file as described in [[systemd-networkd#Required services and setup]], otherwise the DNS lookup in the guest system will not work.}}<br />
<br />
{{Tip|<br />
* To use the virtio driver with user-mode networking, the option is: {{ic|1=-nic user,model=virtio-net-pci}}.<br />
* You can isolate user-mode networking from the host and the outside world by adding {{ic|1=restrict=y}}, for example: {{ic|1=-net user,restrict=y}}<br />
}}<br />
<br />
=== Tap networking with QEMU ===<br />
<br />
[[wikipedia:TUN/TAP|Tap devices]] are a Linux kernel feature that allows you to create virtual network interfaces that appear as real network interfaces. Packets sent to a tap interface are delivered to a userspace program, such as QEMU, that has bound itself to the interface.<br />
<br />
QEMU can use tap networking for a virtual machine so that packets sent to the tap interface will be sent to the virtual machine and appear as coming from a network interface (usually an Ethernet interface) in the virtual machine. Conversely, everything that the virtual machine sends through its network interface will appear on the tap interface.<br />
<br />
Tap devices are supported by the Linux bridge drivers, so it is possible to bridge together tap devices with each other and possibly with other host interfaces such as {{ic|eth0}}. This is desirable if you want your virtual machines to be able to talk to each other, or if you want other machines on your LAN to be able to talk to the virtual machines.<br />
<br />
{{Warning|If you bridge together tap device and some host interface, such as {{ic|eth0}}, your virtual machines will appear directly on the external network, which will expose them to possible attack. Depending on what resources your virtual machines have access to, you may need to take all the [[Firewalls|precautions]] you normally would take in securing a computer to secure your virtual machines. If the risk is too great, virtual machines have little resources or you set up multiple virtual machines, a better solution might be to use [[#Host-only networking|host-only networking]] and set up NAT. In this case you only need one firewall on the host instead of multiple firewalls for each guest.}}<br />
<br />
As indicated in the user-mode networking section, tap devices offer higher networking performance than user-mode. If the guest OS supports virtio network driver, then the networking performance will be increased considerably as well. Supposing the use of the tap0 device, that the virtio driver is used on the guest, and that no scripts are used to help start/stop networking, next is part of the qemu command one should see:<br />
<br />
-device virtio-net,netdev=network0 -netdev tap,id=network0,ifname=tap0,script=no,downscript=no<br />
<br />
But if already using a tap device with virtio networking driver, one can even boost the networking performance by enabling vhost, like:<br />
<br />
-device virtio-net,netdev=network0 -netdev tap,id=network0,ifname=tap0,script=no,downscript=no,vhost=on<br />
<br />
See [https://web.archive.org/web/20160222161955/http://www.linux-kvm.com:80/content/how-maximize-virtio-net-performance-vhost-net] for more information.<br />
<br />
==== Host-only networking ====<br />
<br />
If the bridge is given an IP address and traffic destined for it is allowed, but no real interface (e.g. {{ic|eth0}}) is connected to the bridge, then the virtual machines will be able to talk to each other and the host system. However, they will not be able to talk to anything on the external network, provided that you do not set up IP masquerading on the physical host. This configuration is called ''host-only networking'' by other virtualization software such as [[VirtualBox]].<br />
<br />
{{Tip|<br />
* If you want to set up IP masquerading, e.g. NAT for virtual machines, see the [[Internet sharing#Enable NAT]] page.<br />
* See [[Network bridge]] for information on creating bridge.<br />
* You may want to have a DHCP server running on the bridge interface to service the virtual network. For example, to use the {{ic|172.20.0.1/16}} subnet with [[dnsmasq]] as the DHCP server:<br />
<br />
{{bc|1=<br />
# ip addr add 172.20.0.1/16 dev br0<br />
# ip link set br0 up<br />
# dnsmasq --interface=br0 --bind-interfaces --dhcp-range=172.20.0.2,172.20.255.254<br />
}}<br />
}}<br />
<br />
==== Internal networking ====<br />
<br />
If you do not give the bridge an IP address and add an [[iptables]] rule to drop all traffic to the bridge in the INPUT chain, then the virtual machines will be able to talk to each other, but not to the physical host or to the outside network. This configuration is called ''internal networking'' by other virtualization software such as [[VirtualBox]]. You will need to either assign static IP addresses to the virtual machines or run a DHCP server on one of them.<br />
<br />
By default iptables would drop packets in the bridge network. You may need to use such iptables rule to allow packets in a bridged network:<br />
<br />
# iptables -I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Bridged networking using qemu-bridge-helper ====<br />
<br />
This method does not require a start-up script and readily accommodates multiple taps and multiple bridges. It uses {{ic|/usr/lib/qemu/qemu-bridge-helper}} binary, which allows creating tap devices on an existing bridge.<br />
<br />
{{Tip|<br />
* See [[Network bridge]] for information on creating bridge.<br />
* See https://wiki.qemu.org/Features/HelperNetworking for more information on QEMU's network helper.<br />
}}<br />
<br />
First, create a configuration file containing the names of all bridges to be used by QEMU:<br />
<br />
{{hc|/etc/qemu/bridge.conf|<br />
allow ''br0''<br />
allow ''br1''<br />
...}}<br />
<br />
Make sure {{ic|/etc/qemu/}} has {{ic|755}} [[permissions]]. [https://gitlab.com/qemu-project/qemu/-/issues/515 QEMU issues] and [https://www.gns3.com/community/discussions/gns3-cannot-work-with-qemu GNS3 issues] may arise if this is not the case.<br />
<br />
Now start the virtual machine; the most basic usage to run QEMU with the default network helper and default bridge {{ic|br0}}:<br />
<br />
$ qemu-system-x86_64 -nic bridge ''[...]''<br />
<br />
Using the bridge {{ic|br1}} and the virtio driver:<br />
<br />
$ qemu-system-x86_64 -nic bridge,br=''br1'',model=virtio-net-pci ''[...]''<br />
<br />
==== Creating bridge manually ====<br />
<br />
{{Style|This section needs serious cleanup and may contain out-of-date information.}}<br />
<br />
{{Tip|Since QEMU 1.1, the [https://wiki.qemu.org/Features/HelperNetworking network bridge helper] can set tun/tap up for you without the need for additional scripting. See [[#Bridged networking using qemu-bridge-helper]].}}<br />
<br />
The following describes how to bridge a virtual machine to a host interface such as {{ic|eth0}}, which is probably the most common configuration. This configuration makes it appear that the virtual machine is located directly on the external network, on the same Ethernet segment as the physical host machine.<br />
<br />
We will replace the normal Ethernet adapter with a bridge adapter and bind the normal Ethernet adapter to it.<br />
<br />
* Install {{Pkg|bridge-utils}}, which provides {{ic|brctl}} to manipulate bridges.<br />
<br />
* Enable IPv4 forwarding:<br />
<br />
# sysctl -w net.ipv4.ip_forward=1<br />
<br />
To make the change permanent, change {{ic|1=net.ipv4.ip_forward = 0}} to {{ic|1=net.ipv4.ip_forward = 1}} in {{ic|/etc/sysctl.d/99-sysctl.conf}}.<br />
<br />
* Load the {{ic|tun}} module and configure it to be loaded on boot. See [[Kernel modules]] for details.<br />
<br />
* Optionally create the bridge. See [[Bridge with netctl]] for details. Remember to name your bridge as {{ic|br0}}, or change the scripts below to your bridge's name. In the {{ic|run-qemu}} script below, {{ic|br0}} is set up if not listed, as it is assumed that by default the host is not accessing network via the bridge.<br />
<br />
* Create the script that QEMU uses to bring up the tap adapter with {{ic|root:kvm}} 750 permissions:<br />
<br />
{{hc|/etc/qemu-ifup|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifup"<br />
echo "Bringing up $1 for bridged mode..."<br />
sudo /usr/bin/ip link set $1 up promisc on<br />
echo "Adding $1 to br0..."<br />
sudo /usr/bin/brctl addif br0 $1<br />
sleep 2<br />
</nowiki>}}<br />
<br />
* Create the script that QEMU uses to bring down the tap adapter in {{ic|/etc/qemu-ifdown}} with {{ic|root:kvm}} 750 permissions:<br />
{{hc|/etc/qemu-ifdown|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifdown"<br />
sudo /usr/bin/ip link set $1 down<br />
sudo /usr/bin/brctl delif br0 $1<br />
sudo /usr/bin/ip link delete dev $1<br />
</nowiki>}}<br />
<br />
* Use {{ic|visudo}} to add the following to your {{ic|sudoers}} file:<br />
<br />
{{bc|<nowiki><br />
Cmnd_Alias QEMU=/usr/bin/ip,/usr/bin/modprobe,/usr/bin/brctl<br />
%kvm ALL=NOPASSWD: QEMU<br />
</nowiki>}}<br />
<br />
* You launch QEMU using the following {{ic|run-qemu}} script:<br />
<br />
{{hc|run-qemu|<nowiki><br />
#!/bin/bash<br />
: '<br />
e.g. with img created via:<br />
qemu-img create -f qcow2 example.img 90G<br />
run-qemu -cdrom archlinux-x86_64.iso -boot order=d -drive file=example.img,format=qcow2 -m 4G -enable-kvm -cpu host -smp 4<br />
run-qemu -drive file=example.img,format=qcow2 -m 4G -enable-kvm -cpu host -smp 4<br />
'<br />
<br />
nicbr0() {<br />
sudo ip link set dev $1 promisc on up &> /dev/null<br />
sudo ip addr flush dev $1 scope host &>/dev/null<br />
sudo ip addr flush dev $1 scope site &>/dev/null<br />
sudo ip addr flush dev $1 scope global &>/dev/null<br />
sudo ip link set dev $1 master br0 &> /dev/null<br />
}<br />
_nicbr0() {<br />
sudo ip link set $1 promisc off down &> /dev/null<br />
sudo ip link set dev $1 nomaster &> /dev/null<br />
}<br />
<br />
HASBR0="$( ip link show | grep br0 )"<br />
if [ -z $HASBR0 ] ; then<br />
ROUTER="192.168.1.1"<br />
SUBNET="192.168.1."<br />
NIC=$(ip link show | grep en | grep 'state UP' | head -n 1 | cut -d":" -f 2 | xargs)<br />
IPADDR=$(ip addr show | grep -o "inet $SUBNET\([0-9]*\)" | cut -d ' ' -f2)<br />
sudo ip link add name br0 type bridge &> /dev/null<br />
sudo ip link set dev br0 up<br />
sudo ip addr add $IPADDR/24 brd + dev br0<br />
sudo ip route del default &> /dev/null<br />
sudo ip route add default via $ROUTER dev br0 onlink<br />
nicbr0 $NIC<br />
sudo iptables -I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
fi<br />
<br />
USERID=$(whoami)<br />
precreationg=$(ip tuntap list | cut -d: -f1 | sort)<br />
sudo ip tuntap add user $USERID mode tap<br />
postcreation=$(ip tuntap list | cut -d: -f1 | sort)<br />
TAP=$(comm -13 <(echo "$precreationg") <(echo "$postcreation"))<br />
nicbr0 $TAP<br />
<br />
printf -v MACADDR "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
qemu-system-x86_64 -net nic,macaddr=$MACADDR,model=virtio \<br />
-net tap,ifname=$TAP,script=no,downscript=no,vhost=on \<br />
$@<br />
<br />
_nicbr0 $TAP<br />
sudo ip link set dev $TAP down &> /dev/null<br />
sudo ip tuntap del $TAP mode tap<br />
<br />
if [ -z $HASBR0 ] ; then<br />
_nicbr0 $NIC<br />
sudo ip addr del dev br0 $IPADDR/24 &> /dev/null<br />
sudo ip link set dev br0 down<br />
sudo ip link delete br0 type bridge &> /dev/null<br />
sudo ip route del default &> /dev/null<br />
sudo ip link set dev $NIC up<br />
sudo ip route add default via $ROUTER dev $NIC onlink &> /dev/null<br />
fi<br />
</nowiki>}}<br />
<br />
Then to launch a virtual machine, do something like this<br />
<br />
$ run-qemu -hda ''myvm.img'' -m 512<br />
<br />
* It is recommended for performance and security reasons to disable the [http://ebtables.netfilter.org/documentation/bridge-nf.html firewall on the bridge]:<br />
<br />
{{hc|/etc/sysctl.d/10-disable-firewall-on-bridge.conf|<nowiki><br />
net.bridge.bridge-nf-call-ip6tables = 0<br />
net.bridge.bridge-nf-call-iptables = 0<br />
net.bridge.bridge-nf-call-arptables = 0<br />
</nowiki>}}<br />
<br />
In order to apply the parameters described above on boot, you will also need to load the br-netfilter module on boot. Otherwise, the parameters will not exist when sysctl will try to modify them.<br />
<br />
{{hc|/etc/modules-load.d/br_netfilter.conf|<nowiki><br />
br_netfilter<br />
</nowiki>}}<br />
<br />
Run {{ic|sysctl -p /etc/sysctl.d/10-disable-firewall-on-bridge.conf}} to apply the changes immediately.<br />
<br />
See the [https://wiki.libvirt.org/page/Networking#Creating_network_initscripts libvirt wiki] and [https://bugzilla.redhat.com/show_bug.cgi?id=512206 Fedora bug 512206]. If you get errors by sysctl during boot about non-existing files, make the {{ic|bridge}} module load at boot. See [[Kernel module#systemd]].<br />
<br />
Alternatively, you can configure [[iptables]] to allow all traffic to be forwarded across the bridge by adding a rule like this:<br />
<br />
-I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Network sharing between physical device and a Tap device through iptables ====<br />
<br />
{{Merge|Internet_sharing|Duplication, not specific to QEMU.}}<br />
<br />
Bridged networking works fine between a wired interface (Eg. eth0), and it is easy to setup. However if the host gets connected to the network through a wireless device, then bridging is not possible.<br />
<br />
See [[Network bridge#Wireless interface on a bridge]] as a reference.<br />
<br />
One way to overcome that is to setup a tap device with a static IP, making linux automatically handle the routing for it, and then forward traffic between the tap interface and the device connected to the network through iptables rules.<br />
<br />
See [[Internet sharing]] as a reference.<br />
<br />
There you can find what is needed to share the network between devices, included tap and tun ones. The following just hints further on some of the host configurations required. As indicated in the reference above, the client needs to be configured for a static IP, using the IP assigned to the tap interface as the gateway. The caveat is that the DNS servers on the client might need to be manually edited if they change when changing from one host device connected to the network to another.<br />
<br />
To allow IP forwarding on every boot, one need to add the following lines to sysctl configuration file inside {{ic|/etc/sysctl.d}}:<br />
<br />
net.ipv4.ip_forward = 1<br />
net.ipv6.conf.default.forwarding = 1<br />
net.ipv6.conf.all.forwarding = 1<br />
<br />
The iptables rules can look like:<br />
<br />
# Forwarding from/to outside<br />
iptables -A FORWARD -i ${INT} -o ${EXT_0} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_1} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_2} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_0} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_1} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_2} -o ${INT} -j ACCEPT<br />
# NAT/Masquerade (network address translation)<br />
iptables -t nat -A POSTROUTING -o ${EXT_0} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_1} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_2} -j MASQUERADE<br />
<br />
The prior supposes there are 3 devices connected to the network sharing traffic with one internal device, where for example:<br />
<br />
INT=tap0<br />
EXT_0=eth0<br />
EXT_1=wlan0<br />
EXT_2=tun0<br />
<br />
The prior shows a forwarding that would allow sharing wired and wireless connections with the tap device.<br />
<br />
The forwarding rules shown are stateless, and for pure forwarding. One could think of restricting specific traffic, putting a firewall in place to protect the guest and others. However those would decrease the networking performance, while a simple bridge does not include any of that.<br />
<br />
Bonus: Whether the connection is wired or wireless, if one gets connected through VPN to a remote site with a tun device, supposing the tun device opened for that connection is tun0, and the prior iptables rules are applied, then the remote connection gets also shared with the guest. This avoids the need for the guest to also open a VPN connection. Again, as the guest networking needs to be static, then if connecting the host remotely this way, one most probably will need to edit the DNS servers on the guest.<br />
<br />
=== Networking with VDE2 ===<br />
<br />
{{Style|This section needs serious cleanup and may contain out-of-date information.}}<br />
<br />
==== What is VDE? ====<br />
<br />
VDE stands for Virtual Distributed Ethernet. It started as an enhancement of [[User-mode Linux|uml]]_switch. It is a toolbox to manage virtual networks.<br />
<br />
The idea is to create virtual switches, which are basically sockets, and to "plug" both physical and virtual machines in them. The configuration we show here is quite simple; However, VDE is much more powerful than this, it can plug virtual switches together, run them on different hosts and monitor the traffic in the switches. You are invited to read [https://wiki.virtualsquare.org/ the documentation of the project].<br />
<br />
The advantage of this method is you do not have to add sudo privileges to your users. Regular users should not be allowed to run modprobe.<br />
<br />
==== Basics ====<br />
<br />
VDE support can be [[install]]ed via the {{Pkg|vde2}} package.<br />
<br />
In our config, we use tun/tap to create a virtual interface on my host. Load the {{ic|tun}} module (see [[Kernel modules]] for details):<br />
<br />
# modprobe tun<br />
<br />
Now create the virtual switch:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
<br />
This line creates the switch, creates {{ic|tap0}}, "plugs" it, and allows the users of the group {{ic|users}} to use it.<br />
<br />
The interface is plugged in but not configured yet. To configure it, run this command:<br />
<br />
# ip addr add 192.168.100.254/24 dev tap0<br />
<br />
Now, you just have to run KVM with these {{ic|-net}} options as a normal user:<br />
<br />
$ qemu-system-x86_64 -net nic -net vde -hda ''[...]''<br />
<br />
Configure networking for your guest as you would do in a physical network.<br />
<br />
{{Tip|You might want to set up NAT on tap device to access the internet from the virtual machine. See [[Internet sharing#Enable NAT]] for more information.}}<br />
<br />
==== Startup scripts ====<br />
<br />
Example of main script starting VDE:<br />
<br />
{{hc|/etc/systemd/scripts/qemu-network-env|<nowiki><br />
#!/bin/sh<br />
# QEMU/VDE network environment preparation script<br />
<br />
# The IP configuration for the tap device that will be used for<br />
# the virtual machine network:<br />
<br />
TAP_DEV=tap0<br />
TAP_IP=192.168.100.254<br />
TAP_MASK=24<br />
TAP_NETWORK=192.168.100.0<br />
<br />
# Host interface<br />
NIC=eth0<br />
<br />
case "$1" in<br />
start)<br />
echo -n "Starting VDE network for QEMU: "<br />
<br />
# If you want tun kernel module to be loaded by script uncomment here<br />
#modprobe tun 2>/dev/null<br />
## Wait for the module to be loaded<br />
#while ! lsmod | grep -q "^tun"; do echo "Waiting for tun device"; sleep 1; done<br />
<br />
# Start tap switch<br />
vde_switch -tap "$TAP_DEV" -daemon -mod 660 -group users<br />
<br />
# Bring tap interface up<br />
ip address add "$TAP_IP"/"$TAP_MASK" dev "$TAP_DEV"<br />
ip link set "$TAP_DEV" up<br />
<br />
# Start IP Forwarding<br />
echo "1" > /proc/sys/net/ipv4/ip_forward<br />
iptables -t nat -A POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
;;<br />
stop)<br />
echo -n "Stopping VDE network for QEMU: "<br />
# Delete the NAT rules<br />
iptables -t nat -D POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
<br />
# Bring tap interface down<br />
ip link set "$TAP_DEV" down<br />
<br />
# Kill VDE switch<br />
pgrep vde_switch | xargs kill -TERM<br />
;;<br />
restart|reload)<br />
$0 stop<br />
sleep 1<br />
$0 start<br />
;;<br />
*)<br />
echo "Usage: $0 {start|stop|restart|reload}"<br />
exit 1<br />
esac<br />
exit 0<br />
</nowiki>}}<br />
<br />
Example of systemd service using the above script:<br />
<br />
{{hc|/etc/systemd/system/qemu-network-env.service|<nowiki><br />
[Unit]<br />
Description=Manage VDE Switch<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/etc/systemd/scripts/qemu-network-env start<br />
ExecStop=/etc/systemd/scripts/qemu-network-env stop<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
Change permissions for {{ic|qemu-network-env}} to be [[executable]]. <br />
<br />
You can [[start]] {{ic|qemu-network-env.service}} as usual.<br />
<br />
==== Alternative method ====<br />
<br />
If the above method does not work or you do not want to mess with kernel configs, TUN, dnsmasq, and iptables you can do the following for the same result.<br />
<br />
# vde_switch -daemon -mod 660 -group users<br />
# slirpvde --dhcp --daemon<br />
<br />
Then, to start the virtual machine with a connection to the network of the host:<br />
<br />
$ qemu-system-x86_64 -net nic,macaddr=52:54:00:00:EE:03 -net vde ''disk_image''<br />
<br />
=== VDE2 Bridge ===<br />
<br />
Based on [https://selamatpagicikgu.wordpress.com/2011/06/08/quickhowto-qemu-networking-using-vde-tuntap-and-bridge/ quickhowto: qemu networking using vde, tun/tap, and bridge] graphic. Any virtual machine connected to vde is externally exposed. For example, each virtual machine can receive DHCP configuration directly from your ADSL router.<br />
<br />
==== Basics ====<br />
<br />
Remember that you need {{ic|tun}} module and {{Pkg|bridge-utils}} package.<br />
<br />
Create the vde2/tap device:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
# ip link set tap0 up<br />
<br />
Create bridge:<br />
<br />
# brctl addbr br0<br />
<br />
Add devices:<br />
<br />
# brctl addif br0 eth0<br />
# brctl addif br0 tap0<br />
<br />
And configure bridge interface:<br />
<br />
# dhcpcd br0<br />
<br />
==== Startup scripts ====<br />
<br />
All devices must be set up. And only the bridge needs an IP address. For physical devices on the bridge (e.g. {{ic|eth0}}), this can be done with [[netctl]] using a custom Ethernet profile with:<br />
<br />
{{hc|/etc/netctl/ethernet-noip|2=<br />
Description='A more versatile static Ethernet connection'<br />
Interface=eth0<br />
Connection=ethernet<br />
IP=no<br />
}}<br />
<br />
The following custom systemd service can be used to create and activate a VDE2 tap interface for users in the {{ic|users}} user group.<br />
<br />
{{hc|/etc/systemd/system/vde2@.service|2=<br />
[Unit]<br />
Description=Network Connectivity for %i<br />
Wants=network.target<br />
Before=network.target<br />
<br />
[Service]<br />
Type=oneshot<br />
RemainAfterExit=yes<br />
ExecStart=/usr/bin/vde_switch -tap %i -daemon -mod 660 -group users<br />
ExecStart=/usr/bin/ip link set dev %i up<br />
ExecStop=/usr/bin/ip addr flush dev %i<br />
ExecStop=/usr/bin/ip link set dev %i down<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
}}<br />
<br />
And finally, you can create the [[Bridge with netctl|bridge interface with netctl]].<br />
<br />
=== Shorthand configuration ===<br />
<br />
If you are using QEMU with various networking options a lot, you probably have created a lot of {{ic|-netdev}} and {{ic|-device}} argument pairs, which gets quite repetitive. You can instead use the {{ic|-nic}} argument to combine {{ic|-netdev}} and {{ic|-device}} together, so that, for example, these arguments:<br />
<br />
-netdev tap,id=network0,ifname=tap0,script=no,downscript=no,vhost=on -device virtio-net-pci,netdev=network0<br />
<br />
become:<br />
<br />
-nic tap,script=no,downscript=no,vhost=on,model=virtio-net-pci<br />
<br />
Notice the lack of network IDs, and that the device was created with {{ic|1=model=}}. The first half of the {{ic|-nic}} parameters are {{ic|-netdev}} parameters, whereas the second half (after {{ic|1=model=}}) are related with the device. The same parameters (for example, {{ic|1=smb=}}) are used. To completely disable the networking use {{ic|-nic none}}.<br />
<br />
See [https://qemu.weilnetz.de/doc/6.0/system/net.html QEMU networking documentation] for more information on parameters you can use.<br />
<br />
== Graphic card ==<br />
<br />
QEMU can emulate a standard graphic card text mode using {{ic|-display curses}} command line option. This allows to type text and see text output directly inside a text terminal. Alternatively, {{ic|-nographic}} serves a similar purpose.<br />
<br />
QEMU can emulate several types of VGA card. The card type is passed in the {{ic|-vga ''type''}} command line option and can be {{ic|std}}, {{ic|qxl}}, {{ic|vmware}}, {{ic|virtio}}, {{ic|cirrus}} or {{ic|none}}.<br />
<br />
=== std ===<br />
<br />
With {{ic|-vga std}} you can get a resolution of up to 2560 x 1600 pixels without requiring guest drivers. This is the default since QEMU 2.2.<br />
<br />
=== qxl ===<br />
<br />
QXL is a paravirtual graphics driver with 2D support. To use it, pass the {{ic|-vga qxl}} option and install drivers in the guest. You may want to use [[#SPICE]] for improved graphical performance when using QXL.<br />
<br />
On Linux guests, the {{ic|qxl}} and {{ic|bochs_drm}} kernel modules must be loaded in order to gain a decent performance.<br />
<br />
Default VGA memory size for QXL devices is 16M which is sufficient to drive resolutions approximately up to QHD (2560x1440). To enable higher resolutions, [[#Multi-monitor support|increase vga_memmb]].<br />
<br />
=== vmware ===<br />
<br />
Although it is a bit buggy, it performs better than std and cirrus. Install the VMware drivers {{Pkg|xf86-video-vmware}} and {{Pkg|xf86-input-vmmouse}} for Arch Linux guests.<br />
<br />
=== virtio ===<br />
<br />
{{ic|virtio-vga}} / {{ic|virtio-gpu}} is a paravirtual 3D graphics driver based on [https://virgil3d.github.io/ virgl]. It's mature, currently supporting only Linux guests with {{Pkg|mesa}} compiled with the option {{ic|1=gallium-drivers=virgl}}.<br />
<br />
To enable 3D acceleration on the guest system, select this vga with {{ic|-device virtio-vga-gl}} and enable the OpenGL context in the display device with {{ic|1=-display sdl,gl=on}} or {{ic|1=-display gtk,gl=on}} for the SDL and GTK display output respectively. Successful configuration can be confirmed looking at the kernel log in the guest:<br />
<br />
{{hc|# dmesg {{!}} grep drm |<br />
[drm] pci: virtio-vga detected<br />
[drm] virgl 3d acceleration enabled<br />
}}<br />
<br />
=== cirrus ===<br />
<br />
The cirrus graphical adapter was the default [https://wiki.qemu.org/ChangeLog/2.2#VGA before 2.2]. It [https://www.kraxel.org/blog/2014/10/qemu-using-cirrus-considered-harmful/ should not] be used on modern systems.<br />
<br />
=== none ===<br />
<br />
This is like a PC that has no VGA card at all. You would not even be able to access it with the {{ic|-vnc}} option. Also, this is different from the {{ic|-nographic}} option which lets QEMU emulate a VGA card, but disables the SDL display.<br />
<br />
== SPICE ==<br />
<br />
The [https://www.spice-space.org/ SPICE project] aims to provide a complete open source solution for remote access to virtual machines in a seamless way.<br />
<br />
=== Enabling SPICE support on the host ===<br />
<br />
The following is an example of booting with SPICE as the remote desktop protocol, including the support for copy and paste from host:<br />
<br />
$ qemu-system-x86_64 -vga qxl -device virtio-serial-pci -spice port=5930,disable-ticketing=on -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
The parameters have the following meaning:<br />
<br />
# {{ic|-device virtio-serial-pci}} adds a virtio-serial device<br />
# {{ic|1=-spice port=5930,disable-ticketing=on}} set TCP port {{ic|5930}} for spice channels listening and allow client to connect without authentication{{Tip|Using [[wikipedia:Unix_socket|Unix sockets]] instead of TCP ports does not involve using network stack on the host system. It does not imply that packets are encapsulated and decapsulated to use the network and the related protocol. The sockets are identified solely by the inodes on the hard drive. It is therefore considered better for performance. Use instead {{ic|1=-spice unix=on,addr=/tmp/vm_spice.socket,disable-ticketing=on}}.}}<br />
# {{ic|1=-device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0}} opens a port for spice vdagent in the virtio-serial device,<br />
# {{ic|1=-chardev spicevmc,id=spicechannel0,name=vdagent}} adds a spicevmc chardev for that port. It is important that the {{ic|1=chardev=}} option of the {{ic|virtserialport}} device matches the {{ic|1=id=}} option given to the {{ic|chardev}} option ({{ic|spicechannel0}} in this example). It is also important that the port name is {{ic|com.redhat.spice.0}}, because that is the namespace where vdagent is looking for in the guest. And finally, specify {{ic|1=name=vdagent}} so that spice knows what this channel is for.<br />
<br />
=== Connecting to the guest with a SPICE client ===<br />
<br />
A SPICE client is necessary to connect to the guest. In Arch, the following clients are available:<br />
<br />
* {{App|virt-viewer|SPICE client recommended by the protocol developers, a subset of the virt-manager project.|https://virt-manager.org/|{{Pkg|virt-viewer}}}}<br />
* {{App|spice-gtk|SPICE GTK client, a subset of the SPICE project. Embedded into other applications as a widget.|https://www.spice-space.org/|{{Pkg|spice-gtk}}}}<br />
<br />
For clients that run on smartphone or on other platforms, refer to the ''Other clients'' section in [https://www.spice-space.org/download.html spice-space download].<br />
<br />
==== Manually running a SPICE client ====<br />
<br />
One way of connecting to a guest listening on Unix socket {{ic|/tmp/vm_spice.socket}} is to manually run the SPICE client using {{ic|$ remote-viewer spice+unix:///tmp/vm_spice.socket}} or {{ic|1=$ spicy --uri="spice+unix:///tmp/vm_spice.socket"}}, depending on the desired client. Since QEMU in SPICE mode acts similarly to a remote desktop server, it may be more convenient to run QEMU in daemon mode with the {{ic|-daemonize}} parameter.<br />
<br />
{{Tip|<br />
To connect to the guest through SSH tunneling, the following type of command can be used: {{bc|$ ssh -fL 5999:localhost:5930 ''my.domain.org'' sleep 10; spicy -h 127.0.0.1 -p 5999}}<br />
This example connects ''spicy'' to the local port {{ic|5999}} which is forwarded through SSH to the guest's SPICE server located at the address ''my.domain.org'', port {{ic|5930}}.<br />
Note the {{ic|-f}} option that requests ssh to execute the command {{ic|sleep 10}} in the background. This way, the ssh session runs while the client is active and auto-closes once the client ends.<br />
}}<br />
<br />
==== Running a SPICE client with QEMU ====<br />
<br />
QEMU can automatically start a SPICE client with an appropriate socket, if the display is set to SPICE with the {{ic|-display spice-app}} parameter. This will use the system's default SPICE client as the viewer, determined by your [[XDG MIME Applications#mimeapps.list|mimeapps.list]] files.<br />
<br />
=== Enabling SPICE support on the guest ===<br />
<br />
For '''Arch Linux guests''', for improved support for multiple monitors or clipboard sharing, the following packages should be installed:<br />
* {{Pkg|spice-vdagent}}: Spice agent xorg client that enables copy and paste between client and X-session and more. (Refer to this [https://github.com/systemd/systemd/issues/18791 issue], until fixed, for workarounds to get this to work on non-GNOME desktops.)<br />
* {{Pkg|xf86-video-qxl}}: Xorg X11 qxl video driver<br />
* {{AUR|x-resize}}: Desktop environments other than GNOME do not react automatically when the SPICE client window is resized. This package uses a [[udev]] rule and [[xrandr]] to implement auto-resizing for all X11-based desktop environments and window managers.<br />
For guests under '''other operating systems''', refer to the ''Guest'' section in spice-space [https://www.spice-space.org/download.html download].<br />
<br />
=== Password authentication with SPICE ===<br />
<br />
If you want to enable password authentication with SPICE you need to remove {{ic|disable-ticketing}} from the {{ic|-spice}} argument and instead add {{ic|1=password=''yourpassword''}}. For example:<br />
<br />
$ qemu-system-x86_64 -vga qxl -spice port=5900,password=''yourpassword'' -device virtio-serial-pci -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
Your SPICE client should now ask for the password to be able to connect to the SPICE server.<br />
<br />
=== TLS encrypted communication with SPICE ===<br />
<br />
You can also configure TLS encryption for communicating with the SPICE server. First, you need to have a directory which contains the following files (the names must be exactly as indicated):<br />
<br />
* {{ic|ca-cert.pem}}: the CA master certificate.<br />
* {{ic|server-cert.pem}}: the server certificate signed with {{ic|ca-cert.pem}}.<br />
* {{ic|server-key.pem}}: the server private key.<br />
<br />
An example of generation of self-signed certificates with your own generated CA for your server is shown in the [https://www.spice-space.org/spice-user-manual.html#_generating_self_signed_certificates Spice User Manual].<br />
<br />
Afterwards, you can run QEMU with SPICE as explained above but using the following {{ic|-spice}} argument: {{ic|1=-spice tls-port=5901,password=''yourpassword'',x509-dir=''/path/to/pki_certs''}}, where {{ic|''/path/to/pki_certs''}} is the directory path that contains the three needed files shown earlier.<br />
<br />
It is now possible to connect to the server using {{Pkg|virt-viewer}}:<br />
<br />
$ remote-viewer spice://''hostname''?tls-port=5901 --spice-ca-file=''/path/to/ca-cert.pem'' --spice-host-subject="C=''XX'',L=''city'',O=''organization'',CN=''hostname''" --spice-secure-channels=all<br />
<br />
Keep in mind that the {{ic|--spice-host-subject}} parameter needs to be set according to your {{ic|server-cert.pem}} subject. You also need to copy {{ic|ca-cert.pem}} to every client to verify the server certificate.<br />
<br />
{{Tip|You can get the subject line of the server certificate in the correct format for {{ic|--spice-host-subject}} (with entries separated by commas) using the following command: {{bc|<nowiki>$ openssl x509 -noout -subject -in server-cert.pem | cut -d' ' -f2- | sed 's/\///' | sed 's/\//,/g'</nowiki>}}<br />
}}<br />
<br />
The equivalent {{Pkg|spice-gtk}} command is:<br />
<br />
$ spicy -h ''hostname'' -s 5901 --spice-ca-file=ca-cert.pem --spice-host-subject="C=''XX'',L=''city'',O=''organization'',CN=''hostname''" --spice-secure-channels=all<br />
<br />
== VNC ==<br />
<br />
One can add the {{ic|-vnc :''X''}} option to have QEMU redirect the VGA display to the VNC session. Substitute {{ic|''X''}} for the number of the display (0 will then listen on 5900, 1 on 5901...).<br />
<br />
$ qemu-system-x86_64 -vnc :0<br />
<br />
An example is also provided in the [[#Starting QEMU virtual machines on boot]] section.<br />
<br />
{{Warning|The default VNC server setup does not use any form of authentication. Any user can connect from any host.}}<br />
<br />
=== Basic password authentication ===<br />
<br />
An access password can be setup easily by using the {{ic|password}} option. The password must be indicated in the QEMU monitor and connection is only possible once the password is provided.<br />
<br />
$ qemu-system-x86_64 -vnc :0,password -monitor stdio<br />
<br />
In the QEMU monitor, password is set using the command {{ic|change vnc password}} and then indicating the password.<br />
<br />
The following command line directly runs vnc with a password:<br />
<br />
$ printf "change vnc password\n%s\n" MYPASSWORD | qemu-system-x86_64 -vnc :0,password -monitor stdio<br />
<br />
{{Note|The password is limited to 8 characters and can be guessed through brute force attack. More elaborated protection is strongly recommended for public network.}}<br />
<br />
== Audio ==<br />
<br />
=== Creating an audio backend ===<br />
<br />
The {{ic|-audiodev}} flag sets the audio backend driver on the host and its options.<br />
<br />
To list availabe audio backend drivers:<br />
<br />
$ qemu-system-x86_64 -audiodev help<br />
<br />
Their optional settings are detailed in the {{man|1|qemu}} man page.<br />
<br />
At the bare minimum, one need to choose an audio backend and set an id, for [[PulseAudio]] for example:<br />
<br />
-audiodev pa,id=snd0<br />
<br />
=== Using the audio backend ===<br />
<br />
==== Intel HD Audio ====<br />
<br />
For Intel HD Audio emulation, add both controller and codec devices. To list the available Intel HDA Audio devices:<br />
<br />
$ qemu-system-x86_64 -device help | grep hda<br />
<br />
Add the audio controller:<br />
<br />
-device ich9-intel-hda<br />
<br />
Also, add the audio codec and map it to a host audio backend id:<br />
<br />
-device hda-output,audiodev=snd0<br />
<br />
==== Intel 82801AA AC97 ====<br />
<br />
For AC97 emulation just add the audio card device and map it to a host audio backend id:<br />
<br />
-device AC97,audiodev=snd0<br />
<br />
{{Note|<br />
* If the audiodev backend is not provided, QEMU looks up for it and adds it automatically, this only works for a single audiodev. For example {{ic|-device intel-hda -device hda-duplex}} will emulate {{ic|intel-hda}} on the guest using the default audiodev backend.<br />
* Video graphic card emulated drivers for the guest machine may also cause a problem with the sound quality. Test one by one to make it work. You can list possible options with {{ic|<nowiki>qemu-system-x86_64 -h | grep vga</nowiki>}}.<br />
}}<br />
<br />
==== VirtIO sound ====<br />
<br />
VirtIO sound is also available since QEMU 8.2.0. The usage is:<br />
<br />
-device virtio-sound-pci,audiodev=my_audiodev -audiodev alsa,id=my_audiodev<br />
<br />
More information can be found in [https://qemu-project.gitlab.io/qemu/system/devices/virtio-snd.html QEMU documentation].<br />
<br />
== Installing virtio drivers ==<br />
<br />
QEMU offers guests the ability to use paravirtualized block and network devices using the [https://wiki.libvirt.org/page/Virtio virtio] drivers, which provide better performance and lower overhead.<br />
<br />
* A virtio block device requires the option {{ic|-drive}} for passing a disk image, with parameter {{ic|1=if=virtio}}:<br />
$ qemu-system-x86_64 -drive file=''disk_image'',if='''virtio'''<br />
<br />
* Almost the same goes for the network:<br />
$ qemu-system-x86_64 -nic user,model='''virtio-net-pci'''<br />
<br />
{{Note|This will only work if the guest machine has drivers for virtio devices. Linux does, and the required drivers are included in Arch Linux, but there is no guarantee that virtio devices will work with other operating systems.}}<br />
<br />
=== Preparing an Arch Linux guest ===<br />
<br />
To use virtio devices after an Arch Linux guest has been installed, the following modules must be loaded in the guest: {{ic|virtio}}, {{ic|virtio_pci}}, {{ic|virtio_blk}}, {{ic|virtio_net}}, and {{ic|virtio_ring}}. For 32-bit guests, the specific "virtio" module is not necessary.<br />
<br />
If you want to boot from a virtio disk, the initial ramdisk must contain the necessary modules. By default, this is handled by [[mkinitcpio]]'s {{ic|autodetect}} hook. Otherwise use the {{ic|MODULES}} array in {{ic|/etc/mkinitcpio.conf}} to include the necessary modules and rebuild the initial ramdisk.<br />
<br />
{{hc|/etc/mkinitcpio.conf|2=<br />
MODULES=(virtio virtio_blk virtio_pci virtio_net)}}<br />
<br />
Virtio disks are recognized with the prefix {{ic|'''v'''}} (e.g. {{ic|'''v'''da}}, {{ic|'''v'''db}}, etc.); therefore, changes must be made in at least {{ic|/etc/fstab}} and {{ic|/boot/grub/grub.cfg}} when booting from a virtio disk.<br />
<br />
{{Tip|When referencing disks by [[UUID]] in both {{ic|/etc/fstab}} and boot loader, nothing has to be done.}}<br />
<br />
Further information on paravirtualization with KVM can be found [https://www.linux-kvm.org/page/Boot_from_virtio_block_device here].<br />
<br />
You might also want to install {{Pkg|qemu-guest-agent}} to implement support for QMP commands that will enhance the hypervisor management capabilities.<br />
<br />
=== Preparing a Windows guest ===<br />
<br />
==== Virtio drivers for Windows ====<br />
<br />
Windows does not come with the virtio drivers. The latest and stable versions of the drivers are regularly built by Fedora, details on downloading the drivers are given on [https://github.com/virtio-win/virtio-win-pkg-scripts/blob/master/README.md virtio-win on GitHub]. In the following sections we will mostly use the stable ISO file provided here: [https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/stable-virtio/virtio-win.iso virtio-win.iso]. Alternatively, use {{AUR|virtio-win}}.<br />
<br />
==== Block device drivers ====<br />
<br />
===== New Install of Windows =====<br />
<br />
The drivers need to be loaded during installation, the procedure is to load the ISO image with the virtio drivers in a cdrom device along with the primary disk device and the Windows ISO install media:<br />
<br />
$ qemu-system-x86_64 ... \<br />
-drive file=''disk_image'',index=0,media=disk,if=virtio \<br />
-drive file=''windows.iso'',index=2,media=cdrom \<br />
-drive file=''virtio-win.iso'',index=3,media=cdrom \<br />
...<br />
<br />
During the installation, at some stage, the Windows installer will ask "Where do you want to install Windows?", it will give a warning that no disks are found. Follow the example instructions below (based on Windows Server 2012 R2 with Update).<br />
<br />
* Select the option ''Load Drivers''.<br />
* Uncheck the box for ''Hide drivers that are not compatible with this computer's hardware''.<br />
* Click the browse button and open the CDROM for the virtio iso, usually named "virtio-win-XX".<br />
* Now browse to {{ic|E:\viostor\[your-os]\amd64}}, select it, and confirm.<br />
<br />
You should now see your virtio disk(s) listed here, ready to be selected, formatted and installed to.<br />
<br />
===== Change existing Windows virtual machine to use virtio =====<br />
<br />
Modifying an existing Windows guest for booting from virtio disk requires that the virtio driver is loaded by the guest at boot time.<br />
We will therefore need to teach Windows to load the virtio driver at boot time before being able to boot a disk image in virtio mode.<br />
<br />
To achieve that, first create a new disk image that will be attached in virtio mode and trigger the search for the driver:<br />
<br />
$ qemu-img create -f qcow2 ''dummy.qcow2'' 1G<br />
<br />
Run the original Windows guest with the boot disk still in IDE mode, the fake disk in virtio mode and the driver ISO image.<br />
<br />
$ qemu-system-x86_64 -m 4G -drive file=''disk_image'',if=ide -drive file=''dummy.qcow2'',if=virtio -cdrom virtio-win.iso<br />
<br />
Windows will detect the fake disk and look for a suitable driver. If it fails, go to ''Device Manager'', locate the SCSI drive with an exclamation mark icon (should be open), click ''Update driver'' and select the virtual CD-ROM. Do not navigate to the driver folder within the CD-ROM, simply select the CD-ROM drive and Windows will find the appropriate driver automatically (tested for Windows 7 SP1).<br />
<br />
Request Windows to boot in safe mode next time it starts up. This can be done using the ''msconfig.exe'' tool in Windows. In safe mode all the drivers will be loaded at boot time including the new virtio driver. Once Windows knows that the virtio driver is required at boot it will memorize it for future boot.<br />
<br />
Once instructed to boot in safe mode, you can turn off the virtual machine and launch it again, now with the boot disk attached in virtio mode:<br />
<br />
$ qemu-system-x86_64 -m 4G -drive file=''disk_image'',if=virtio<br />
<br />
You should boot in safe mode with virtio driver loaded, you can now return to ''msconfig.exe'' disable safe mode boot and restart Windows.<br />
<br />
{{Note|If you encounter the blue screen of death using the {{ic|1=if=virtio}} parameter, it probably means the virtio disk driver is not installed or not loaded at boot time, reboot in safe mode and check your driver configuration.}}<br />
<br />
==== Network drivers ====<br />
<br />
Installing virtio network drivers is a bit easier, simply add the {{ic|-nic}} argument.<br />
<br />
$ qemu-system-x86_64 -m 4G -drive file=''windows_disk_image'',if=virtio -nic user,model=virtio-net-pci -cdrom virtio-win.iso<br />
<br />
Windows will detect the network adapter and try to find a driver for it. If it fails, go to the ''Device Manager'', locate the network adapter with an exclamation mark icon (should be open), click ''Update driver'' and select the virtual CD-ROM. Do not forget to select the checkbox which says to search for directories recursively.<br />
<br />
==== Balloon driver ====<br />
<br />
If you want to track you guest memory state (for example via {{ic|virsh}} command {{ic|dommemstat}}) or change guest's memory size in runtime (you still will not be able to change memory size, but can limit memory usage via inflating balloon driver) you will need to install guest balloon driver.<br />
<br />
For this you will need to go to ''Device Manager'', locate ''PCI standard RAM Controller'' in ''System devices'' (or unrecognized PCI controller from ''Other devices'') and choose ''Update driver''. In opened window you will need to choose ''Browse my computer...'' and select the CD-ROM (and do not forget the ''Include subdirectories'' checkbox). Reboot after installation. This will install the driver and you will be able to inflate the balloon (for example via hmp command {{ic|balloon ''memory_size''}}, which will cause balloon to take as much memory as possible in order to shrink the guest's available memory size to ''memory_size''). However, you still will not be able to track guest memory state. In order to do this you will need to install ''Balloon'' service properly. For that open command line as administrator, go to the CD-ROM, ''Balloon'' directory and deeper, depending on your system and architecture. Once you are in ''amd64'' (''x86'') directory, run {{ic|blnsrv.exe -i}} which will do the installation. After that {{ic|virsh}} command {{ic|dommemstat}} should be outputting all supported values.<br />
<br />
=== Preparing a FreeBSD guest ===<br />
<br />
Install the {{ic|emulators/virtio-kmod}} port if you are using FreeBSD 8.3 or later up until 10.0-CURRENT where they are included into the kernel. After installation, add the following to your {{ic|/boot/loader.conf}} file:<br />
<br />
{{bc|1=<br />
virtio_load="YES"<br />
virtio_pci_load="YES"<br />
virtio_blk_load="YES"<br />
if_vtnet_load="YES"<br />
virtio_balloon_load="YES"<br />
}}<br />
<br />
Then modify your {{ic|/etc/fstab}} by doing the following:<br />
<br />
# sed -ibak "s/ada/vtbd/g" /etc/fstab<br />
<br />
And verify that {{ic|/etc/fstab}} is consistent. If anything goes wrong, just boot into a rescue CD and copy {{ic|/etc/fstab.bak}} back to {{ic|/etc/fstab}}.<br />
<br />
== QEMU monitor ==<br />
<br />
While QEMU is running, a monitor console is provided in order to provide several ways to interact with the virtual machine running. The QEMU monitor offers interesting capabilities such as obtaining information about the current virtual machine, hotplugging devices, creating snapshots of the current state of the virtual machine, etc. To see the list of all commands, run {{ic|help}} or {{ic|?}} in the QEMU monitor console or review the relevant section of the [https://www.qemu.org/docs/master/system/monitor.html official QEMU documentation].<br />
<br />
=== Accessing the monitor console ===<br />
<br />
==== Graphical view ====<br />
<br />
When using the {{ic|std}} default graphics option, one can access the QEMU monitor by pressing {{ic|Ctrl+Alt+2}} or by clicking ''View > compatmonitor0'' in the QEMU window. To return to the virtual machine graphical view either press {{ic|Ctrl+Alt+1}} or click ''View > VGA''.<br />
<br />
However, the standard method of accessing the monitor is not always convenient and does not work in all graphic outputs QEMU supports.<br />
<br />
==== Telnet ====<br />
<br />
To enable [[telnet]], run QEMU with the {{ic|-monitor telnet:127.0.0.1:''port'',server,nowait}} parameter. When the virtual machine is started you will be able to access the monitor via telnet:<br />
<br />
$ telnet 127.0.0.1 ''port''<br />
<br />
{{Note|If {{ic|127.0.0.1}} is specified as the IP to listen it will be only possible to connect to the monitor from the same host QEMU is running on. If connecting from remote hosts is desired, QEMU must be told to listen {{ic|0.0.0.0}} as follows: {{ic|-monitor telnet:0.0.0.0:''port'',server,nowait}}. Keep in mind that it is recommended to have a [[firewall]] configured in this case or make sure your local network is completely trustworthy since this connection is completely unauthenticated and unencrypted.}}<br />
<br />
==== UNIX socket ====<br />
<br />
Run QEMU with the {{ic|-monitor unix:''socketfile'',server,nowait}} parameter. Then you can connect with either {{Pkg|socat}}, {{Pkg|nmap}} or {{Pkg|openbsd-netcat}}.<br />
<br />
For example, if QEMU is run via:<br />
<br />
$ qemu-system-x86_64 -monitor unix:/tmp/monitor.sock,server,nowait ''[...]''<br />
<br />
It is possible to connect to the monitor with:<br />
<br />
$ socat - UNIX-CONNECT:/tmp/monitor.sock<br />
<br />
Or with:<br />
<br />
$ nc -U /tmp/monitor.sock<br />
<br />
Alternatively with {{Pkg|nmap}}:<br />
<br />
$ ncat -U /tmp/monitor.sock<br />
<br />
==== TCP ====<br />
<br />
You can expose the monitor over TCP with the argument {{ic|-monitor tcp:127.0.0.1:''port'',server,nowait}}. Then connect with netcat, either {{Pkg|openbsd-netcat}} or {{Pkg|gnu-netcat}} by running:<br />
<br />
$ nc 127.0.0.1 ''port''<br />
<br />
{{Note|In order to be able to connect to the tcp socket from other devices other than the same host QEMU is being run on you need to listen to {{ic|0.0.0.0}} like explained in the telnet case. The same security warnings apply in this case as well.}}<br />
<br />
==== Standard I/O ====<br />
<br />
It is possible to access the monitor automatically from the same terminal QEMU is being run by running it with the argument {{ic|-monitor stdio}}.<br />
<br />
=== Sending keyboard presses to the virtual machine using the monitor console ===<br />
<br />
Some combinations of keys may be difficult to perform on virtual machines due to the host intercepting them instead in some configurations (a notable example is the {{ic|Ctrl+Alt+F*}} key combinations, which change the active tty). To avoid this problem, the problematic combination of keys may be sent via the monitor console instead. Switch to the monitor and use the {{ic|sendkey}} command to forward the necessary keypresses to the virtual machine. For example:<br />
<br />
(qemu) sendkey ctrl-alt-f2<br />
<br />
=== Creating and managing snapshots via the monitor console ===<br />
<br />
{{Note|This feature will '''only''' work when the virtual machine disk image is in ''qcow2'' format. It will not work with ''raw'' images.}}<br />
<br />
It is sometimes desirable to save the current state of a virtual machine and having the possibility of reverting the state of the virtual machine to that of a previously saved snapshot at any time. The QEMU monitor console provides the user with the necessary utilities to create snapshots, manage them, and revert the machine state to a saved snapshot.<br />
<br />
* Use {{ic|savevm ''name''}} in order to create a snapshot with the tag ''name''.<br />
* Use {{ic|loadvm ''name''}} to revert the virtual machine to the state of the snapshot ''name''.<br />
* Use {{ic|delvm ''name''}} to delete the snapshot tagged as ''name''.<br />
* Use {{ic|info snapshots}} to see a list of saved snapshots. Snapshots are identified by both an auto-incremented ID number and a text tag (set by the user on snapshot creation).<br />
<br />
=== Running the virtual machine in immutable mode ===<br />
<br />
It is possible to run a virtual machine in a frozen state so that all changes will be discarded when the virtual machine is powered off just by running QEMU with the {{ic|-snapshot}} parameter. When the disk image is written by the guest, changes will be saved in a temporary file in {{ic|/tmp}} and will be discarded when QEMU halts.<br />
<br />
However, if a machine is running in frozen mode it is still possible to save the changes to the disk image if it is afterwards desired by using the monitor console and running the following command:<br />
<br />
(qemu) commit all<br />
<br />
If snapshots are created when running in frozen mode they will be discarded as soon as QEMU is exited unless changes are explicitly commited to disk, as well.<br />
<br />
=== Pause and power options via the monitor console ===<br />
<br />
Some operations of a physical machine can be emulated by QEMU using some monitor commands:<br />
<br />
* {{ic|system_powerdown}} will send an ACPI shutdown request to the virtual machine. This effect is similar to the power button in a physical machine.<br />
* {{ic|system_reset}} will reset the virtual machine similarly to a reset button in a physical machine. This operation can cause data loss and file system corruption since the virtual machine is not cleanly restarted.<br />
* {{ic|stop}} will pause the virtual machine.<br />
* {{ic|cont}} will resume a virtual machine previously paused.<br />
<br />
=== Taking screenshots of the virtual machine ===<br />
<br />
Screenshots of the virtual machine graphic display can be obtained in the PPM format by running the following command in the monitor console:<br />
<br />
(qemu) screendump ''file.ppm''<br />
<br />
== QEMU machine protocol ==<br />
<br />
The QEMU machine protocol (QMP) is a JSON-based protocol which allows applications to control a QEMU instance. Similarly to the [[#QEMU monitor]] it offers ways to interact with a running machine and the JSON protocol allows to do it programmatically. The description of all the QMP commands can be found in [https://raw.githubusercontent.com/coreos/qemu/master/qmp-commands.hx qmp-commands].<br />
<br />
=== Start QMP ===<br />
<br />
The usual way to control the guest using the QMP protocol, is to open a TCP socket when launching the machine using the {{ic|-qmp}} option. Here it is using for example the TCP port 4444:<br />
<br />
$ qemu-system-x86_64 ''[...]'' -qmp tcp:localhost:4444,server,nowait<br />
<br />
Then one way to communicate with the QMP agent is to use [[netcat]]:<br />
<br />
{{hc|nc localhost 4444|{"QMP": {"version": {"qemu": {"micro": 0, "minor": 1, "major": 3}, "package": ""}, "capabilities": []} } }}<br />
<br />
At this stage, the only command that can be recognized is {{ic|qmp_capabilities}}, so that QMP enters into command mode. Type:<br />
<br />
{"execute": "qmp_capabilities"}<br />
<br />
Now, QMP is ready to receive commands, to retrieve the list of recognized commands, use:<br />
<br />
{"execute": "query-commands"}<br />
<br />
=== Live merging of child image into parent image ===<br />
<br />
It is possible to merge a running snapshot into its parent by issuing a {{ic|block-commit}} command. In its simplest form the following line will commit the child into its parent:<br />
<br />
{"execute": "block-commit", "arguments": {"device": "''devicename''"}}<br />
<br />
Upon reception of this command, the handler looks for the base image and converts it from read only to read write mode and then runs the commit job.<br />
<br />
Once the ''block-commit'' operation has completed, the event {{ic|BLOCK_JOB_READY}} will be emitted, signalling that the synchronization has finished. The job can then be gracefully completed by issuing the command {{ic|block-job-complete}}:<br />
<br />
{"execute": "block-job-complete", "arguments": {"device": "''devicename''"}}<br />
<br />
Until such a command is issued, the ''commit'' operation remains active.<br />
After successful completion, the base image remains in read write mode and becomes the new active layer. On the other hand, the child image becomes invalid and it is the responsibility of the user to clean it up.<br />
<br />
{{Tip|The list of device and their names can be retrieved by executing the command {{ic|query-block}} and parsing the results. The device name is in the {{ic|device}} field, for example {{ic|ide0-hd0}} for the hard disk in this example: {{hc|{"execute": "query-block"}|{"return": [{"io-status": "ok", "device": "'''ide0-hd0'''", "locked": false, "removable": false, "inserted": {"iops_rd": 0, "detect_zeroes": "off", "image": {"backing-image": {"virtual-size": 27074281472, "filename": "parent.qcow2", ... } }} }}<br />
<br />
=== Live creation of a new snapshot ===<br />
<br />
To create a new snapshot out of a running image, run the command:<br />
<br />
{"execute": "blockdev-snapshot-sync", "arguments": {"device": "''devicename''","snapshot-file": "''new_snapshot_name''.qcow2"}}<br />
<br />
This creates an overlay file named {{ic|''new_snapshot_name''.qcow2}} which then becomes the new active layer.<br />
<br />
== Tips and tricks ==<br />
<br />
=== Improve virtual machine performance ===<br />
<br />
There are a number of techniques that you can use to improve the performance of the virtual machine. For example:<br />
<br />
* Apply [[#Enabling KVM]] for full virtualization.<br />
* Use the {{ic|-cpu host}} option to make QEMU emulate the host's exact CPU rather than a more generic CPU.<br />
* Especially for Windows guests, enable [https://blog.wikichoon.com/2014/07/enabling-hyper-v-enlightenments-with-kvm.html Hyper-V enlightenments]: {{ic|1=-cpu host,hv_relaxed,hv_spinlocks=0x1fff,hv_vapic,hv_time}}. See the [https://www.qemu.org/docs/master/system/i386/hyperv.html QEMU documentation] for more information and flags.<br />
* multiple cores can be assigned to the guest using the {{ic|-smp cores{{=}}x,threads{{=}}y,sockets{{=}}1,maxcpus{{=}}z}} option. The threads parameter is used to assign [https://www.tomshardware.com/reviews/simultaneous-multithreading-definition,5762.html SMT cores]. Leaving a physical core for QEMU, the hypervisor and the host system to operate unimpeded is highly beneficial.<br />
* Make sure you have assigned the virtual machine enough memory. By default, QEMU only assigns 128 MiB of memory to each virtual machine. Use the {{ic|-m}} option to assign more memory. For example, {{ic|-m 1024}} runs a virtual machine with 1024 MiB of memory.<br />
* If supported by drivers in the guest operating system, use virtio for network and/or block devices, see [[#Installing virtio drivers]].<br />
* Use TAP devices instead of user-mode networking, see [[#Tap networking with QEMU]].<br />
* If the guest OS is doing heavy writing to its disk, you may benefit from certain mount options on the host's file system. For example, you can mount an [[Ext4|ext4 file system]] with the option {{ic|1=barrier=0}}. You should read the documentation for any options that you change because sometimes performance-enhancing options for file systems come at the cost of data integrity.<br />
* If you have a raw disk or partition, you may want to disable the cache: {{bc|1=$ qemu-system-x86_64 -drive file=/dev/''disk'',if=virtio,'''cache=none'''}}<br />
* Use the native Linux AIO: {{bc|1=$ qemu-system-x86_64 -drive file=''disk_image'',if=virtio''',aio=native,cache.direct=on'''}}<br />
* If you are running multiple virtual machines concurrently that all have the same operating system installed, you can save memory by enabling [[wikipedia:Kernel_SamePage_Merging_(KSM)|kernel same-page merging]]. See [[#Enabling KSM]].<br />
* In some cases, memory can be reclaimed from running virtual machines by running a memory ballooning driver in the guest operating system and launching QEMU using {{ic|-device virtio-balloon}}.<br />
* It is possible to use a emulation layer for an ICH-9 AHCI controller (although it may be unstable). The AHCI emulation supports [[Wikipedia:Native_Command_Queuing|NCQ]], so multiple read or write requests can be outstanding at the same time: {{bc|1=$ qemu-system-x86_64 -drive id=disk,file=''disk_image'',if=none -device ich9-ahci,id=ahci -device ide-drive,drive=disk,bus=ahci.0}}<br />
<br />
See https://www.linux-kvm.org/page/Tuning_KVM for more information.<br />
<br />
=== Starting QEMU virtual machines on boot ===<br />
<br />
==== With libvirt ====<br />
<br />
If a virtual machine is set up with [[libvirt]], it can be configured with {{ic|virsh autostart}} or through the ''virt-manager'' GUI to start at host boot by going to the Boot Options for the virtual machine and selecting "Start virtual machine on host boot up".<br />
<br />
==== With systemd service ====<br />
<br />
To run QEMU virtual machines on boot, you can use following systemd unit and config.<br />
<br />
{{hc|/etc/systemd/system/qemu@.service|2=<br />
[Unit]<br />
Description=QEMU virtual machine<br />
<br />
[Service]<br />
Environment="haltcmd=kill -INT $MAINPID"<br />
EnvironmentFile=/etc/conf.d/qemu.d/%i<br />
ExecStart=/usr/bin/qemu-system-x86_64 -name %i -enable-kvm -m 512 -nographic $args<br />
ExecStop=/usr/bin/bash -c ${haltcmd}<br />
ExecStop=/usr/bin/bash -c 'while nc localhost 7100; do sleep 1; done'<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
}}<br />
<br />
{{Note|This service will wait for the console port to be released, which means that the virtual machine has been shutdown, to graciously end.}}<br />
<br />
Then create per-VM configuration files, named {{ic|/etc/conf.d/qemu.d/''vm_name''}}, with the variables {{ic|args}} and {{ic|haltcmd}} set. Example configs:<br />
<br />
{{hc|/etc/conf.d/qemu.d/one|2=<br />
args="-hda /dev/vg0/vm1 -serial telnet:localhost:7000,server,nowait,nodelay \<br />
-monitor telnet:localhost:7100,server,nowait,nodelay -vnc :0"<br />
<br />
haltcmd="echo 'system_powerdown' {{!}} nc localhost 7100" # or netcat/ncat}}<br />
<br />
{{hc|/etc/conf.d/qemu.d/two|2=<br />
args="-hda /srv/kvm/vm2 -serial telnet:localhost:7001,server,nowait,nodelay -vnc :1"<br />
<br />
haltcmd="ssh powermanager@vm2 sudo poweroff"}}<br />
<br />
The description of the variables is the following:<br />
<br />
* {{ic|args}} - QEMU command line arguments to be used.<br />
* {{ic|haltcmd}} - Command to shut down a virtual machine safely. In the first example, the QEMU monitor is exposed via telnet using {{ic|-monitor telnet:..}} and the virtual machines are powered off via ACPI by sending {{ic|system_powerdown}} to monitor with the {{ic|nc}} command. In the other example, SSH is used.<br />
<br />
To set which virtual machines will start on boot-up, [[enable]] the {{ic|qemu@''vm_name''.service}} systemd unit.<br />
<br />
=== Mouse integration ===<br />
<br />
To prevent the mouse from being grabbed when clicking on the guest operating system's window, add the options {{ic|-usb -device usb-tablet}}. This means QEMU is able to report the mouse position without having to grab the mouse. This also overrides PS/2 mouse emulation when activated. For example:<br />
<br />
$ qemu-system-x86_64 -hda ''disk_image'' -m 512 -usb -device usb-tablet<br />
<br />
If that does not work, try using {{ic|-vga qxl}} parameter, also look at the instructions [[#Mouse cursor is jittery or erratic]].<br />
<br />
=== Pass-through host USB device ===<br />
<br />
It is possible to access the physical device connected to a USB port of the host from the guest. The first step is to identify where the device is connected, this can be found running the {{ic|lsusb}} command. For example:<br />
<br />
{{hc|$ lsusb|<br />
...<br />
Bus '''003''' Device '''007''': ID '''0781''':'''5406''' SanDisk Corp. Cruzer Micro U3<br />
}}<br />
<br />
The outputs in bold above will be useful to identify respectively the ''host_bus'' and ''host_addr'' or the ''vendor_id'' and ''product_id''.<br />
<br />
In qemu, the idea is to emulate an EHCI (USB 2) or XHCI (USB 1.1 USB 2 USB 3) controller with the option {{ic|1=-device usb-ehci,id=ehci}} or {{ic|1=-device qemu-xhci,id=xhci}} respectively and then attach the physical device to it with the option {{ic|1=-device usb-host,..}}. We will consider that ''controller_id'' is either {{ic|ehci}} or {{ic|xhci}} for the rest of this section.<br />
<br />
Then, there are two ways to connect to the USB of the host with qemu:<br />
<br />
# Identify the device and connect to it on any bus and address it is attached to on the host, the generic syntax is: {{bc|1=-device usb-host,bus=''controller_id''.0,vendorid=0x''vendor_id'',productid=0x''product_id''}}Applied to the device used in the example above, it becomes:{{bc|1=-device usb-ehci,id=ehci -device usb-host,bus=ehci.0,vendorid=0x'''0781''',productid=0x'''5406'''}}One can also add the {{ic|1=...,port=''port_number''}} setting to the previous option to specify in which physical port of the virtual controller the device should be attached, useful in the case one wants to add multiple USB devices to the virtual machine. Another option is to use the new {{ic|hostdevice}} property of {{ic|usb-host}} which is available since QEMU 5.1.0, the syntax is: {{bc|1=-device qemu-xhci,id=xhci -device usb-host,hostdevice=/dev/bus/usb/003/007}}<br />
# Attach whatever is connected to a given USB bus and address, the syntax is:{{bc|1=-device usb-host,bus=''controller_id''.0,hostbus=''host_bus'',host_addr=''host_addr''}}Applied to the bus and the address in the example above, it becomes:{{bc|1=-device usb-ehci,id=ehci -device usb-host,bus=ehci.0,hostbus='''3''',hostaddr='''7'''}}<br />
See [https://www.qemu.org/docs/master/system/devices/usb.html QEMU/USB emulation] for more information.<br />
{{Note|If you encounter permission errors when running QEMU, see [[udev#About udev rules]] for information on how to set permissions of the device.}}<br />
<br />
=== USB redirection with SPICE ===<br />
<br />
When using [[#SPICE]] it is possible to redirect USB devices from the client to the virtual machine without needing to specify them in the QEMU command. It is possible to configure the number of USB slots available for redirected devices (the number of slots will determine the maximum number of devices which can be redirected simultaneously). The main advantages of using SPICE for redirection compared to the previously-mentioned {{ic|-usbdevice}} method is the possibility of hot-swapping USB devices after the virtual machine has started, without needing to halt it in order to remove USB devices from the redirection or adding new ones. This method of USB redirection also allows us to redirect USB devices over the network, from the client to the server. In summary, it is the most flexible method of using USB devices in a QEMU virtual machine.<br />
<br />
We need to add one EHCI/UHCI controller per available USB redirection slot desired as well as one SPICE redirection channel per slot. For example, adding the following arguments to the QEMU command you use for starting the virtual machine in SPICE mode will start the virtual machine with three available USB slots for redirection:<br />
<br />
{{bc|1=<br />
-device ich9-usb-ehci1,id=usb \<br />
-device ich9-usb-uhci1,masterbus=usb.0,firstport=0,multifunction=on \<br />
-device ich9-usb-uhci2,masterbus=usb.0,firstport=2 \<br />
-device ich9-usb-uhci3,masterbus=usb.0,firstport=4 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev1 -device usb-redir,chardev=usbredirchardev1,id=usbredirdev1 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev2 -device usb-redir,chardev=usbredirchardev2,id=usbredirdev2 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev3 -device usb-redir,chardev=usbredirchardev3,id=usbredirdev3<br />
}}<br />
<br />
See [https://www.spice-space.org/usbredir.html SPICE/usbredir] for more information.<br />
<br />
Both {{ic|spicy}} from {{Pkg|spice-gtk}} (''Input > Select USB Devices for redirection'') and {{ic|remote-viewer}} from {{Pkg|virt-viewer}} (''File > USB device selection'') support this feature. Please make sure that you have installed the necessary SPICE Guest Tools on the virtual machine for this functionality to work as expected (see the [[#SPICE]] section for more information).<br />
<br />
{{Warning|Keep in mind that when a USB device is redirected from the client, it will not be usable from the client operating system itself until the redirection is stopped. It is specially important to never redirect the input devices (namely mouse and keyboard), since it will be then difficult to access the SPICE client menus to revert the situation, because the client will not respond to the input devices after being redirected to the virtual machine.}}<br />
<br />
==== Automatic USB forwarding with udev ====<br />
<br />
Normally, forwarded devices must be available at the boot time of the virtual machine to be forwarded. If that device is disconnected, it will not be forwarded anymore.<br />
<br />
You can use [[udev rule]]s to automatically attach a device when it comes online. Create a {{ic|hostdev}} entry somewhere on disk. [[chown]] it to root to prevent other users modifying it.<br />
<br />
{{hc|/usr/local/hostdev-mydevice.xml|2=<br />
<hostdev mode='subsystem' type='usb'><br />
<source><br />
<vendor id='0x03f0'/><br />
<product id='0x4217'/><br />
</source><br />
</hostdev><br />
}}<br />
<br />
Then create a ''udev'' rule which will attach/detach the device:<br />
<br />
{{hc|/usr/lib/udev/rules.d/90-libvirt-mydevice|2=<br />
ACTION=="add", \<br />
SUBSYSTEM=="usb", \<br />
ENV{ID_VENDOR_ID}=="03f0", \<br />
ENV{ID_MODEL_ID}=="4217", \<br />
RUN+="/usr/bin/virsh attach-device GUESTNAME /usr/local/hostdev-mydevice.xml"<br />
ACTION=="remove", \<br />
SUBSYSTEM=="usb", \<br />
ENV{ID_VENDOR_ID}=="03f0", \<br />
ENV{ID_MODEL_ID}=="4217", \<br />
RUN+="/usr/bin/virsh detach-device GUESTNAME /usr/local/hostdev-mydevice.xml"<br />
}}<br />
<br />
[https://rolandtapken.de/blog/2011-04/how-auto-hotplug-usb-devices-libvirt-vms-update-1 Source and further reading].<br />
<br />
=== Enabling KSM ===<br />
<br />
Kernel Samepage Merging (KSM) is a feature of the Linux kernel that allows for an application to register with the kernel to have its pages merged with other processes that also register to have their pages merged. The KSM mechanism allows for guest virtual machines to share pages with each other. In an environment where many of the guest operating systems are similar, this can result in significant memory savings.<br />
<br />
{{Note|Although KSM may reduce memory usage, it may increase CPU usage. Also note some security issues may occur, see [[Wikipedia:Kernel same-page merging]].}}<br />
<br />
To enable KSM:<br />
<br />
# echo 1 > /sys/kernel/mm/ksm/run<br />
<br />
To make it permanent, use [[systemd#systemd-tmpfiles - temporary files|systemd's temporary files]]:<br />
<br />
{{hc|/etc/tmpfiles.d/ksm.conf|<br />
w /sys/kernel/mm/ksm/run - - - - 1<br />
}}<br />
<br />
If KSM is running, and there are pages to be merged (i.e. at least two similar virtual machines are running), then {{ic|/sys/kernel/mm/ksm/pages_shared}} should be non-zero. See https://docs.kernel.org/admin-guide/mm/ksm.html for more information.<br />
<br />
{{Tip|An easy way to see how well KSM is performing is to simply print the contents of all the files in that directory:<br />
<br />
$ grep -r . /sys/kernel/mm/ksm/<br />
<br />
}}<br />
<br />
=== Multi-monitor support ===<br />
<br />
The Linux QXL driver supports four heads (virtual screens) by default. This can be changed via the {{ic|1=qxl.heads=N}} kernel parameter.<br />
<br />
The default VGA memory size for QXL devices is 16M (VRAM size is 64M). This is not sufficient if you would like to enable two 1920x1200 monitors since that requires 2 × 1920 × 4 (color depth) × 1200 = 17.6 MiB VGA memory. This can be changed by replacing {{ic|-vga qxl}} by {{ic|<nowiki>-vga none -device qxl-vga,vgamem_mb=32</nowiki>}}. If you ever increase vgamem_mb beyond 64M, then you also have to increase the {{ic|vram_size_mb}} option.<br />
<br />
=== Custom display resolution ===<br />
<br />
A custom display resolution can be set with {{ic|1=-device VGA,edid=on,xres=1280,yres=720}} (see [[wikipedia:Extended_Display_Identification_Data|EDID]] and [[wikipedia:Display_resolution|display resolution]]).<br />
<br />
=== Copy and paste ===<br />
<br />
==== SPICE ====<br />
<br />
One way to share the clipboard between the host and the guest is to enable the SPICE remote desktop protocol and access the client with a SPICE client.<br />
One needs to follow the steps described in [[#SPICE]]. A guest run this way will support copy paste with the host.<br />
<br />
==== qemu-vdagent ====<br />
<br />
QEMU provides its own implementation of the spice vdagent chardev called {{ic|qemu-vdagent}}. It interfaces with the spice-vdagent guest service and allows the guest and host share a clipboard.<br />
<br />
To access this shared clipboard with QEMU's GTK display, you will need to [[#Custom build|compile QEMU from source]] with the {{ic|--enable-gtk-clipboard}} configure parameter. It is sufficient to replace the installed {{ic|qemu-ui-gtk}} package.<br />
<br />
{{Note|<br />
* Feature request {{Bug|79716}} submitted to enable the functionality in the official package.<br />
* The shared clipboard in qemu-ui-gtk has been pushed back to experimental as it can [https://gitlab.com/qemu-project/qemu/-/issues/1150 freeze guests under certain circumstances]. A fix has been proposed to solve the issue upstream.<br />
}}<br />
<br />
Add the following QEMU command line arguments:<br />
<br />
-device virtio-serial,packed=on,ioeventfd=on<br />
-device virtserialport,name=com.redhat.spice.0,chardev=vdagent0<br />
-chardev qemu-vdagent,id=vdagent0,name=vdagent,clipboard=on,mouse=off<br />
<br />
These arguments are also valid if converted to [[Libvirt#QEMU command line arguments|libvirt form]].<br />
<br />
{{Note|While the spicevmc chardev will start the spice-vdagent service of the guest automatically, the qemu-vdagent chardev may not.}}<br />
<br />
On linux guests, you may [[start]] the {{ic|spice-vdagent.service}} [[user unit]] manually. On Windows guests, set the spice-agent startup type to automatic.<br />
<br />
=== Windows-specific notes ===<br />
<br />
QEMU can run any version of Windows from Windows 95 through Windows 11.<br />
<br />
It is possible to run [[Windows PE]] in QEMU.<br />
<br />
==== Fast startup ====<br />
<br />
{{Note|An administrator account is required to change power settings.}}<br />
<br />
For Windows 8 (or later) guests it is better to disable "Turn on fast startup (recommended)" from the Power Options of the Control Panel as explained in the following [https://www.tenforums.com/tutorials/4189-turn-off-fast-startup-windows-10-a.html forum page], as it causes the guest to hang during every other boot.<br />
<br />
Fast Startup may also need to be disabled for changes to the {{ic|-smp}} option to be properly applied.<br />
<br />
==== Remote Desktop Protocol ====<br />
<br />
If you use a MS Windows guest, you might want to use RDP to connect to your guest virtual machine. If you are using a VLAN or are not in the same network as the guest, use:<br />
<br />
$ qemu-system-x86_64 -nographic -nic user,hostfwd=tcp::5555-:3389<br />
<br />
Then connect with either {{Pkg|rdesktop}} or {{Pkg|freerdp}} to the guest. For example:<br />
<br />
$ xfreerdp -g 2048x1152 localhost:5555 -z -x lan<br />
<br />
=== Clone Linux system installed on physical equipment ===<br />
<br />
Linux system installed on physical equipment can be cloned for running on a QEMU virtual machine. See [https://coffeebirthday.wordpress.com/2018/09/14/clone-linux-system-for-qemu-virtual-machine/ Clone Linux system from hardware for QEMU virtual machine]<br />
<br />
=== Chrooting into arm/arm64 environment from x86_64 ===<br />
<br />
Sometimes it is easier to work directly on a disk image instead of the real ARM based device. This can be achieved by mounting an SD card/storage containing the ''root'' partition and chrooting into it.<br />
<br />
Another use case for an ARM chroot is building ARM packages on an x86_64 machine. Here, the chroot environment can be created from an image tarball from [https://archlinuxarm.org Arch Linux ARM] - see [https://nerdstuff.org/posts/2020/2020-003_simplest_way_to_create_an_arm_chroot/] for a detailed description of this approach.<br />
<br />
Either way, from the chroot it should be possible to run ''pacman'' and install more packages, compile large libraries etc. Since the executables are for the ARM architecture, the translation to x86 needs to be performed by [[QEMU]].<br />
<br />
Install {{Pkg|qemu-user-static}} on the x86_64 machine/host, and {{Pkg|qemu-user-static-binfmt}} to register the qemu binaries to binfmt service.<br />
<br />
''qemu-user-static'' is used to allow the execution of compiled programs from other architectures. This is similar to what is provided by {{Pkg|qemu-emulators-full}}, but the "static" variant is required for chroot. Examples:<br />
<br />
qemu-arm-static path_to_sdcard/usr/bin/ls<br />
qemu-aarch64-static path_to_sdcard/usr/bin/ls<br />
<br />
These two lines execute the {{ic|ls}} command compiled for 32-bit ARM and 64-bit ARM respectively. Note that this will not work without chrooting, because it will look for libraries not present in the host system.<br />
<br />
{{Pkg|qemu-user-static}} allows automatically prefixing the ARM exectuable with {{ic|qemu-arm-static}} or {{ic|qemu-aarch64-static}}.<br />
<br />
Make sure that the ARM executable support is active:<br />
<br />
{{hc|$ ls /proc/sys/fs/binfmt_misc|<br />
qemu-aarch64 qemu-arm qemu-cris qemu-microblaze qemu-mipsel qemu-ppc64 qemu-riscv64 qemu-sh4 qemu-sparc qemu-sparc64 status<br />
qemu-alpha qemu-armeb qemu-m68k qemu-mips qemu-ppc qemu-ppc64abi32 qemu-s390x qemu-sh4eb qemu-sparc32plus register<br />
}}<br />
<br />
Each executable must be listed.<br />
<br />
If it is not active, [[restart]] {{ic|systemd-binfmt.service}}.<br />
<br />
Mount the SD card to {{ic|/mnt/sdcard}} (the device name may be different).<br />
<br />
# mount --mkdir /dev/mmcblk0p2 /mnt/sdcard<br />
<br />
Mount boot partition if needed (again, use the suitable device name):<br />
<br />
# mount /dev/mmcblk0p1 /mnt/sdcard/boot<br />
<br />
Finally ''chroot'' into the SD card root as described in [[Change root#Using chroot]]:<br />
<br />
# chroot /mnt/sdcard /bin/bash<br />
<br />
Alternatively, you can use ''arch-chroot'' from {{Pkg|arch-install-scripts}}, as it will provide an easier way to get network support:<br />
<br />
# arch-chroot /mnt/sdcard /bin/bash<br />
<br />
You can also use [[systemd-nspawn]] to chroot into the ARM environment:<br />
<br />
# systemd-nspawn -D /mnt/sdcard -M myARMMachine --bind-ro=/etc/resolv.conf<br />
<br />
{{ic|1=--bind-ro=/etc/resolv.conf}} is optional and gives a working network DNS inside the chroot<br />
<br />
==== sudo in chroot ====<br />
<br />
If you install [[sudo]] in the chroot and receive the following error when trying to use it:<br />
<br />
sudo: effective uid is not 0, is /usr/bin/sudo on a file system with the 'nosuid' option set or an NFS file system without root privileges?<br />
<br />
then you may need to modify the binfmt flags, for example for {{ic|aarch64}}:<br />
<br />
# cp /usr/lib/binfmt.d/qemu-aarch64-static.conf /etc/binfmt.d/<br />
# vi /etc/binfmt.d/qemu-aarch64-static.conf<br />
<br />
and add a {{ic|C}} at the end of this file:<br />
<br />
:qemu-aarch64:M::\x7fELF\x02\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\xb7\x00:\xff\xff\xff\xff\xff\xff\xff\x00\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff\xff:/usr/bin/qemu-aarch64-static:FPC<br />
<br />
Then [[restart]] {{ic|systemd-binfmt.service}} and check that the changes have taken effect (note the {{ic|C}} on the {{ic|flags}} line):<br />
<br />
{{hc|# cat /proc/sys/fs/binfmt_misc/qemu-aarch64|<br />
enabled<br />
interpreter /usr/bin/qemu-aarch64-static<br />
flags: POCF<br />
offset 0<br />
magic 7f454c460201010000000000000000000200b700<br />
mask ffffffffffffff00fffffffffffffffffeffffff<br />
}}<br />
<br />
See the "flags" section of the [https://docs.kernel.org/admin-guide/binfmt-misc.html kernel binfmt documentation] for more information.<br />
<br />
=== Not grabbing mouse input ===<br />
<br />
{{Style|It is not explained what the option actually does. Is it causing or avoiding the side effect?}}<br />
<br />
Tablet mode has side effect of not grabbing mouse input in QEMU window:<br />
<br />
-usb -device usb-tablet<br />
<br />
It works with several {{ic|-vga}} backends one of which is virtio.<br />
<br />
== Troubleshooting ==<br />
<br />
{{Merge|QEMU/Troubleshooting|This section is long enough to be split into a dedicated subpage.}}<br />
<br />
=== Mouse cursor is jittery or erratic ===<br />
<br />
If the cursor jumps around the screen uncontrollably, entering this on the terminal before starting QEMU might help:<br />
<br />
$ export SDL_VIDEO_X11_DGAMOUSE=0<br />
<br />
If this helps, you can add this to your {{ic|~/.bashrc}} file.<br />
<br />
=== No visible Cursor ===<br />
<br />
Add {{ic|1=-display default,show-cursor=on}} to QEMU's options to see a mouse cursor.<br />
<br />
If that still does not work, make sure you have set your display device appropriately, for example: {{ic|-vga qxl}}.<br />
<br />
Another option to try is {{ic|-usb -device usb-tablet}} as mentioned in [[#Mouse integration]]. This overrides the default PS/2 mouse emulation and synchronizes pointer location between host and guest as an added bonus.<br />
<br />
=== Two different mouse cursors are visible ===<br />
<br />
Apply the tip [[#Mouse integration]].<br />
<br />
=== Keyboard issues when using VNC ===<br />
<br />
When using VNC, you might experience keyboard problems described (in gory details) [https://www.berrange.com/posts/2010/07/04/more-than-you-or-i-ever-wanted-to-know-about-virtual-keyboard-handling/ here]. The solution is ''not'' to use the {{ic|-k}} option on QEMU, and to use {{ic|gvncviewer}} from {{Pkg|gtk-vnc}}. See also [https://www.mail-archive.com/libvir-list@redhat.com/msg13340.html this] message posted on libvirt's mailing list.<br />
<br />
=== Keyboard seems broken or the arrow keys do not work ===<br />
<br />
Should you find that some of your keys do not work or "press" the wrong key (in particular, the arrow keys), you likely need to specify your keyboard layout as an option. The keyboard layouts can be found in {{ic|/usr/share/qemu/keymaps/}}.<br />
<br />
$ qemu-system-x86_64 -k ''keymap'' ''disk_image''<br />
<br />
=== Could not read keymap file ===<br />
<br />
qemu-system-x86_64: -display vnc=0.0.0.0:0: could not read keymap file: 'en'<br />
<br />
is caused by an invalid ''keymap'' passed to the {{ic|-k}} argument. For example, {{ic|en}} is invalid, but {{ic|en-us}} is valid - see {{ic|/usr/share/qemu/keymaps/}}.<br />
<br />
=== Guest display stretches on window resize ===<br />
<br />
To restore default window size, press {{ic|Ctrl+Alt+u}}.<br />
<br />
=== ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy ===<br />
<br />
If an error message like this is printed when starting QEMU with {{ic|-enable-kvm}} option:<br />
<br />
ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy<br />
failed to initialize KVM: Device or resource busy<br />
<br />
that means another [[hypervisor]] is currently running. It is not recommended or possible to run several hypervisors in parallel.<br />
<br />
=== libgfapi error message ===<br />
<br />
The error message displayed at startup:<br />
<br />
Failed to open module: libgfapi.so.0: cannot open shared object file: No such file or directory<br />
<br />
[[Install]] {{Pkg|glusterfs}} or ignore the error message as GlusterFS is a optional dependency.<br />
<br />
=== Kernel panic on LIVE-environments ===<br />
<br />
If you start a live-environment (or better: booting a system) you may encounter this:<br />
<br />
[ end Kernel panic - not syncing: VFS: Unable to mount root fs on unknown block(0,0)<br />
<br />
or some other boot hindering process (e.g. cannot unpack initramfs, cant start service foo).<br />
Try starting the virtual machine with the {{ic|-m VALUE}} switch and an appropriate amount of RAM, if the ram is to low you will probably encounter similar issues as above/without the memory-switch.<br />
<br />
=== Windows 7 guest suffers low-quality sound ===<br />
<br />
Using the {{ic|hda}} audio driver for Windows 7 guest may result in low-quality sound. Changing the audio driver to {{ic|ac97}} by passing the {{ic|-soundhw ac97}} arguments to QEMU and installing the AC97 driver from [https://www.realtek.com/en/component/zoo/category/pc-audio-codecs-ac-97-audio-codecs-software Realtek AC'97 Audio Codecs] in the guest may solve the problem. See [https://bugzilla.redhat.com/show_bug.cgi?id=1176761#c16 Red Hat Bugzilla – Bug 1176761] for more information.<br />
<br />
=== Could not access KVM kernel module: Permission denied ===<br />
<br />
If you encounter the following error:<br />
<br />
libvirtError: internal error: process exited while connecting to monitor: Could not access KVM kernel module: Permission denied failed to initialize KVM: Permission denied<br />
<br />
Systemd 234 assigns a dynamic ID for the {{ic|kvm}} group (see {{Bug|54943}}). To avoid this error, you need edit the file {{ic|/etc/libvirt/qemu.conf}} and change the line with {{ic|1=group = "78"}} to {{ic|1=group = "kvm"}}.<br />
<br />
=== "System Thread Exception Not Handled" when booting a Windows virtual machine ===<br />
<br />
Windows 8 or Windows 10 guests may raise a generic compatibility exception at boot, namely "System Thread Exception Not Handled", which tends to be caused by legacy drivers acting strangely on real machines. On KVM machines this issue can generally be solved by setting the CPU model to {{ic|core2duo}}.<br />
<br />
=== Certain Windows games/applications crashing/causing a bluescreen ===<br />
<br />
Occasionally, applications running in the virtual machine may crash unexpectedly, whereas they would run normally on a physical machine. If, while running {{ic|dmesg -wH}} as root, you encounter an error mentioning {{ic|MSR}}, the reason for those crashes is that KVM injects a [[wikipedia:General protection fault|General protection fault]] (GPF) when the guest tries to access unsupported [[wikipedia:Model-specific register|Model-specific registers]] (MSRs) - this often results in guest applications/OS crashing. A number of those issues can be solved by passing the {{ic|1=ignore_msrs=1}} option to the KVM module, which will ignore unimplemented MSRs.<br />
<br />
{{hc|/etc/modprobe.d/kvm.conf|2=<br />
...<br />
options kvm ignore_msrs=1<br />
...<br />
}}<br />
<br />
Cases where adding this option might help:<br />
<br />
* GeForce Experience complaining about an unsupported CPU being present.<br />
* StarCraft 2 and L.A. Noire reliably blue-screening Windows 10 with {{ic|KMODE_EXCEPTION_NOT_HANDLED}}. The blue screen information does not identify a driver file in these cases.<br />
<br />
{{Warning|While this is normally safe and some applications might not work without this, silently ignoring unknown MSR accesses could potentially break other software within the virtual machine or other virtual machine.}}<br />
<br />
=== Applications in the virtual machine experience long delays or take a long time to start ===<br />
<br />
{{Out of date|No longer true since kernel 5.6}}<br />
<br />
This may be caused by insufficient available entropy in the virtual machine. Consider allowing the guest to access the hosts's entropy pool by adding a [https://wiki.qemu.org/Features/VirtIORNG VirtIO RNG device] to the virtual machine, or by installing an entropy generating daemon such as [[Haveged]].<br />
<br />
Anecdotally, OpenSSH takes a while to start accepting connections under insufficient entropy, without the logs revealing why.<br />
<br />
=== High interrupt latency and microstuttering ===<br />
<br />
This problem manifests itself as small pauses (stutters) and is particularly noticeable in graphics-intensive applications, such as games.<br />
<br />
* One of the causes is CPU power saving features, which are controlled by [[CPU frequency scaling]]. Change this to {{ic|performance}} for all processor cores. <br />
* Another possible cause is PS/2 inputs. Switch from PS/2 to Virtio inputs, see [[PCI passthrough via OVMF#Passing keyboard/mouse via Evdev]].<br />
<br />
=== QXL video causes low resolution ===<br />
<br />
QEMU 4.1.0 introduced a regression where QXL video can fall back to low resolutions, when being displayed through spice. [https://bugs.launchpad.net/qemu/+bug/1843151] For example, when KMS starts, text resolution may become as low as 4x10 characters. When trying to increase GUI resolution, it may go to the lowest supported resolution.<br />
<br />
As a workaround, create your device in this form:<br />
<br />
-device qxl-vga,max_outputs=1...<br />
<br />
=== Virtual machine not booting when using a Secure Boot enabled OVMF ===<br />
<br />
{{ic|OVMF_CODE.secboot.4m.fd}} and {{ic|OVMF_CODE.secboot.fd}} files from {{Pkg|edk2-ovmf}} are built with [[Wikipedia:System Management Mode|SMM]] support. If S3 support is not disabled in the virtual machine, then the virtual machine might not boot at all.<br />
<br />
Add the {{ic|1=-global ICH9-LPC.disable_s3=1}} option to the ''qemu'' command.<br />
<br />
See {{Bug|59465}} and https://github.com/tianocore/edk2/blob/master/OvmfPkg/README for more details and the required options to use Secure Boot in QEMU.<br />
<br />
=== Virtual machine not booting into Arch ISO ===<br />
<br />
When trying to boot the virtual machine for the first time from an Arch ISO image, the boot process hangs. Adding {{ic|1=console=ttyS0}} to kernel boot options by pressing {{ic|e}} in the boot menu you will get more boot messages and the following error:<br />
<br />
:: Mounting '/dev/disk/by-label/ARCH_202204' to '/run/archiso/bootmnt'<br />
Waiting 30 seconds for device /dev/disk/by-label/ARCH_202204 ...<br />
ERROR: '/dev/disk/by-label/ARCH_202204' device did not show up after 30 seconds...<br />
Falling back to interactive prompt<br />
You can try to fix the problem manually, log out when you are finished<br />
sh: can't access tty; job control turned off<br />
<br />
The error message does not give a good clue as to what the real issue is. The problem is with the default 128MB of RAM that QEMU allocates to the virtual machine. Increasing the limit to 1024MB with {{ic|-m 1024}} solves the issue and lets the system boot. You can continue installing Arch Linux as usual after that. Once the installation is complete, the memory allocation for the virtual machine can be decreased. The need for 1024MB is due to RAM disk requirements and size of the installation media. See [https://lists.archlinux.org/archives/list/arch-releng@lists.archlinux.org/message/D5HSGOFTPGYI6IZUEB3ZNAX4D3F3ID37/ this message on the arch-releng mailing list] and [https://bbs.archlinux.org/viewtopic.php?id=204023 this forum thread].<br />
<br />
=== Guest CPU interrupts are not firing ===<br />
<br />
If you are writing your own operating system by following the [https://wiki.osdev.org/ OSDev wiki], or are simply getting stepping through the guest architecture assembly code using QEMU's {{ic|gdb}} interface using the {{ic|-s}} flag, it is useful to know that many emulators, QEMU included, usually implement some CPU interrupts leaving many hardware interrupts unimplemented. One way to know if your code is firing an interrupt, is by using:<br />
<br />
-d int<br />
<br />
to enable showing interrupts/exceptions on stdout.<br />
<br />
To see what other guest debugging features QEMU has to offer, see:<br />
<br />
qemu-system-x86_64 -d help<br />
<br />
or replace {{ic|x86_64}} for your chosen guest architecture.<br />
<br />
=== KDE with sddm does not start spice-vdagent at login automatically ===<br />
<br />
Remove or comment out {{ic|X-GNOME-Autostart-Phase{{=}}WindowManager}} from {{ic|/etc/xdg/autostart/spice-vdagent.desktop}}. [https://github.com/systemd/systemd/issues/18791]<br />
<br />
=== Error starting domain: Requested operation is not valid: network 'default' is not active ===<br />
<br />
If for any reason the default network is deactivated, you will not be able to start any guest virtual machines which are configured to use the network. Your first attempt can be simply trying to start the network with virsh.<br />
<br />
# virsh net-start default<br />
<br />
For additional troubleshooting steps, see [https://www.xmodulo.com/network-default-is-not-active.html].<br />
<br />
== See also ==<br />
<br />
* [https://qemu.org Official QEMU website]<br />
* [https://www.linux-kvm.org Official KVM website]<br />
* [https://qemu.weilnetz.de/doc/6.0/ QEMU Emulator User Documentation]<br />
* [[Wikibooks:QEMU|QEMU Wikibook]]<br />
* [http://alien.slackbook.org/dokuwiki/doku.php?id=slackware:qemu Hardware virtualization with QEMU] by AlienBOB (last updated in 2008)<br />
* [http://blog.falconindy.com/articles/build-a-virtual-army.html Building a Virtual Army] by Falconindy<br />
* [https://git.qemu.org/?p=qemu.git;a=tree;f=docs Lastest docs]<br />
* [https://qemu.weilnetz.de/ QEMU on Windows]<br />
* [[wikipedia:Qemu|Wikipedia]]<br />
* [[debian:QEMU|Debian Wiki - QEMU]]<br />
* [https://people.gnome.org/~markmc/qemu-networking.html QEMU Networking on gnome.org]{{Dead link|2022|09|22|status=404}}<br />
* [http://bsdwiki.reedmedia.net/wiki/networking_qemu_virtual_bsd_systems.html Networking QEMU Virtual BSD Systems]<br />
* [https://www.gnu.org/software/hurd/hurd/running/qemu.html QEMU on gnu.org]<br />
* [https://wiki.freebsd.org/qemu QEMU on FreeBSD as host]<br />
* [https://wiki.mikejung.biz/KVM_/_Xen KVM/QEMU Virtio Tuning and SSD VM Optimization Guide]{{Dead link|2022|09|22|status=404}}<br />
* [https://doc.opensuse.org/documentation/leap/virtualization/html/book-virt/part-virt-qemu.html Managing Virtual Machines with QEMU - openSUSE documentation]<br />
* [https://www.ibm.com/support/knowledgecenter/en/linuxonibm/liaat/liaatkvm.htm KVM on IBM Knowledge Center]</div>Malcontenthttps://wiki.archlinux.org/index.php?title=QEMU&diff=796033QEMU2024-01-04T14:15:08Z<p>Malcontent: Add missing comma</p>
<hr />
<div>[[Category:Emulation]]<br />
[[Category:Hypervisors]]<br />
[[de:QEMU]]<br />
[[es:QEMU]]<br />
[[fr:QEMU]]<br />
[[ja:QEMU]]<br />
[[zh-hans:QEMU]]<br />
{{Related articles start}}<br />
{{Related|:Category:Hypervisors}}<br />
{{Related|Libvirt}}<br />
{{Related|QEMU/Guest graphics acceleration}}<br />
{{Related|PCI passthrough via OVMF}}<br />
{{Related articles end}}<br />
<br />
According to the [https://wiki.qemu.org/Main_Page QEMU about page], "QEMU is a generic and open source machine emulator and virtualizer."<br />
<br />
When used as a machine emulator, QEMU can run OSes and programs made for one machine (e.g. an ARM board) on a different machine (e.g. your x86 PC). By using dynamic translation, it achieves very good performance.<br />
<br />
QEMU can use other hypervisors like [[Xen]] or [[KVM]] to use CPU extensions ([[Wikipedia:Hardware-assisted virtualization|HVM]]) for virtualization. When used as a virtualizer, QEMU achieves near native performances by executing the guest code directly on the host CPU.<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|qemu-full}} package (or {{Pkg|qemu-base}} for the version without GUI) and below optional packages for your needs:<br />
<br />
* {{Pkg|qemu-block-gluster}} - [[Glusterfs]] block support<br />
* {{Pkg|qemu-block-iscsi}} - [[iSCSI]] block support<br />
* {{Pkg|samba}} - [[Samba|SMB/CIFS]] server support<br />
<br />
Alternatively, {{Pkg|qemu-user-static}} exists as a usermode and static variant.<br />
<br />
=== QEMU variants ===<br />
<br />
QEMU is offered in several variants suited for different use cases.<br />
<br />
As a first classification, QEMU is offered in full-system and usermode emulation modes:<br />
<br />
; Full-system emulation<br />
: In this mode, QEMU emulates a full system, including one or several processors and various peripherals. It is more accurate but slower, and does not require the emulated OS to be Linux.<br />
: QEMU commands for full-system emulation are named {{ic|qemu-system-''target_architecture''}}, e.g. {{ic|qemu-system-x86_64}} for emulating [[Wikipedia:x86_64|x86_64]] CPUs, {{ic|qemu-system-i386}} for Intel [[Wikipedia:i386|32-bit x86]] CPUs, {{ic|qemu-system-arm}} for [[Wikipedia:ARM architecture family#32-bit architecture|ARM (32 bits)]], {{ic|qemu-system-aarch64}} for [[Wikipedia:AArch64|ARM64]], etc.<br />
: If the target architecture matches the host CPU, this mode may still benefit from a significant speedup by using a hypervisor like [[#Enabling KVM|KVM]] or Xen.<br />
; [https://www.qemu.org/docs/master/user/main.html Usermode emulation]<br />
: In this mode, QEMU is able to invoke a Linux executable compiled for a (potentially) different architecture by leveraging the host system resources. There may be compatibility issues, e.g. some features may not be implemented, dynamically linked executables will not work out of the box (see [[#Chrooting into arm/arm64 environment from x86_64]] to address this) and only Linux is supported (although [https://wiki.winehq.org/Emulation Wine may be used] for running Windows executables).<br />
: QEMU commands for usermode emulation are named {{ic|qemu-''target_architecture''}}, e.g. {{ic|qemu-x86_64}} for emulating 64-bit CPUs.<br />
<br />
QEMU is offered in dynamically-linked and statically-linked variants:<br />
<br />
; Dynamically-linked (default): {{ic|qemu-*}} commands depend on the host OS libraries, so executables are smaller.<br />
; Statically-linked: {{ic|qemu-*}} commands can be copied to any Linux system with the same architecture.<br />
<br />
In the case of Arch Linux, full-system emulation is offered as:<br />
<br />
; Non-headless (default): This variant enables GUI features that require additional dependencies (like SDL or GTK).<br />
; Headless: This is a slimmer variant that does not require GUI (this is suitable e.g. for servers).<br />
<br />
Note that headless and non-headless versions install commands with the same name (e.g. {{ic|qemu-system-x86_64}}) and thus cannot be both installed at the same time.<br />
<br />
=== Details on packages available in Arch Linux ===<br />
<br />
* The {{Pkg|qemu-desktop}} package provides the {{ic|x86_64}} architecture emulators for full-system emulation ({{ic|qemu-system-x86_64}}). The {{Pkg|qemu-emulators-full}} package provides the {{ic|x86_64}} usermode variant ({{ic|qemu-x86_64}}) and also for the rest of supported architectures it includes both full-system and usermode variants (e.g. {{ic|qemu-system-arm}} and {{ic|qemu-arm}}).<br />
* The headless versions of these packages (only applicable to full-system emulation) are {{Pkg|qemu-base}} ({{ic|x86_64}}-only) and {{Pkg|qemu-emulators-full}} (rest of architectures).<br />
* Full-system emulation can be expanded with some QEMU modules present in separate packages: {{Pkg|qemu-block-gluster}}, {{Pkg|qemu-block-iscsi}} and {{Pkg|qemu-guest-agent}}.<br />
* {{Pkg|qemu-user-static}} provides a usermode and static variant for all target architectures supported by QEMU. The installed QEMU commands are named {{ic|qemu-''target_architecture''-static}}, for example, {{ic|qemu-x86_64-static}} for intel 64-bit CPUs.<br />
<br />
{{Note|At present, Arch does not offer a full-system mode and statically linked variant (neither officially nor via AUR), as this is usually not needed.}}<br />
<br />
=== Custom build ===<br />
<br />
{{Remove|Explaining how to use the [[Arch build system]] is out of scope here. There is no motivation for the customization in the first place.}}<br />
<br />
To obtain a customized version of QEMU, [[Git#Getting a Git repository|clone]] the package source of {{Pkg|qemu-common}} or {{AUR|qemu-git}}.<br />
<br />
The respective [[PKGBUILD]] file calls QEMU's [https://www.gnu.org/prep/standards/html_node/Configuration.html configure script] which accepts parameters obtainable by first manually running --help on it. <br />
To access this help beforehand, you may [[Makepkg#Usage|use makepkg]] to let it download and extract the QEMU source, canceling the build process as soon as the configure script begins.<br />
<br />
With the PKGBUILD file's configure script calls modified as desired, you may [[Makepkg#Usage|use makepkg]] (again) to let it build the packages, though it is inadvisable to let it install them as conflicting headless / static packages will be built as well and a typical user certainly won't need the additional system emulators for the other architectures.<br />
<br />
When the build process completes, it is advisable to instead copy your desired packages (see the [[#Removal|list for qemu-desktop in "Removal"]]{{Broken section link}}) to a different directory, [[Pacman#Additional commands|let pacman install them all]] and add them to the [[Pacman#Skip package from being upgraded|IgnorePkg]] list so you get to upgrade them manually.<br />
<br />
== Graphical front-ends for QEMU ==<br />
<br />
Unlike other virtualization programs such as [[VirtualBox]] and [[VMware]], QEMU does not provide a GUI to manage virtual machines (other than the window that appears when running a virtual machine), nor does it provide a way to create persistent virtual machines with saved settings. All parameters to run a virtual machine must be specified on the command line at every launch, unless you have created a custom script to start your virtual machine(s).<br />
<br />
[[Libvirt]] provides a convenient way to manage QEMU virtual machines. See [[Libvirt#Client|list of libvirt clients]] for available front-ends.<br />
<br />
== Creating new virtualized system ==<br />
<br />
=== Creating a hard disk image ===<br />
<br />
{{Accuracy|If I get the man page right the raw format only allocates the full size if the filesystem does not support "holes" or it is <br />
explicitly told to preallocate. See {{man|1|qemu-img|NOTES}}.}} <br />
<br />
{{Tip|See [[Wikibooks:QEMU/Images]] for more information on QEMU images.}}<br />
<br />
To run QEMU you will need a hard disk image, unless you are booting a live system from CD-ROM or the network (and not doing so to install an operating system to a hard disk image). A hard disk image is a file which stores the contents of the emulated hard disk.<br />
<br />
A hard disk image can be ''raw'', so that it is literally byte-by-byte the same as what the guest sees, and will always use the full capacity of the guest hard drive on the host. This method provides the least I/O overhead, but can waste a lot of space, as not-used space on the guest cannot be used on the host.<br />
<br />
Alternatively, the hard disk image can be in a format such as ''qcow2'' which only allocates space to the image file when the guest operating system actually writes to those sectors on its virtual hard disk. The image appears as the full size to the guest operating system, even though it may take up only a very small amount of space on the host system. This image format also supports QEMU snapshotting functionality (see [[#Creating and managing snapshots via the monitor console]] for details). However, using this format instead of ''raw'' will likely affect performance.<br />
<br />
QEMU provides the {{ic|qemu-img}} command to create hard disk images. For example to create a 4 GiB image in the ''raw'' format:<br />
<br />
$ qemu-img create -f raw ''image_file'' 4G<br />
<br />
You may use {{ic|-f qcow2}} to create a ''qcow2'' disk instead.<br />
<br />
{{Note|You can also simply create a ''raw'' image by creating a file of the needed size using {{ic|dd}} or {{ic|fallocate}}.}}<br />
<br />
{{Warning|If you store the hard disk images on a [[Btrfs]] file system, you should consider disabling [[Btrfs#Copy-on-Write (CoW)|Copy-on-Write]] for the directory before creating any images.}}<br />
<br />
==== Overlay storage images ====<br />
<br />
You can create a storage image once (the 'backing' image) and have QEMU keep mutations to this image in an overlay image. This allows you to revert to a previous state of this storage image. You could revert by creating a new overlay image at the time you wish to revert, based on the original backing image.<br />
<br />
To create an overlay image, issue a command like:<br />
<br />
$ qemu-img create -o backing_file=''img1.raw'',backing_fmt=''raw'' -f ''qcow2'' ''img1.cow''<br />
<br />
After that you can run your QEMU virtual machine as usual (see [[#Running virtualized system]]):<br />
<br />
$ qemu-system-x86_64 ''img1.cow''<br />
<br />
The backing image will then be left intact and mutations to this storage will be recorded in the overlay image file.<br />
<br />
When the path to the backing image changes, repair is required.<br />
<br />
{{Warning|The backing image's absolute filesystem path is stored in the (binary) overlay image file. Changing the backing image's path requires some effort.}}<br />
<br />
Make sure that the original backing image's path still leads to this image. If necessary, make a symbolic link at the original path to the new path. Then issue a command like:<br />
<br />
$ qemu-img rebase -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
At your discretion, you may alternatively perform an 'unsafe' rebase where the old path to the backing image is not checked:<br />
<br />
$ qemu-img rebase -u -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
==== Resizing an image ====<br />
<br />
{{Warning|Resizing an image containing an NTFS boot file system could make the operating system installed on it unbootable. It is recommended to create a backup first.}}<br />
<br />
The {{ic|qemu-img}} executable has the {{ic|resize}} option, which enables easy resizing of a hard drive image. It works for both ''raw'' and ''qcow2''. For example, to increase image space by 10 GiB, run:<br />
<br />
$ qemu-img resize ''disk_image'' +10G<br />
<br />
After enlarging the disk image, you must use file system and partitioning tools inside the virtual machine to actually begin using the new space. <br />
<br />
===== Shrinking an image =====<br />
<br />
When shrinking a disk image, you must first reduce the allocated file systems and partition sizes using the file system and partitioning tools inside the virtual machine and then shrink the disk image accordingly. For a Windows guest, this can be performed from the "create and format hard disk partitions" control panel.<br />
<br />
{{Warning|Proceeding to shrink the disk image without reducing the guest partition sizes will result in data loss.}}<br />
<br />
Then, to decrease image space by 10 GiB, run:<br />
<br />
$ qemu-img resize --shrink ''disk_image'' -10G<br />
<br />
==== Converting an image ====<br />
<br />
You can convert an image to other formats using {{ic|qemu-img convert}}. This example shows how to convert a ''raw'' image to ''qcow2'':<br />
<br />
$ qemu-img convert -f raw -O qcow2 ''input''.img ''output''.qcow2<br />
<br />
This will not remove the original input file.<br />
<br />
=== Preparing the installation media ===<br />
<br />
To install an operating system into your disk image, you need the installation medium (e.g. optical disc, USB-drive, or ISO image) for the operating system. The installation medium should not be mounted because QEMU accesses the media directly.<br />
<br />
{{Tip|If using an optical disc, it is a good idea to first dump the media to a file because this both improves performance and does not require you to have direct access to the devices (that is, you can run QEMU as a regular user without having to change access permissions on the media's device file). For example, if the CD-ROM device node is named {{ic|/dev/cdrom}}, you can dump it to a file with the command: {{bc|1=$ dd if=/dev/cdrom of=''cd_image.iso'' bs=4k}}}}<br />
<br />
=== Installing the operating system ===<br />
<br />
This is the first time you will need to start the emulator. To install the operating system on the disk image, you must attach both the disk image and the installation media to the virtual machine, and have it boot from the installation media.<br />
<br />
For example on i386 guests, to install from a bootable ISO file as CD-ROM and a raw disk image:<br />
<br />
$ qemu-system-x86_64 -cdrom ''iso_image'' -boot order=d -drive file=''disk_image'',format=raw<br />
<br />
See {{man|1|qemu}} for more information about loading other media types (such as floppy, disk images or physical drives) and [[#Running virtualized system]] for other useful options.<br />
<br />
After the operating system has finished installing, the QEMU image can be booted directly (see [[#Running virtualized system]]).<br />
<br />
{{Note|By default only 128 MiB of memory is assigned to the machine. The amount of memory can be adjusted with the {{ic|-m}} switch, for example {{ic|-m 512M}} or {{ic|-m 2G}}.}}<br />
<br />
{{Tip|<br />
* Instead of specifying {{ic|1=-boot order=x}}, some users may feel more comfortable using a boot menu: {{ic|1=-boot menu=on}}, at least during configuration and experimentation.<br />
* When running QEMU in headless mode, it starts a local VNC server on port 5900 per default. You can use [[TigerVNC]] to connect to the guest OS: {{ic|vncviewer :5900}}<br />
* If you need to replace floppies or CDs as part of the installation process, you can use the QEMU machine monitor (press {{ic|Ctrl+Alt+2}} in the virtual machine's window) to remove and attach storage devices to a virtual machine. Type {{ic|info block}} to see the block devices, and use the {{ic|change}} command to swap out a device. Press {{ic|Ctrl+Alt+1}} to go back to the virtual machine.<br />
}}<br />
<br />
== Running virtualized system ==<br />
<br />
{{ic|qemu-system-*}} binaries (for example {{ic|qemu-system-i386}} or {{ic|qemu-system-x86_64}}, depending on guest's architecture) are used to run the virtualized guest. The usage is:<br />
<br />
$ qemu-system-x86_64 ''options'' ''disk_image''<br />
<br />
Options are the same for all {{ic|qemu-system-*}} binaries, see {{man|1|qemu}} for documentation of all options.<br />
<br />
Usually, if an option has many possible values, you can use<br />
<br />
$ qemu-system-x86_64 ''option'' ''help''<br />
<br />
to list all possible values. If it supports properties, you can use<br />
<br />
$ qemu-system-x86_64 ''option'' ''value,help''<br />
<br />
to list all available properties.<br />
<br />
For example:<br />
$ qemu-system-x86_64 -machine help<br />
$ qemu-system-x86_64 -machine q35,help<br />
$ qemu-system-x86_64 -device help<br />
$ qemu-system-x86_64 -device qxl,help<br />
<br />
You can use these methods and the {{man|1|qemu}} documentation to understand the options used in follow sections.<br />
<br />
By default, QEMU will show the virtual machine's video output in a window. One thing to keep in mind: when you click inside the QEMU window, the mouse pointer is grabbed. To release it, press {{ic|Ctrl+Alt+g}}.<br />
<br />
{{Warning|QEMU should never be run as root. If you must launch it in a script as root, you should use the {{ic|-runas}} option to make QEMU drop root privileges.}}<br />
<br />
=== Enabling KVM ===<br />
<br />
KVM (''Kernel-based Virtual Machine'') full virtualization must be supported by your Linux kernel and your hardware, and necessary [[kernel modules]] must be loaded. See [[KVM]] for more information.<br />
<br />
To start QEMU in KVM mode, append {{ic|-accel kvm}} to the additional start options. To check if KVM is enabled for a running virtual machine, enter the [[#QEMU monitor]] and type {{ic|info kvm}}.<br />
<br />
{{Note|<br />
* The argument {{ic|1=accel=kvm}} of the {{ic|-machine}} option is equivalent to the {{ic|-enable-kvm}} or the {{ic|-accel kvm}} option.<br />
* CPU model {{ic|host}} requires KVM.<br />
* If you start your virtual machine with a GUI tool and experience very bad performance, you should check for proper KVM support, as QEMU may be falling back to software emulation.<br />
* KVM needs to be enabled in order to start Windows 7 or Windows 8 properly without a ''blue screen''.<br />
}}<br />
<br />
=== Enabling IOMMU (Intel VT-d/AMD-Vi) support ===<br />
<br />
First enable IOMMU, see [[PCI passthrough via OVMF#Setting up IOMMU]].<br />
<br />
Add {{ic|-device intel-iommu}} to create the IOMMU device:<br />
<br />
$ qemu-system-x86_64 '''-enable-kvm -machine q35 -device intel-iommu''' -cpu host ..<br />
<br />
{{Note|<br />
On Intel CPU based systems creating an IOMMU device in a QEMU guest with {{ic|-device intel-iommu}} will disable PCI passthrough with an error like: {{bc|Device at bus pcie.0 addr 09.0 requires iommu notifier which is currently not supported by intel-iommu emulation}} While adding the kernel parameter {{ic|1=intel_iommu=on}} is still needed for remapping IO (e.g. [[PCI passthrough via OVMF#Isolating the GPU|PCI passthrough with vfio-pci]]), {{ic|-device intel-iommu}} should not be set if PCI passthrough is required.<br />
}}<br />
<br />
=== Booting in UEFI mode ===<br />
<br />
The default firmware used by QEMU is [https://www.coreboot.org/SeaBIOS SeaBIOS], which is a Legacy BIOS implementation. QEMU uses {{ic|/usr/share/qemu/bios-256k.bin}} (provided by the {{Pkg|seabios}} package) as a default read-only (ROM) image. You can use the {{ic|-bios}} argument to select another firmware file. However, UEFI requires writable memory to work properly, so you need to emulate [https://wiki.qemu.org/Features/PC_System_Flash PC System Flash] instead.<br />
<br />
[https://github.com/tianocore/tianocore.github.io/wiki/OVMF OVMF] is a TianoCore project to enable UEFI support for Virtual Machines. It can be [[install]]ed with the {{Pkg|edk2-ovmf}} package.<br />
<br />
There are two ways to use OVMF as a firmware. The first is to copy {{ic|/usr/share/edk2/x64/OVMF.4m.fd}}, make it writable and use as a pflash drive:<br />
<br />
-drive if=pflash,format=raw,file=''/copy/of/OVMF.4m.fd''<br />
<br />
All changes to the UEFI settings will be saved directly to this file.<br />
<br />
Another and more preferable way is to split OVMF into two files. The first one will be read-only and store the firmware executable, and the second one will be used as a writable variable store. The advantage is that you can use the firmware file directly without copying, so it will be updated automatically by [[pacman]].<br />
<br />
Use {{ic|/usr/share/edk2/x64/OVMF_CODE.4m.fd}} as a first read-only pflash drive. Copy {{ic|/usr/share/edk2/x64/OVMF_VARS.4m.fd}}, make it writable and use as a second writable pflash drive:<br />
<br />
-drive if=pflash,format=raw,readonly=on,file=/usr/share/edk2/x64/OVMF_CODE.4m.fd \<br />
-drive if=pflash,format=raw,file=''/copy/of/OVMF_VARS.4m.fd''<br />
<br />
If secure boot is wanted, replace {{ic|/usr/share/edk2/x64/OVMF_CODE.4m.fd}} with {{ic|/usr/share/edk2/x64/OVMF_CODE.secboot.4m.fd}}.<br />
<br />
=== Trusted Platform Module emulation ===<br />
<br />
QEMU can emulate [[Trusted Platform Module]], which is required by some systems such as Windows 11 (which requires TPM 2.0).<br />
<br />
[[Install]] the {{Pkg|swtpm}} package, which provides a software TPM implementation. Create some directory for storing TPM data ({{ic|''/path/to/mytpm''}} will be used as an example). Run this command to start the emulator:<br />
<br />
$ swtpm socket --tpm2 --tpmstate dir=''/path/to/mytpm'' --ctrl type=unixio,path=''/path/to/mytpm/swtpm-sock''<br />
<br />
{{ic|''/path/to/mytpm/swtpm-sock''}} will be created by ''swtpm'': this is a UNIX socket to which QEMU will connect. You can put it in any directory.<br />
<br />
By default, ''swtpm'' starts a TPM version 1.2 emulator. The {{ic|--tpm2}} option enables TPM 2.0 emulation.<br />
<br />
Finally, add the following options to QEMU:<br />
<br />
-chardev socket,id=chrtpm,path=''/path/to/mytpm/swtpm-sock'' \<br />
-tpmdev emulator,id=tpm0,chardev=chrtpm \<br />
-device tpm-tis,tpmdev=tpm0<br />
<br />
and TPM will be available inside the virtual machine. After shutting down the virtual machine, ''swtpm'' will be automatically terminated.<br />
<br />
See [https://qemu-project.gitlab.io/qemu/specs/tpm.html the QEMU documentation] for more information. <br />
<br />
If guest OS still doesn't recognize the TPM device, try to adjust ''CPU Models and Topology'' options. It might cause problem.<br />
<br />
== Sharing data between host and guest ==<br />
<br />
=== Network ===<br />
<br />
Data can be shared between the host and guest OS using any network protocol that can transfer files, such as [[NFS]], [[SMB]], [[Wikipedia:Network block device|NBD]], HTTP, [[Very Secure FTP Daemon|FTP]], or [[SSH]], provided that you have set up the network appropriately and enabled the appropriate services.<br />
<br />
The default user-mode networking allows the guest to access the host OS at the IP address 10.0.2.2. Any servers that you are running on your host OS, such as a SSH server or SMB server, will be accessible at this IP address. So on the guests, you can mount directories exported on the host via [[SMB]] or [[NFS]], or you can access the host's HTTP server, etc.<br />
It will not be possible for the host OS to access servers running on the guest OS, but this can be done with other network configurations (see [[#Tap networking with QEMU]]).<br />
<br />
=== QEMU's port forwarding ===<br />
<br />
{{Note|QEMU's port forwarding is IPv4-only. IPv6 port forwarding is not implemented and the last patches were proposed in 2018.[https://lore.kernel.org/qemu-devel/1540512223-21199-1-git-send-email-max7255@yandex-team.ru/T/#u]}}<br />
<br />
QEMU can forward ports from the host to the guest to enable e.g. connecting from the host to an SSH server running on the guest.<br />
<br />
For example, to bind port 60022 on the host with port 22 (SSH) on the guest, start QEMU with a command like:<br />
<br />
$ qemu-system-x86_64 ''disk_image'' -nic user,hostfwd=tcp::60022-:22<br />
<br />
Make sure the sshd is running on the guest and connect with:<br />
<br />
$ ssh ''guest-user''@127.0.0.1 -p 60022<br />
<br />
You can use [[SSHFS]] to mount the guest's file system at the host for shared read and write access.<br />
<br />
To forward several ports, you just repeat the {{ic|hostfwd}} in the {{ic|-nic}} argument, e.g. for VNC's port:<br />
<br />
$ qemu-system-x86_64 ''disk_image'' -nic user,hostfwd=tcp::60022-:22,hostfwd=tcp::5900-:5900<br />
<br />
=== QEMU's built-in SMB server ===<br />
<br />
QEMU's documentation says it has a "built-in" SMB server, but actually it just starts up [[Samba]] on the host with an automatically generated {{ic|smb.conf}} file located in {{ic|/tmp/qemu-smb.''random_string''}} and makes it accessible to the guest at a different IP address (10.0.2.4 by default). This only works for user networking, and is useful when you do not want to start the normal [[Samba]] service on the host, which the guest can also access if you have set up shares on it.<br />
<br />
Only a single directory can be set as shared with the option {{ic|1=smb=}}, but adding more directories (even while the virtual machine is running) could be as easy as creating symbolic links in the shared directory if QEMU configured SMB to follow symbolic links. It does not do so, but the configuration of the running SMB server can be changed as described below.<br />
<br />
''Samba'' must be installed on the host. To enable this feature, start QEMU with a command like:<br />
<br />
$ qemu-system-x86_64 -nic user,id=nic0,smb=''shared_dir_path'' ''disk_image''<br />
<br />
where {{ic|''shared_dir_path''}} is a directory that you want to share between the guest and host.<br />
<br />
Then, in the guest, you will be able to access the shared directory on the host 10.0.2.4 with the share name "qemu". For example, in Windows Explorer you would go to {{ic|\\10.0.2.4\qemu}}.<br />
<br />
{{Note|<br />
* If you are using sharing options multiple times like {{ic|1=-net user,smb=''shared_dir_path1'' -net user,smb=''shared_dir_path2''}} or {{ic|1=-net user,smb=''shared_dir_path1'',smb=''shared_dir_path2''}} then it will share only the last defined one.<br />
* If you cannot access the shared folder and the guest system is Windows, check that the [http://ecross.mvps.org/howto/enable-netbios-over-tcp-ip-with-windows.htm NetBIOS protocol is enabled]{{Dead link|2023|05|06|status=domain name not resolved}} and that a firewall does not block [https://technet.microsoft.com/en-us/library/cc940063.aspx ports] used by the NetBIOS protocol.<br />
* If you cannot access the shared folder and the guest system is Windows 10 Enterprise or Education or Windows Server 2016, [https://support.microsoft.com/en-us/help/4046019 enable guest access].<br />
* If you use [[#Tap networking with QEMU]], use {{ic|1=-device virtio-net,netdev=vmnic -netdev user,id=vmnic,smb=''shared_dir_path''}} to get SMB.<br />
}}<br />
<br />
One way to share multiple directories and to add or remove them while the virtual machine is running, is to share an empty directory and create/remove symbolic links to the directories in the shared directory. For this to work, the configuration of the running SMB server can be changed with the following script, which also allows the execution of files on the guest that are not set executable on the host:<br />
<br />
#!/bin/sh<br />
eval $(ps h -C smbd -o pid,args | grep /tmp/qemu-smb | gawk '{print "pid="$1";conf="$6}')<br />
echo "[global]<br />
allow insecure wide links = yes<br />
[qemu]<br />
follow symlinks = yes<br />
wide links = yes<br />
acl allow execute always = yes" >> "$conf"<br />
# in case the change is not detected automatically:<br />
smbcontrol --configfile="$conf" "$pid" reload-config<br />
<br />
This can be applied to the running server started by qemu only after the guest has connected to the network drive the first time. An alternative to this method is to add additional shares to the configuration file like so:<br />
<br />
echo "[''myshare'']<br />
path=''another_path''<br />
read only=no<br />
guest ok=yes<br />
force user=''username''" >> $conf<br />
<br />
This share will be available on the guest as {{ic|\\10.0.2.4\''myshare''}}.<br />
<br />
=== Using filesystem passthrough and VirtFS ===<br />
<br />
See the [https://wiki.qemu.org/Documentation/9psetup QEMU documentation].<br />
<br />
=== Host file sharing with virtiofsd ===<br />
<br />
{{Style|See [[Help:Style/Formatting and punctuation]].}}<br />
<br />
virtiofsd is shipped with QEMU package. Documentation is available [https://qemu-stsquad.readthedocs.io/en/docs-next/tools/virtiofsd.html online]{{Dead link|2023|05|06|status=404}} or {{ic|/usr/share/doc/qemu/qemu/tools/virtiofsd.html}} on local file system with {{Pkg|qemu-docs}} installed.<br />
<br />
Add user that runs qemu to the 'kvm' [[user group]], because it needs to access the virtiofsd socket. You might have to logout for change to take effect.<br />
<br />
{{Accuracy|Running services as root is not secure. Also the process should be wrapped in a systemd service.}}<br />
<br />
Start as virtiofsd as root:<br />
<br />
# /usr/lib/virtiofsd --socket-path=/var/run/qemu-vm-001.sock --shared-dir /tmp/vm-001 --cache always<br />
<br />
where<br />
<br />
* {{ic|/var/run/qemu-vm-001.sock}} is a socket file,<br />
* {{ic|/tmp/vm-001}} is a shared directory between the host and the guest virtual machine.<br />
<br />
The created socket file has root only access permission. Give group kvm access to it with:<br />
<br />
# chgrp kvm qemu-vm-001.sock; chmod g+rxw qemu-vm-001.sock<br />
<br />
Add the following configuration options when starting the virtual machine:<br />
<br />
-object memory-backend-memfd,id=mem,size=4G,share=on \<br />
-numa node,memdev=mem \<br />
-chardev socket,id=char0,path=/var/run/qemu-vm-001.sock \<br />
-device vhost-user-fs-pci,chardev=char0,tag=myfs<br />
<br />
where<br />
<br />
{{Expansion|Explain the remaining options (or remove them if they are not necessary).}}<br />
<br />
* {{ic|1=size=4G}} shall match size specified with {{ic|-m 4G}} option,<br />
* {{ic|/var/run/qemu-vm-001.sock}} points to socket file started earlier,<br />
<br />
{{Style|The section should not be specific to Windows.}}<br />
<br />
Remember, that guest must be configured to enable sharing. For Windows there are [https://virtio-fs.gitlab.io/howto-windows.html instructions]. Once configured, Windows will have the {{ic|Z:}} drive mapped automatically with shared directory content.<br />
<br />
Your Windows 10 guest system is properly configured if it has:<br />
<br />
* VirtioFSSService windows service,<br />
* WinFsp.Launcher windows service,<br />
* VirtIO FS Device driver under "System devices" in Windows "Device Manager".<br />
<br />
If the above installed and {{ic|Z:}} drive is still not listed, try repairing "Virtio-win-guest-tools" in Windows ''Add/Remove programs''.<br />
<br />
=== Mounting a partition of the guest on the host ===<br />
<br />
It can be useful to mount a drive image under the host system, it can be a way to transfer files in and out of the guest. This should be done when the virtual machine is not running.<br />
<br />
The procedure to mount the drive on the host depends on the type of qemu image, ''raw'' or ''qcow2''. We detail thereafter the steps to mount a drive in the two formats in [[#Mounting a partition from a raw image]] and [[#Mounting a partition from a qcow2 image]]. For the full documentation see [[Wikibooks:QEMU/Images#Mounting an image on the host]].<br />
<br />
{{Warning|You must unmount the partitions before running the virtual machine again. Otherwise, data corruption is very likely to occur.}}<br />
<br />
==== Mounting a partition from a raw image ====<br />
<br />
It is possible to mount partitions that are inside a raw disk image file by setting them up as loopback devices.<br />
<br />
===== With manually specifying byte offset =====<br />
<br />
One way to mount a disk image partition is to mount the disk image at a certain offset using a command like the following:<br />
<br />
# mount -o loop,offset=32256 ''disk_image'' ''mountpoint''<br />
<br />
The {{ic|1=offset=32256}} option is actually passed to the {{ic|losetup}} program to set up a loopback device that starts at byte offset 32256 of the file and continues to the end. This loopback device is then mounted. You may also use the {{ic|sizelimit}} option to specify the exact size of the partition, but this is usually unnecessary.<br />
<br />
Depending on your disk image, the needed partition may not start at offset 32256. Run {{ic|fdisk -l ''disk_image''}} to see the partitions in the image. fdisk gives the start and end offsets in 512-byte sectors, so multiply by 512 to get the correct offset to pass to {{ic|mount}}.<br />
<br />
===== With loop module autodetecting partitions =====<br />
<br />
The Linux loop driver actually supports partitions in loopback devices, but it is disabled by default. To enable it, do the following:<br />
<br />
* Get rid of all your loopback devices (unmount all mounted images, etc.).<br />
* [[Kernel modules#Manual module handling|Unload]] the {{ic|loop}} kernel module, and load it with the {{ic|1=max_part=15}} parameter set. Additionally, the maximum number of loop devices can be controlled with the {{ic|max_loop}} parameter.<br />
<br />
{{Tip|You can put an entry in {{ic|/etc/modprobe.d}} to load the loop module with {{ic|1=max_part=15}} every time, or you can put {{ic|1=loop.max_part=15}} on the kernel command-line, depending on whether you have the {{ic|loop.ko}} module built into your kernel or not.}}<br />
<br />
Set up your image as a loopback device:<br />
<br />
# losetup -f -P ''disk_image''<br />
<br />
Then, if the device created was {{ic|/dev/loop0}}, additional devices {{ic|/dev/loop0p''X''}} will have been automatically created, where X is the number of the partition. These partition loopback devices can be mounted directly. For example:<br />
<br />
# mount /dev/loop0p1 ''mountpoint''<br />
<br />
To mount the disk image with ''udisksctl'', see [[Udisks#Mount loop devices]].<br />
<br />
===== With kpartx =====<br />
<br />
''kpartx'' from the {{Pkg|multipath-tools}} package can read a partition table on a device and create a new device for each partition. For example:<br />
<br />
# kpartx -a ''disk_image''<br />
<br />
This will setup the loopback device and create the necessary partition(s) device(s) in {{ic|/dev/mapper/}}.<br />
<br />
==== Mounting a partition from a qcow2 image ====<br />
<br />
We will use {{ic|qemu-nbd}}, which lets use the NBD (''network block device'') protocol to share the disk image.<br />
<br />
First, we need the ''nbd'' module loaded:<br />
<br />
# modprobe nbd max_part=16<br />
<br />
Then, we can share the disk and create the device entries:<br />
<br />
# qemu-nbd -c /dev/nbd0 ''/path/to/image.qcow2''<br />
<br />
Discover the partitions:<br />
<br />
# partprobe /dev/nbd0<br />
<br />
''fdisk'' can be used to get information regarding the different partitions in {{ic|''nbd0''}}:<br />
<br />
{{hc|# fdisk -l /dev/nbd0|2=<br />
Disk /dev/nbd0: 25.2 GiB, 27074281472 bytes, 52879456 sectors<br />
Units: sectors of 1 * 512 = 512 bytes<br />
Sector size (logical/physical): 512 bytes / 512 bytes<br />
I/O size (minimum/optimal): 512 bytes / 512 bytes<br />
Disklabel type: dos<br />
Disk identifier: 0xa6a4d542<br />
<br />
Device Boot Start End Sectors Size Id Type<br />
/dev/nbd0p1 * 2048 1026047 1024000 500M 7 HPFS/NTFS/exFAT<br />
/dev/nbd0p2 1026048 52877311 51851264 24.7G 7 HPFS/NTFS/exFAT}}<br />
<br />
Then mount any partition of the drive image, for example the partition 2:<br />
<br />
# mount /dev/nbd0'''p2''' ''mountpoint''<br />
<br />
After the usage, it is important to unmount the image and reverse previous steps, i.e. unmount the partition and disconnect the nbd device:<br />
<br />
# umount ''mountpoint''<br />
# qemu-nbd -d /dev/nbd0<br />
<br />
=== Using any real partition as the single primary partition of a hard disk image ===<br />
<br />
Sometimes, you may wish to use one of your system partitions from within QEMU. Using a raw partition for a virtual machine will improve performance, as the read and write operations do not go through the file system layer on the physical host. Such a partition also provides a way to share data between the host and guest.<br />
<br />
In Arch Linux, device files for raw partitions are, by default, owned by ''root'' and the ''disk'' group. If you would like to have a non-root user be able to read and write to a raw partition, you must either change the owner of the partition's device file to that user, add that user to the ''disk'' group, or use [[ACL]] for more fine-grained access control.<br />
<br />
{{Warning|<br />
* Although it is possible, it is not recommended to allow virtual machines to alter critical data on the host system, such as the root partition.<br />
* You must not mount a file system on a partition read-write on both the host and the guest at the same time. Otherwise, data corruption will result.<br />
}}<br />
<br />
After doing so, you can attach the partition to a QEMU virtual machine as a virtual disk.<br />
<br />
However, things are a little more complicated if you want to have the ''entire'' virtual machine contained in a partition. In that case, there would be no disk image file to actually boot the virtual machine since you cannot install a boot loader to a partition that is itself formatted as a file system and not as a partitioned device with an MBR. Such a virtual machine can be booted either by: [[#Specifying kernel and initrd manually]], [[#Simulating a virtual disk with MBR]], [[#Using the device-mapper]], [[#Using a linear RAID]] or [[#Using a Network Block Device]].<br />
<br />
==== Specifying kernel and initrd manually ====<br />
<br />
QEMU supports loading [[Kernels|Linux kernels]] and [[initramfs|init ramdisks]] directly, thereby circumventing boot loaders such as [[GRUB]]. It then can be launched with the physical partition containing the root file system as the virtual disk, which will not appear to be partitioned. This is done by issuing a command similar to the following:<br />
<br />
{{Note|In this example, it is the '''host's''' images that are being used, not the guest's. If you wish to use the guest's images, either mount {{ic|/dev/sda3}} read-only (to protect the file system from the host) and specify the {{ic|/full/path/to/images}} or use some kexec hackery in the guest to reload the guest's kernel (extends boot time). }}<br />
<br />
$ qemu-system-x86_64 -kernel /boot/vmlinuz-linux -initrd /boot/initramfs-linux.img -append root=/dev/sda /dev/sda3<br />
<br />
In the above example, the physical partition being used for the guest's root file system is {{ic|/dev/sda3}} on the host, but it shows up as {{ic|/dev/sda}} on the guest.<br />
<br />
You may, of course, specify any kernel and initrd that you want, and not just the ones that come with Arch Linux.<br />
<br />
When there are multiple [[kernel parameters]] to be passed to the {{ic|-append}} option, they need to be quoted using single or double quotes. For example:<br />
<br />
... -append 'root=/dev/sda1 console=ttyS0'<br />
<br />
==== Simulating a virtual disk with MBR ====<br />
<br />
A more complicated way to have a virtual machine use a physical partition, while keeping that partition formatted as a file system and not just having the guest partition the partition as if it were a disk, is to simulate an MBR for it so that it can boot using a boot loader such as GRUB.<br />
<br />
For the following, suppose you have a plain, unmounted {{ic|/dev/hda''N''}} partition with some file system on it you wish to make part of a QEMU disk image. The trick is to dynamically prepend a master boot record (MBR) to the real partition you wish to embed in a QEMU raw disk image. More generally, the partition can be any part of a larger simulated disk, in particular a block device that simulates the original physical disk but only exposes {{ic|/dev/hda''N''}} to the virtual machine.<br />
<br />
A virtual disk of this type can be represented by a VMDK file that contains references to (a copy of) the MBR and the partition, but QEMU does not support this VMDK format. For instance, a virtual disk [https://www.virtualbox.org/manual/ch09.html#rawdisk created by]<br />
<br />
$ VBoxManage internalcommands createrawvmdk -filename ''/path/to/file.vmdk'' -rawdisk /dev/hda<br />
<br />
will be rejected by QEMU with the error message<br />
<br />
Unsupported image type 'partitionedDevice'<br />
<br />
Note that {{ic|VBoxManage}} creates two files, {{ic|''file.vmdk''}} and {{ic|''file-pt.vmdk''}}, the latter being a copy of the MBR, to which the text file {{ic|file.vmdk}} points. Read operations outside the target partition or the MBR would give zeros, while written data would be discarded.<br />
<br />
===== Using the device-mapper =====<br />
<br />
A method that is similar to the use of a VMDK descriptor file uses the [https://docs.kernel.org/admin-guide/device-mapper/index.html device-mapper] to prepend a loop device attached to the MBR file to the target partition. In case we do not need our virtual disk to have the same size as the original, we first create a file to hold the MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=2048<br />
<br />
Here, a 1 MiB (2048 * 512 bytes) file is created in accordance with partition alignment policies used by modern disk partitioning tools. For compatibility with older partitioning software, 63 sectors instead of 2048 might be required. The MBR only needs a single 512 bytes block, the additional free space can be used for a BIOS boot partition and, in the case of a hybrid partitioning scheme, for a GUID Partition Table. Then, we attach a loop device to the MBR file:<br />
<br />
{{hc|# losetup --show -f ''/path/to/mbr''|/dev/loop0}}<br />
<br />
In this example, the resulting device is {{ic|/dev/loop0}}. The device mapper is now used to join the MBR and the partition:<br />
<br />
# echo "0 2048 linear /dev/loop0 0<br />
2048 `blockdev --getsz /dev/hda''N''` linear /dev/hda''N'' 0" | dmsetup create qemu<br />
<br />
The resulting {{ic|/dev/mapper/qemu}} is what we will use as a QEMU raw disk image. Additional steps are required to create a partition table (see the section that describes the use of a linear RAID for an example) and boot loader code on the virtual disk (which will be stored in {{ic|''/path/to/mbr''}}).<br />
<br />
The following setup is an example where the position of {{ic|/dev/hda''N''}} on the virtual disk is to be the same as on the physical disk and the rest of the disk is hidden, except for the MBR, which is provided as a copy:<br />
<br />
# dd if=/dev/hda count=1 of=''/path/to/mbr''<br />
# loop=`losetup --show -f ''/path/to/mbr''`<br />
# start=`blockdev --report /dev/hda''N'' | tail -1 | awk '{print $5}'`<br />
# size=`blockdev --getsz /dev/hda''N''`<br />
# disksize=`blockdev --getsz /dev/hda`<br />
# echo "0 1 linear $loop 0<br />
1 $((start-1)) zero<br />
$start $size linear /dev/hda''N'' 0<br />
$((start+size)) $((disksize-start-size)) zero" | dmsetup create qemu<br />
<br />
The table provided as standard input to {{ic|dmsetup}} has a similar format as the table in a VDMK descriptor file produced by {{ic|VBoxManage}} and can alternatively be loaded from a file with {{ic|dmsetup create qemu --table ''table_file''}}. To the virtual machine, only {{ic|/dev/hda''N''}} is accessible, while the rest of the hard disk reads as zeros and discards written data, except for the first sector. We can print the table for {{ic|/dev/mapper/qemu}} with {{ic|dmsetup table qemu}} (use {{ic|udevadm info -rq name /sys/dev/block/''major'':''minor''}} to translate {{ic|''major'':''minor''}} to the corresponding {{ic|/dev/''blockdevice''}} name). Use {{ic|dmsetup remove qemu}} and {{ic|losetup -d $loop}} to delete the created devices.<br />
<br />
A situation where this example would be useful is an existing Windows XP installation in a multi-boot configuration and maybe a hybrid partitioning scheme (on the physical hardware, Windows XP could be the only operating system that uses the MBR partition table, while more modern operating systems installed on the same computer could use the GUID Partition Table). Windows XP supports hardware profiles, so that that the same installation can be used with different hardware configurations alternatingly (in this case bare metal vs. virtual) with Windows needing to install drivers for newly detected hardware only once for every profile. Note that in this example the boot loader code in the copied MBR needs to be updated to directly load Windows XP from {{ic|/dev/hda''N''}} instead of trying to start the multi-boot capable boot loader (like GRUB) present in the original system. Alternatively, a copy of the boot partition containing the boot loader installation can be included in the virtual disk the same way as the MBR.<br />
<br />
===== Using a linear RAID =====<br />
<br />
{{Out of date|[[Wikipedia:Cylinder-head-sector|CHS]] has been obsolete for decades.}}<br />
<br />
You can also do this using software [[RAID]] in linear mode (you need the {{ic|linear.ko}} kernel driver) and a loopback device: <br />
<br />
First, you create some small file to hold the MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=32<br />
<br />
Here, a 16 KiB (32 * 512 bytes) file is created. It is important not to make it too small (even if the MBR only needs a single 512 bytes block), since the smaller it will be, the smaller the chunk size of the software RAID device will have to be, which could have an impact on performance. Then, you setup a loopback device to the MBR file:<br />
<br />
# losetup -f ''/path/to/mbr''<br />
<br />
Let us assume the resulting device is {{ic|/dev/loop0}}, because we would not already have been using other loopbacks. Next step is to create the "merged" MBR + {{ic|/dev/hda''N''}} disk image using software RAID:<br />
<br />
# modprobe linear<br />
# mdadm --build --verbose /dev/md0 --chunk=16 --level=linear --raid-devices=2 /dev/loop0 /dev/hda''N''<br />
<br />
The resulting {{ic|/dev/md0}} is what you will use as a QEMU raw disk image (do not forget to set the permissions so that the emulator can access it). The last (and somewhat tricky) step is to set the disk configuration (disk geometry and partitions table) so that the primary partition start point in the MBR matches the one of {{ic|/dev/hda''N''}} inside {{ic|/dev/md0}} (an offset of exactly 16 * 512 = 16384 bytes in this example). Do this using {{ic|fdisk}} on the host machine, not in the emulator: the default raw disc detection routine from QEMU often results in non-kibibyte-roundable offsets (such as 31.5 KiB, as in the previous section) that cannot be managed by the software RAID code. Hence, from the host:<br />
<br />
# fdisk /dev/md0<br />
<br />
Press {{ic|X}} to enter the expert menu. Set number of 's'ectors per track so that the size of one cylinder matches the size of your MBR file. For two heads and a sector size of 512, the number of sectors per track should be 16, so we get cylinders of size 2x16x512=16k.<br />
<br />
Now, press {{ic|R}} to return to the main menu.<br />
<br />
Press {{ic|P}} and check that the cylinder size is now 16k.<br />
<br />
Now, create a single primary partition corresponding to {{ic|/dev/hda''N''}}. It should start at cylinder 2 and end at the end of the disk (note that the number of cylinders now differs from what it was when you entered fdisk.<br />
<br />
Finally, 'w'rite the result to the file: you are done. You now have a partition you can mount directly from your host, as well as part of a QEMU disk image:<br />
<br />
$ qemu-system-x86_64 -hdc /dev/md0 ''[...]''<br />
<br />
You can, of course, safely set any boot loader on this disk image using QEMU, provided the original {{ic|/dev/hda''N''}} partition contains the necessary tools.<br />
<br />
===== Using a Network Block Device =====<br />
<br />
With [https://docs.kernel.org/admin-guide/blockdev/nbd.html Network Block Device], Linux can use a remote server as one of its block device. You may use {{ic|nbd-server}} (from the {{Pkg|nbd}} package) to create an MBR wrapper for QEMU.<br />
<br />
Assuming you have already set up your MBR wrapper file like above, rename it to {{ic|wrapper.img.0}}. Then create a symbolic link named {{ic|wrapper.img.1}} in the same directory, pointing to your partition. Then put the following script in the same directory:<br />
<br />
{{bc|1=<br />
#!/bin/sh<br />
dir="$(realpath "$(dirname "$0")")"<br />
cat >wrapper.conf <<EOF<br />
[generic]<br />
allowlist = true<br />
listenaddr = 127.713705<br />
port = 10809<br />
<br />
[wrap]<br />
exportname = $dir/wrapper.img<br />
multifile = true<br />
EOF<br />
<br />
nbd-server \<br />
-C wrapper.conf \<br />
-p wrapper.pid \<br />
"$@"<br />
}}<br />
<br />
The {{ic|.0}} and {{ic|.1}} suffixes are essential; the rest can be changed. After running the above script (which you may need to do as root to make sure nbd-server is able to access the partition), you can launch QEMU with:<br />
<br />
qemu-system-x86_64 -drive file=nbd:127.713705:10809:exportname=wrap ''[...]''<br />
<br />
=== Using an entire physical disk device inside the virtual machine ===<br />
<br />
{{Style|Duplicates [[#Using any real partition as the single primary partition of a hard disk image]], libvirt instructions do not belong to this page.}}<br />
<br />
You may have a second disk with a different OS (like Windows) on it and may want to gain the ability to also boot it inside a virtual machine.<br />
Since the disk access is raw, the disk will perform quite well inside the virtual machine.<br />
<br />
==== Windows virtual machine boot prerequisites ====<br />
<br />
Be sure to install the [https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/archive-virtio/ virtio drivers] inside the OS on that disk before trying to boot it in the virtual machine.<br />
For Win 7 use version [https://askubuntu.com/questions/1310440/using-virtio-win-drivers-with-win7-sp1-x64 0.1.173-4].<br />
Some singular drivers from newer virtio builds may be used on Win 7 but you will have to install them manually via device manager.<br />
For Win 10 you can use the latest virtio build.<br />
<br />
===== Set up the windows disk interface drivers =====<br />
<br />
You may get a {{ic|0x0000007B}} bluescreen when trying to boot the virtual machine. This means Windows can not access the drive during the early boot stage because the disk interface driver it would need for that is not loaded / is set to start manually.<br />
<br />
The solution is to [https://superuser.com/a/1032769 enable these drivers to start at boot].<br />
<br />
In {{ic|HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services}}, find the folders {{ic|aliide, amdide, atapi, cmdide, iastor (may not exist), iastorV, intelide, LSI_SAS, msahci, pciide and viaide}}.<br />
Inside each of those, set all their "start" values to 0 in order to enable them at boot.<br />
If your drive is a PCIe NVMe drive, also enable that driver (should it exist).<br />
<br />
==== Find the unique path of your disk ====<br />
<br />
Run {{ic|ls /dev/disk/by-id/}}: tere you pick out the ID of the drive you want to insert into the virtual machine, for example {{ic|ata-TS512GMTS930L_C199211383}}.<br />
Now add that ID to {{ic|/dev/disk/by-id/}} so you get {{ic|/dev/disk/by-id/ata-TS512GMTS930L_C199211383}}.<br />
That is the unique path to that disk.<br />
<br />
==== Add the disk in QEMU CLI ====<br />
<br />
In QEMU CLI that would probably be:<br />
<br />
{{ic|1=-drive file=/dev/disk/by-id/ata-TS512GMTS930L_C199211383,format=raw,media=disk}}<br />
<br />
Just modify {{ic|file{{=}}}} to be the unique path of your drive.<br />
<br />
==== Add the disk in libvirt ====<br />
<br />
In libvirt XML that translates to<br />
<br />
{{hc|$ virsh edit ''vmname''|<nowiki><br />
...<br />
<disk type="block" device="disk"><br />
<driver name="qemu" type="raw" cache="none" io="native"/><br />
<source dev="/dev/disk/by-id/ata-TS512GMTS930L_C199211383"/><br />
<target dev="sda" bus="sata"/><br />
<address type="drive" controller="0" bus="0" target="0" unit="0"/><br />
</disk><br />
...<br />
</nowiki>}}<br />
<br />
Just modify "source dev" to be the unique path of your drive.<br />
<br />
==== Add the disk in virt-manager ====<br />
<br />
When creating a virtual machine, select "import existing drive" and just paste that unique path.<br />
If you already have the virtual machine, add a device, storage, then select or create custom storage.<br />
Now paste the unique path.<br />
<br />
== Networking ==<br />
<br />
{{Style|Network topologies (sections [[#Host-only networking]], [[#Internal networking]] and info spread out across other sections) should not be described alongside the various virtual interfaces implementations, such as [[#User-mode networking]], [[#Tap networking with QEMU]], [[#Networking with VDE2]].}}<br />
<br />
The performance of virtual networking should be better with tap devices and bridges than with user-mode networking or vde because tap devices and bridges are implemented in-kernel.<br />
<br />
In addition, networking performance can be improved by assigning virtual machines a [https://wiki.libvirt.org/page/Virtio virtio] network device rather than the default emulation of an e1000 NIC. See [[#Installing virtio drivers]] for more information.<br />
<br />
=== Link-level address caveat ===<br />
<br />
By giving the {{ic|-net nic}} argument to QEMU, it will, by default, assign a virtual machine a network interface with the link-level address {{ic|52:54:00:12:34:56}}. However, when using bridged networking with multiple virtual machines, it is essential that each virtual machine has a unique link-level (MAC) address on the virtual machine side of the tap device. Otherwise, the bridge will not work correctly, because it will receive packets from multiple sources that have the same link-level address. This problem occurs even if the tap devices themselves have unique link-level addresses because the source link-level address is not rewritten as packets pass through the tap device.<br />
<br />
Make sure that each virtual machine has a unique link-level address, but it should always start with {{ic|52:54:}}. Use the following option, replace ''X'' with arbitrary hexadecimal digit:<br />
<br />
$ qemu-system-x86_64 -net nic,macaddr=52:54:''XX:XX:XX:XX'' -net vde ''disk_image''<br />
<br />
Generating unique link-level addresses can be done in several ways:<br />
<br />
* Manually specify unique link-level address for each NIC. The benefit is that the DHCP server will assign the same IP address each time the virtual machine is run, but it is unusable for large number of virtual machines.<br />
* Generate random link-level address each time the virtual machine is run. Practically zero probability of collisions, but the downside is that the DHCP server will assign a different IP address each time. You can use the following command in a script to generate random link-level address in a {{ic|macaddr}} variable:<br />
<br />
{{bc|1=<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
qemu-system-x86_64 -net nic,macaddr="$macaddr" -net vde ''disk_image''<br />
}}<br />
<br />
* Use the following script {{ic|qemu-mac-hasher.py}} to generate the link-level address from the virtual machine name using a hashing function. Given that the names of virtual machines are unique, this method combines the benefits of the aforementioned methods: it generates the same link-level address each time the script is run, yet it preserves the practically zero probability of collisions.<br />
<br />
{{hc|qemu-mac-hasher.py|2=<br />
#!/usr/bin/env python<br />
# usage: qemu-mac-hasher.py <VMName><br />
<br />
import sys<br />
import zlib<br />
<br />
crc = str(hex(zlib.crc32(sys.argv[1].encode("utf-8")))).replace("x", "")[-8:]<br />
print("52:54:%s%s:%s%s:%s%s:%s%s" % tuple(crc))<br />
}}<br />
<br />
In a script, you can use for example:<br />
<br />
vm_name="''VM Name''"<br />
qemu-system-x86_64 -name "$vm_name" -net nic,macaddr=$(qemu-mac-hasher.py "$vm_name") -net vde ''disk_image''<br />
<br />
=== User-mode networking ===<br />
<br />
By default, without any {{ic|-netdev}} arguments, QEMU will use user-mode networking with a built-in DHCP server. Your virtual machines will be assigned an IP address when they run their DHCP client, and they will be able to access the physical host's network through IP masquerading done by QEMU.<br />
<br />
{{Note|ICMPv6 will not work, as support for it is not implemented: {{ic|Slirp: external icmpv6 not supported yet}}. [[Ping]]ing an IPv6 address will not work.}}<br />
<br />
This default configuration allows your virtual machines to easily access the Internet, provided that the host is connected to it, but the virtual machines will not be directly visible on the external network, nor will virtual machines be able to talk to each other if you start up more than one concurrently.<br />
<br />
QEMU's user-mode networking can offer more capabilities such as built-in TFTP or SMB servers, redirecting host ports to the guest (for example to allow SSH connections to the guest) or attaching guests to VLANs so that they can talk to each other. See the QEMU documentation on the {{ic|-net user}} flag for more details.<br />
<br />
However, user-mode networking has limitations in both utility and performance. More advanced network configurations require the use of tap devices or other methods.<br />
<br />
{{Note|If the host system uses [[systemd-networkd]], make sure to symlink the {{ic|/etc/resolv.conf}} file as described in [[systemd-networkd#Required services and setup]], otherwise the DNS lookup in the guest system will not work.}}<br />
<br />
{{Tip|<br />
* To use the virtio driver with user-mode networking, the option is: {{ic|1=-nic user,model=virtio-net-pci}}.<br />
* You can isolate user-mode networking from the host and the outside world by adding {{ic|1=restrict=y}}, for example: {{ic|1=-net user,restrict=y}}<br />
}}<br />
<br />
=== Tap networking with QEMU ===<br />
<br />
[[wikipedia:TUN/TAP|Tap devices]] are a Linux kernel feature that allows you to create virtual network interfaces that appear as real network interfaces. Packets sent to a tap interface are delivered to a userspace program, such as QEMU, that has bound itself to the interface.<br />
<br />
QEMU can use tap networking for a virtual machine so that packets sent to the tap interface will be sent to the virtual machine and appear as coming from a network interface (usually an Ethernet interface) in the virtual machine. Conversely, everything that the virtual machine sends through its network interface will appear on the tap interface.<br />
<br />
Tap devices are supported by the Linux bridge drivers, so it is possible to bridge together tap devices with each other and possibly with other host interfaces such as {{ic|eth0}}. This is desirable if you want your virtual machines to be able to talk to each other, or if you want other machines on your LAN to be able to talk to the virtual machines.<br />
<br />
{{Warning|If you bridge together tap device and some host interface, such as {{ic|eth0}}, your virtual machines will appear directly on the external network, which will expose them to possible attack. Depending on what resources your virtual machines have access to, you may need to take all the [[Firewalls|precautions]] you normally would take in securing a computer to secure your virtual machines. If the risk is too great, virtual machines have little resources or you set up multiple virtual machines, a better solution might be to use [[#Host-only networking|host-only networking]] and set up NAT. In this case you only need one firewall on the host instead of multiple firewalls for each guest.}}<br />
<br />
As indicated in the user-mode networking section, tap devices offer higher networking performance than user-mode. If the guest OS supports virtio network driver, then the networking performance will be increased considerably as well. Supposing the use of the tap0 device, that the virtio driver is used on the guest, and that no scripts are used to help start/stop networking, next is part of the qemu command one should see:<br />
<br />
-device virtio-net,netdev=network0 -netdev tap,id=network0,ifname=tap0,script=no,downscript=no<br />
<br />
But if already using a tap device with virtio networking driver, one can even boost the networking performance by enabling vhost, like:<br />
<br />
-device virtio-net,netdev=network0 -netdev tap,id=network0,ifname=tap0,script=no,downscript=no,vhost=on<br />
<br />
See [https://web.archive.org/web/20160222161955/http://www.linux-kvm.com:80/content/how-maximize-virtio-net-performance-vhost-net] for more information.<br />
<br />
==== Host-only networking ====<br />
<br />
If the bridge is given an IP address and traffic destined for it is allowed, but no real interface (e.g. {{ic|eth0}}) is connected to the bridge, then the virtual machines will be able to talk to each other and the host system. However, they will not be able to talk to anything on the external network, provided that you do not set up IP masquerading on the physical host. This configuration is called ''host-only networking'' by other virtualization software such as [[VirtualBox]].<br />
<br />
{{Tip|<br />
* If you want to set up IP masquerading, e.g. NAT for virtual machines, see the [[Internet sharing#Enable NAT]] page.<br />
* See [[Network bridge]] for information on creating bridge.<br />
* You may want to have a DHCP server running on the bridge interface to service the virtual network. For example, to use the {{ic|172.20.0.1/16}} subnet with [[dnsmasq]] as the DHCP server:<br />
<br />
{{bc|1=<br />
# ip addr add 172.20.0.1/16 dev br0<br />
# ip link set br0 up<br />
# dnsmasq --interface=br0 --bind-interfaces --dhcp-range=172.20.0.2,172.20.255.254<br />
}}<br />
}}<br />
<br />
==== Internal networking ====<br />
<br />
If you do not give the bridge an IP address and add an [[iptables]] rule to drop all traffic to the bridge in the INPUT chain, then the virtual machines will be able to talk to each other, but not to the physical host or to the outside network. This configuration is called ''internal networking'' by other virtualization software such as [[VirtualBox]]. You will need to either assign static IP addresses to the virtual machines or run a DHCP server on one of them.<br />
<br />
By default iptables would drop packets in the bridge network. You may need to use such iptables rule to allow packets in a bridged network:<br />
<br />
# iptables -I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Bridged networking using qemu-bridge-helper ====<br />
<br />
This method does not require a start-up script and readily accommodates multiple taps and multiple bridges. It uses {{ic|/usr/lib/qemu/qemu-bridge-helper}} binary, which allows creating tap devices on an existing bridge.<br />
<br />
{{Tip|<br />
* See [[Network bridge]] for information on creating bridge.<br />
* See https://wiki.qemu.org/Features/HelperNetworking for more information on QEMU's network helper.<br />
}}<br />
<br />
First, create a configuration file containing the names of all bridges to be used by QEMU:<br />
<br />
{{hc|/etc/qemu/bridge.conf|<br />
allow ''br0''<br />
allow ''br1''<br />
...}}<br />
<br />
Make sure {{ic|/etc/qemu/}} has {{ic|755}} [[permissions]]. [https://gitlab.com/qemu-project/qemu/-/issues/515 QEMU issues] and [https://www.gns3.com/community/discussions/gns3-cannot-work-with-qemu GNS3 issues] may arise if this is not the case.<br />
<br />
Now start the virtual machine; the most basic usage to run QEMU with the default network helper and default bridge {{ic|br0}}:<br />
<br />
$ qemu-system-x86_64 -nic bridge ''[...]''<br />
<br />
Using the bridge {{ic|br1}} and the virtio driver:<br />
<br />
$ qemu-system-x86_64 -nic bridge,br=''br1'',model=virtio-net-pci ''[...]''<br />
<br />
==== Creating bridge manually ====<br />
<br />
{{Style|This section needs serious cleanup and may contain out-of-date information.}}<br />
<br />
{{Tip|Since QEMU 1.1, the [https://wiki.qemu.org/Features/HelperNetworking network bridge helper] can set tun/tap up for you without the need for additional scripting. See [[#Bridged networking using qemu-bridge-helper]].}}<br />
<br />
The following describes how to bridge a virtual machine to a host interface such as {{ic|eth0}}, which is probably the most common configuration. This configuration makes it appear that the virtual machine is located directly on the external network, on the same Ethernet segment as the physical host machine.<br />
<br />
We will replace the normal Ethernet adapter with a bridge adapter and bind the normal Ethernet adapter to it.<br />
<br />
* Install {{Pkg|bridge-utils}}, which provides {{ic|brctl}} to manipulate bridges.<br />
<br />
* Enable IPv4 forwarding:<br />
<br />
# sysctl -w net.ipv4.ip_forward=1<br />
<br />
To make the change permanent, change {{ic|1=net.ipv4.ip_forward = 0}} to {{ic|1=net.ipv4.ip_forward = 1}} in {{ic|/etc/sysctl.d/99-sysctl.conf}}.<br />
<br />
* Load the {{ic|tun}} module and configure it to be loaded on boot. See [[Kernel modules]] for details.<br />
<br />
* Optionally create the bridge. See [[Bridge with netctl]] for details. Remember to name your bridge as {{ic|br0}}, or change the scripts below to your bridge's name. In the {{ic|run-qemu}} script below, {{ic|br0}} is set up if not listed, as it is assumed that by default the host is not accessing network via the bridge.<br />
<br />
* Create the script that QEMU uses to bring up the tap adapter with {{ic|root:kvm}} 750 permissions:<br />
<br />
{{hc|/etc/qemu-ifup|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifup"<br />
echo "Bringing up $1 for bridged mode..."<br />
sudo /usr/bin/ip link set $1 up promisc on<br />
echo "Adding $1 to br0..."<br />
sudo /usr/bin/brctl addif br0 $1<br />
sleep 2<br />
</nowiki>}}<br />
<br />
* Create the script that QEMU uses to bring down the tap adapter in {{ic|/etc/qemu-ifdown}} with {{ic|root:kvm}} 750 permissions:<br />
{{hc|/etc/qemu-ifdown|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifdown"<br />
sudo /usr/bin/ip link set $1 down<br />
sudo /usr/bin/brctl delif br0 $1<br />
sudo /usr/bin/ip link delete dev $1<br />
</nowiki>}}<br />
<br />
* Use {{ic|visudo}} to add the following to your {{ic|sudoers}} file:<br />
<br />
{{bc|<nowiki><br />
Cmnd_Alias QEMU=/usr/bin/ip,/usr/bin/modprobe,/usr/bin/brctl<br />
%kvm ALL=NOPASSWD: QEMU<br />
</nowiki>}}<br />
<br />
* You launch QEMU using the following {{ic|run-qemu}} script:<br />
<br />
{{hc|run-qemu|<nowiki><br />
#!/bin/bash<br />
: '<br />
e.g. with img created via:<br />
qemu-img create -f qcow2 example.img 90G<br />
run-qemu -cdrom archlinux-x86_64.iso -boot order=d -drive file=example.img,format=qcow2 -m 4G -enable-kvm -cpu host -smp 4<br />
run-qemu -drive file=example.img,format=qcow2 -m 4G -enable-kvm -cpu host -smp 4<br />
'<br />
<br />
nicbr0() {<br />
sudo ip link set dev $1 promisc on up &> /dev/null<br />
sudo ip addr flush dev $1 scope host &>/dev/null<br />
sudo ip addr flush dev $1 scope site &>/dev/null<br />
sudo ip addr flush dev $1 scope global &>/dev/null<br />
sudo ip link set dev $1 master br0 &> /dev/null<br />
}<br />
_nicbr0() {<br />
sudo ip link set $1 promisc off down &> /dev/null<br />
sudo ip link set dev $1 nomaster &> /dev/null<br />
}<br />
<br />
HASBR0="$( ip link show | grep br0 )"<br />
if [ -z $HASBR0 ] ; then<br />
ROUTER="192.168.1.1"<br />
SUBNET="192.168.1."<br />
NIC=$(ip link show | grep en | grep 'state UP' | head -n 1 | cut -d":" -f 2 | xargs)<br />
IPADDR=$(ip addr show | grep -o "inet $SUBNET\([0-9]*\)" | cut -d ' ' -f2)<br />
sudo ip link add name br0 type bridge &> /dev/null<br />
sudo ip link set dev br0 up<br />
sudo ip addr add $IPADDR/24 brd + dev br0<br />
sudo ip route del default &> /dev/null<br />
sudo ip route add default via $ROUTER dev br0 onlink<br />
nicbr0 $NIC<br />
sudo iptables -I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
fi<br />
<br />
USERID=$(whoami)<br />
precreationg=$(ip tuntap list | cut -d: -f1 | sort)<br />
sudo ip tuntap add user $USERID mode tap<br />
postcreation=$(ip tuntap list | cut -d: -f1 | sort)<br />
TAP=$(comm -13 <(echo "$precreationg") <(echo "$postcreation"))<br />
nicbr0 $TAP<br />
<br />
printf -v MACADDR "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
qemu-system-x86_64 -net nic,macaddr=$MACADDR,model=virtio \<br />
-net tap,ifname=$TAP,script=no,downscript=no,vhost=on \<br />
$@<br />
<br />
_nicbr0 $TAP<br />
sudo ip link set dev $TAP down &> /dev/null<br />
sudo ip tuntap del $TAP mode tap<br />
<br />
if [ -z $HASBR0 ] ; then<br />
_nicbr0 $NIC<br />
sudo ip addr del dev br0 $IPADDR/24 &> /dev/null<br />
sudo ip link set dev br0 down<br />
sudo ip link delete br0 type bridge &> /dev/null<br />
sudo ip route del default &> /dev/null<br />
sudo ip link set dev $NIC up<br />
sudo ip route add default via $ROUTER dev $NIC onlink &> /dev/null<br />
fi<br />
</nowiki>}}<br />
<br />
Then to launch a virtual machine, do something like this<br />
<br />
$ run-qemu -hda ''myvm.img'' -m 512<br />
<br />
* It is recommended for performance and security reasons to disable the [http://ebtables.netfilter.org/documentation/bridge-nf.html firewall on the bridge]:<br />
<br />
{{hc|/etc/sysctl.d/10-disable-firewall-on-bridge.conf|<nowiki><br />
net.bridge.bridge-nf-call-ip6tables = 0<br />
net.bridge.bridge-nf-call-iptables = 0<br />
net.bridge.bridge-nf-call-arptables = 0<br />
</nowiki>}}<br />
<br />
In order to apply the parameters described above on boot, you will also need to load the br-netfilter module on boot. Otherwise, the parameters will not exist when sysctl will try to modify them.<br />
<br />
{{hc|/etc/modules-load.d/br_netfilter.conf|<nowiki><br />
br_netfilter<br />
</nowiki>}}<br />
<br />
Run {{ic|sysctl -p /etc/sysctl.d/10-disable-firewall-on-bridge.conf}} to apply the changes immediately.<br />
<br />
See the [https://wiki.libvirt.org/page/Networking#Creating_network_initscripts libvirt wiki] and [https://bugzilla.redhat.com/show_bug.cgi?id=512206 Fedora bug 512206]. If you get errors by sysctl during boot about non-existing files, make the {{ic|bridge}} module load at boot. See [[Kernel module#systemd]].<br />
<br />
Alternatively, you can configure [[iptables]] to allow all traffic to be forwarded across the bridge by adding a rule like this:<br />
<br />
-I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Network sharing between physical device and a Tap device through iptables ====<br />
<br />
{{Merge|Internet_sharing|Duplication, not specific to QEMU.}}<br />
<br />
Bridged networking works fine between a wired interface (Eg. eth0), and it is easy to setup. However if the host gets connected to the network through a wireless device, then bridging is not possible.<br />
<br />
See [[Network bridge#Wireless interface on a bridge]] as a reference.<br />
<br />
One way to overcome that is to setup a tap device with a static IP, making linux automatically handle the routing for it, and then forward traffic between the tap interface and the device connected to the network through iptables rules.<br />
<br />
See [[Internet sharing]] as a reference.<br />
<br />
There you can find what is needed to share the network between devices, included tap and tun ones. The following just hints further on some of the host configurations required. As indicated in the reference above, the client needs to be configured for a static IP, using the IP assigned to the tap interface as the gateway. The caveat is that the DNS servers on the client might need to be manually edited if they change when changing from one host device connected to the network to another.<br />
<br />
To allow IP forwarding on every boot, one need to add the following lines to sysctl configuration file inside {{ic|/etc/sysctl.d}}:<br />
<br />
net.ipv4.ip_forward = 1<br />
net.ipv6.conf.default.forwarding = 1<br />
net.ipv6.conf.all.forwarding = 1<br />
<br />
The iptables rules can look like:<br />
<br />
# Forwarding from/to outside<br />
iptables -A FORWARD -i ${INT} -o ${EXT_0} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_1} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_2} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_0} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_1} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_2} -o ${INT} -j ACCEPT<br />
# NAT/Masquerade (network address translation)<br />
iptables -t nat -A POSTROUTING -o ${EXT_0} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_1} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_2} -j MASQUERADE<br />
<br />
The prior supposes there are 3 devices connected to the network sharing traffic with one internal device, where for example:<br />
<br />
INT=tap0<br />
EXT_0=eth0<br />
EXT_1=wlan0<br />
EXT_2=tun0<br />
<br />
The prior shows a forwarding that would allow sharing wired and wireless connections with the tap device.<br />
<br />
The forwarding rules shown are stateless, and for pure forwarding. One could think of restricting specific traffic, putting a firewall in place to protect the guest and others. However those would decrease the networking performance, while a simple bridge does not include any of that.<br />
<br />
Bonus: Whether the connection is wired or wireless, if one gets connected through VPN to a remote site with a tun device, supposing the tun device opened for that connection is tun0, and the prior iptables rules are applied, then the remote connection gets also shared with the guest. This avoids the need for the guest to also open a VPN connection. Again, as the guest networking needs to be static, then if connecting the host remotely this way, one most probably will need to edit the DNS servers on the guest.<br />
<br />
=== Networking with VDE2 ===<br />
<br />
{{Style|This section needs serious cleanup and may contain out-of-date information.}}<br />
<br />
==== What is VDE? ====<br />
<br />
VDE stands for Virtual Distributed Ethernet. It started as an enhancement of [[User-mode Linux|uml]]_switch. It is a toolbox to manage virtual networks.<br />
<br />
The idea is to create virtual switches, which are basically sockets, and to "plug" both physical and virtual machines in them. The configuration we show here is quite simple; However, VDE is much more powerful than this, it can plug virtual switches together, run them on different hosts and monitor the traffic in the switches. You are invited to read [https://wiki.virtualsquare.org/ the documentation of the project].<br />
<br />
The advantage of this method is you do not have to add sudo privileges to your users. Regular users should not be allowed to run modprobe.<br />
<br />
==== Basics ====<br />
<br />
VDE support can be [[install]]ed via the {{Pkg|vde2}} package.<br />
<br />
In our config, we use tun/tap to create a virtual interface on my host. Load the {{ic|tun}} module (see [[Kernel modules]] for details):<br />
<br />
# modprobe tun<br />
<br />
Now create the virtual switch:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
<br />
This line creates the switch, creates {{ic|tap0}}, "plugs" it, and allows the users of the group {{ic|users}} to use it.<br />
<br />
The interface is plugged in but not configured yet. To configure it, run this command:<br />
<br />
# ip addr add 192.168.100.254/24 dev tap0<br />
<br />
Now, you just have to run KVM with these {{ic|-net}} options as a normal user:<br />
<br />
$ qemu-system-x86_64 -net nic -net vde -hda ''[...]''<br />
<br />
Configure networking for your guest as you would do in a physical network.<br />
<br />
{{Tip|You might want to set up NAT on tap device to access the internet from the virtual machine. See [[Internet sharing#Enable NAT]] for more information.}}<br />
<br />
==== Startup scripts ====<br />
<br />
Example of main script starting VDE:<br />
<br />
{{hc|/etc/systemd/scripts/qemu-network-env|<nowiki><br />
#!/bin/sh<br />
# QEMU/VDE network environment preparation script<br />
<br />
# The IP configuration for the tap device that will be used for<br />
# the virtual machine network:<br />
<br />
TAP_DEV=tap0<br />
TAP_IP=192.168.100.254<br />
TAP_MASK=24<br />
TAP_NETWORK=192.168.100.0<br />
<br />
# Host interface<br />
NIC=eth0<br />
<br />
case "$1" in<br />
start)<br />
echo -n "Starting VDE network for QEMU: "<br />
<br />
# If you want tun kernel module to be loaded by script uncomment here<br />
#modprobe tun 2>/dev/null<br />
## Wait for the module to be loaded<br />
#while ! lsmod | grep -q "^tun"; do echo "Waiting for tun device"; sleep 1; done<br />
<br />
# Start tap switch<br />
vde_switch -tap "$TAP_DEV" -daemon -mod 660 -group users<br />
<br />
# Bring tap interface up<br />
ip address add "$TAP_IP"/"$TAP_MASK" dev "$TAP_DEV"<br />
ip link set "$TAP_DEV" up<br />
<br />
# Start IP Forwarding<br />
echo "1" > /proc/sys/net/ipv4/ip_forward<br />
iptables -t nat -A POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
;;<br />
stop)<br />
echo -n "Stopping VDE network for QEMU: "<br />
# Delete the NAT rules<br />
iptables -t nat -D POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
<br />
# Bring tap interface down<br />
ip link set "$TAP_DEV" down<br />
<br />
# Kill VDE switch<br />
pgrep vde_switch | xargs kill -TERM<br />
;;<br />
restart|reload)<br />
$0 stop<br />
sleep 1<br />
$0 start<br />
;;<br />
*)<br />
echo "Usage: $0 {start|stop|restart|reload}"<br />
exit 1<br />
esac<br />
exit 0<br />
</nowiki>}}<br />
<br />
Example of systemd service using the above script:<br />
<br />
{{hc|/etc/systemd/system/qemu-network-env.service|<nowiki><br />
[Unit]<br />
Description=Manage VDE Switch<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/etc/systemd/scripts/qemu-network-env start<br />
ExecStop=/etc/systemd/scripts/qemu-network-env stop<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
Change permissions for {{ic|qemu-network-env}} to be [[executable]]. <br />
<br />
You can [[start]] {{ic|qemu-network-env.service}} as usual.<br />
<br />
==== Alternative method ====<br />
<br />
If the above method does not work or you do not want to mess with kernel configs, TUN, dnsmasq, and iptables you can do the following for the same result.<br />
<br />
# vde_switch -daemon -mod 660 -group users<br />
# slirpvde --dhcp --daemon<br />
<br />
Then, to start the virtual machine with a connection to the network of the host:<br />
<br />
$ qemu-system-x86_64 -net nic,macaddr=52:54:00:00:EE:03 -net vde ''disk_image''<br />
<br />
=== VDE2 Bridge ===<br />
<br />
Based on [https://selamatpagicikgu.wordpress.com/2011/06/08/quickhowto-qemu-networking-using-vde-tuntap-and-bridge/ quickhowto: qemu networking using vde, tun/tap, and bridge] graphic. Any virtual machine connected to vde is externally exposed. For example, each virtual machine can receive DHCP configuration directly from your ADSL router.<br />
<br />
==== Basics ====<br />
<br />
Remember that you need {{ic|tun}} module and {{Pkg|bridge-utils}} package.<br />
<br />
Create the vde2/tap device:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
# ip link set tap0 up<br />
<br />
Create bridge:<br />
<br />
# brctl addbr br0<br />
<br />
Add devices:<br />
<br />
# brctl addif br0 eth0<br />
# brctl addif br0 tap0<br />
<br />
And configure bridge interface:<br />
<br />
# dhcpcd br0<br />
<br />
==== Startup scripts ====<br />
<br />
All devices must be set up. And only the bridge needs an IP address. For physical devices on the bridge (e.g. {{ic|eth0}}), this can be done with [[netctl]] using a custom Ethernet profile with:<br />
<br />
{{hc|/etc/netctl/ethernet-noip|2=<br />
Description='A more versatile static Ethernet connection'<br />
Interface=eth0<br />
Connection=ethernet<br />
IP=no<br />
}}<br />
<br />
The following custom systemd service can be used to create and activate a VDE2 tap interface for users in the {{ic|users}} user group.<br />
<br />
{{hc|/etc/systemd/system/vde2@.service|2=<br />
[Unit]<br />
Description=Network Connectivity for %i<br />
Wants=network.target<br />
Before=network.target<br />
<br />
[Service]<br />
Type=oneshot<br />
RemainAfterExit=yes<br />
ExecStart=/usr/bin/vde_switch -tap %i -daemon -mod 660 -group users<br />
ExecStart=/usr/bin/ip link set dev %i up<br />
ExecStop=/usr/bin/ip addr flush dev %i<br />
ExecStop=/usr/bin/ip link set dev %i down<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
}}<br />
<br />
And finally, you can create the [[Bridge with netctl|bridge interface with netctl]].<br />
<br />
=== Shorthand configuration ===<br />
<br />
If you are using QEMU with various networking options a lot, you probably have created a lot of {{ic|-netdev}} and {{ic|-device}} argument pairs, which gets quite repetitive. You can instead use the {{ic|-nic}} argument to combine {{ic|-netdev}} and {{ic|-device}} together, so that, for example, these arguments:<br />
<br />
-netdev tap,id=network0,ifname=tap0,script=no,downscript=no,vhost=on -device virtio-net-pci,netdev=network0<br />
<br />
become:<br />
<br />
-nic tap,script=no,downscript=no,vhost=on,model=virtio-net-pci<br />
<br />
Notice the lack of network IDs, and that the device was created with {{ic|1=model=}}. The first half of the {{ic|-nic}} parameters are {{ic|-netdev}} parameters, whereas the second half (after {{ic|1=model=}}) are related with the device. The same parameters (for example, {{ic|1=smb=}}) are used. To completely disable the networking use {{ic|-nic none}}.<br />
<br />
See [https://qemu.weilnetz.de/doc/6.0/system/net.html QEMU networking documentation] for more information on parameters you can use.<br />
<br />
== Graphic card ==<br />
<br />
QEMU can emulate a standard graphic card text mode using {{ic|-display curses}} command line option. This allows to type text and see text output directly inside a text terminal. Alternatively, {{ic|-nographic}} serves a similar purpose.<br />
<br />
QEMU can emulate several types of VGA card. The card type is passed in the {{ic|-vga ''type''}} command line option and can be {{ic|std}}, {{ic|qxl}}, {{ic|vmware}}, {{ic|virtio}}, {{ic|cirrus}} or {{ic|none}}.<br />
<br />
=== std ===<br />
<br />
With {{ic|-vga std}} you can get a resolution of up to 2560 x 1600 pixels without requiring guest drivers. This is the default since QEMU 2.2.<br />
<br />
=== qxl ===<br />
<br />
QXL is a paravirtual graphics driver with 2D support. To use it, pass the {{ic|-vga qxl}} option and install drivers in the guest. You may want to use [[#SPICE]] for improved graphical performance when using QXL.<br />
<br />
On Linux guests, the {{ic|qxl}} and {{ic|bochs_drm}} kernel modules must be loaded in order to gain a decent performance.<br />
<br />
Default VGA memory size for QXL devices is 16M which is sufficient to drive resolutions approximately up to QHD (2560x1440). To enable higher resolutions, [[#Multi-monitor support|increase vga_memmb]].<br />
<br />
=== vmware ===<br />
<br />
Although it is a bit buggy, it performs better than std and cirrus. Install the VMware drivers {{Pkg|xf86-video-vmware}} and {{Pkg|xf86-input-vmmouse}} for Arch Linux guests.<br />
<br />
=== virtio ===<br />
<br />
{{ic|virtio-vga}} / {{ic|virtio-gpu}} is a paravirtual 3D graphics driver based on [https://virgil3d.github.io/ virgl]. It's mature, currently supporting only Linux guests with {{Pkg|mesa}} compiled with the option {{ic|1=gallium-drivers=virgl}}.<br />
<br />
To enable 3D acceleration on the guest system, select this vga with {{ic|-device virtio-vga-gl}} and enable the OpenGL context in the display device with {{ic|1=-display sdl,gl=on}} or {{ic|1=-display gtk,gl=on}} for the SDL and GTK display output respectively. Successful configuration can be confirmed looking at the kernel log in the guest:<br />
<br />
{{hc|# dmesg {{!}} grep drm |<br />
[drm] pci: virtio-vga detected<br />
[drm] virgl 3d acceleration enabled<br />
}}<br />
<br />
=== cirrus ===<br />
<br />
The cirrus graphical adapter was the default [https://wiki.qemu.org/ChangeLog/2.2#VGA before 2.2]. It [https://www.kraxel.org/blog/2014/10/qemu-using-cirrus-considered-harmful/ should not] be used on modern systems.<br />
<br />
=== none ===<br />
<br />
This is like a PC that has no VGA card at all. You would not even be able to access it with the {{ic|-vnc}} option. Also, this is different from the {{ic|-nographic}} option which lets QEMU emulate a VGA card, but disables the SDL display.<br />
<br />
== SPICE ==<br />
<br />
The [https://www.spice-space.org/ SPICE project] aims to provide a complete open source solution for remote access to virtual machines in a seamless way.<br />
<br />
=== Enabling SPICE support on the host ===<br />
<br />
The following is an example of booting with SPICE as the remote desktop protocol, including the support for copy and paste from host:<br />
<br />
$ qemu-system-x86_64 -vga qxl -device virtio-serial-pci -spice port=5930,disable-ticketing=on -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
The parameters have the following meaning:<br />
<br />
# {{ic|-device virtio-serial-pci}} adds a virtio-serial device<br />
# {{ic|1=-spice port=5930,disable-ticketing=on}} set TCP port {{ic|5930}} for spice channels listening and allow client to connect without authentication{{Tip|Using [[wikipedia:Unix_socket|Unix sockets]] instead of TCP ports does not involve using network stack on the host system. It does not imply that packets are encapsulated and decapsulated to use the network and the related protocol. The sockets are identified solely by the inodes on the hard drive. It is therefore considered better for performance. Use instead {{ic|1=-spice unix=on,addr=/tmp/vm_spice.socket,disable-ticketing=on}}.}}<br />
# {{ic|1=-device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0}} opens a port for spice vdagent in the virtio-serial device,<br />
# {{ic|1=-chardev spicevmc,id=spicechannel0,name=vdagent}} adds a spicevmc chardev for that port. It is important that the {{ic|1=chardev=}} option of the {{ic|virtserialport}} device matches the {{ic|1=id=}} option given to the {{ic|chardev}} option ({{ic|spicechannel0}} in this example). It is also important that the port name is {{ic|com.redhat.spice.0}}, because that is the namespace where vdagent is looking for in the guest. And finally, specify {{ic|1=name=vdagent}} so that spice knows what this channel is for.<br />
<br />
=== Connecting to the guest with a SPICE client ===<br />
<br />
A SPICE client is necessary to connect to the guest. In Arch, the following clients are available:<br />
<br />
* {{App|virt-viewer|SPICE client recommended by the protocol developers, a subset of the virt-manager project.|https://virt-manager.org/|{{Pkg|virt-viewer}}}}<br />
* {{App|spice-gtk|SPICE GTK client, a subset of the SPICE project. Embedded into other applications as a widget.|https://www.spice-space.org/|{{Pkg|spice-gtk}}}}<br />
<br />
For clients that run on smartphone or on other platforms, refer to the ''Other clients'' section in [https://www.spice-space.org/download.html spice-space download].<br />
<br />
==== Manually running a SPICE client ====<br />
<br />
One way of connecting to a guest listening on Unix socket {{ic|/tmp/vm_spice.socket}} is to manually run the SPICE client using {{ic|$ remote-viewer spice+unix:///tmp/vm_spice.socket}} or {{ic|1=$ spicy --uri="spice+unix:///tmp/vm_spice.socket"}}, depending on the desired client. Since QEMU in SPICE mode acts similarly to a remote desktop server, it may be more convenient to run QEMU in daemon mode with the {{ic|-daemonize}} parameter.<br />
<br />
{{Tip|<br />
To connect to the guest through SSH tunneling, the following type of command can be used: {{bc|$ ssh -fL 5999:localhost:5930 ''my.domain.org'' sleep 10; spicy -h 127.0.0.1 -p 5999}}<br />
This example connects ''spicy'' to the local port {{ic|5999}} which is forwarded through SSH to the guest's SPICE server located at the address ''my.domain.org'', port {{ic|5930}}.<br />
Note the {{ic|-f}} option that requests ssh to execute the command {{ic|sleep 10}} in the background. This way, the ssh session runs while the client is active and auto-closes once the client ends.<br />
}}<br />
<br />
==== Running a SPICE client with QEMU ====<br />
<br />
QEMU can automatically start a SPICE client with an appropriate socket, if the display is set to SPICE with the {{ic|-display spice-app}} parameter. This will use the system's default SPICE client as the viewer, determined by your [[XDG MIME Applications#mimeapps.list|mimeapps.list]] files.<br />
<br />
=== Enabling SPICE support on the guest ===<br />
<br />
For '''Arch Linux guests''', for improved support for multiple monitors or clipboard sharing, the following packages should be installed:<br />
* {{Pkg|spice-vdagent}}: Spice agent xorg client that enables copy and paste between client and X-session and more. (Refer to this [https://github.com/systemd/systemd/issues/18791 issue], until fixed, for workarounds to get this to work on non-GNOME desktops.)<br />
* {{Pkg|xf86-video-qxl}}: Xorg X11 qxl video driver<br />
* {{AUR|x-resize}}: Desktop environments other than GNOME do not react automatically when the SPICE client window is resized. This package uses a [[udev]] rule and [[xrandr]] to implement auto-resizing for all X11-based desktop environments and window managers.<br />
For guests under '''other operating systems''', refer to the ''Guest'' section in spice-space [https://www.spice-space.org/download.html download].<br />
<br />
=== Password authentication with SPICE ===<br />
<br />
If you want to enable password authentication with SPICE you need to remove {{ic|disable-ticketing}} from the {{ic|-spice}} argument and instead add {{ic|1=password=''yourpassword''}}. For example:<br />
<br />
$ qemu-system-x86_64 -vga qxl -spice port=5900,password=''yourpassword'' -device virtio-serial-pci -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
Your SPICE client should now ask for the password to be able to connect to the SPICE server.<br />
<br />
=== TLS encrypted communication with SPICE ===<br />
<br />
You can also configure TLS encryption for communicating with the SPICE server. First, you need to have a directory which contains the following files (the names must be exactly as indicated):<br />
<br />
* {{ic|ca-cert.pem}}: the CA master certificate.<br />
* {{ic|server-cert.pem}}: the server certificate signed with {{ic|ca-cert.pem}}.<br />
* {{ic|server-key.pem}}: the server private key.<br />
<br />
An example of generation of self-signed certificates with your own generated CA for your server is shown in the [https://www.spice-space.org/spice-user-manual.html#_generating_self_signed_certificates Spice User Manual].<br />
<br />
Afterwards, you can run QEMU with SPICE as explained above but using the following {{ic|-spice}} argument: {{ic|1=-spice tls-port=5901,password=''yourpassword'',x509-dir=''/path/to/pki_certs''}}, where {{ic|''/path/to/pki_certs''}} is the directory path that contains the three needed files shown earlier.<br />
<br />
It is now possible to connect to the server using {{Pkg|virt-viewer}}:<br />
<br />
$ remote-viewer spice://''hostname''?tls-port=5901 --spice-ca-file=''/path/to/ca-cert.pem'' --spice-host-subject="C=''XX'',L=''city'',O=''organization'',CN=''hostname''" --spice-secure-channels=all<br />
<br />
Keep in mind that the {{ic|--spice-host-subject}} parameter needs to be set according to your {{ic|server-cert.pem}} subject. You also need to copy {{ic|ca-cert.pem}} to every client to verify the server certificate.<br />
<br />
{{Tip|You can get the subject line of the server certificate in the correct format for {{ic|--spice-host-subject}} (with entries separated by commas) using the following command: {{bc|<nowiki>$ openssl x509 -noout -subject -in server-cert.pem | cut -d' ' -f2- | sed 's/\///' | sed 's/\//,/g'</nowiki>}}<br />
}}<br />
<br />
The equivalent {{Pkg|spice-gtk}} command is:<br />
<br />
$ spicy -h ''hostname'' -s 5901 --spice-ca-file=ca-cert.pem --spice-host-subject="C=''XX'',L=''city'',O=''organization'',CN=''hostname''" --spice-secure-channels=all<br />
<br />
== VNC ==<br />
<br />
One can add the {{ic|-vnc :''X''}} option to have QEMU redirect the VGA display to the VNC session. Substitute {{ic|''X''}} for the number of the display (0 will then listen on 5900, 1 on 5901...).<br />
<br />
$ qemu-system-x86_64 -vnc :0<br />
<br />
An example is also provided in the [[#Starting QEMU virtual machines on boot]] section.<br />
<br />
{{Warning|The default VNC server setup does not use any form of authentication. Any user can connect from any host.}}<br />
<br />
=== Basic password authentication ===<br />
<br />
An access password can be setup easily by using the {{ic|password}} option. The password must be indicated in the QEMU monitor and connection is only possible once the password is provided.<br />
<br />
$ qemu-system-x86_64 -vnc :0,password -monitor stdio<br />
<br />
In the QEMU monitor, password is set using the command {{ic|change vnc password}} and then indicating the password.<br />
<br />
The following command line directly runs vnc with a password:<br />
<br />
$ printf "change vnc password\n%s\n" MYPASSWORD | qemu-system-x86_64 -vnc :0,password -monitor stdio<br />
<br />
{{Note|The password is limited to 8 characters and can be guessed through brute force attack. More elaborated protection is strongly recommended for public network.}}<br />
<br />
== Audio ==<br />
<br />
=== Creating an audio backend ===<br />
<br />
The {{ic|-audiodev}} flag sets the audio backend driver on the host and its options.<br />
<br />
To list availabe audio backend drivers:<br />
<br />
$ qemu-system-x86_64 -audiodev help<br />
<br />
Their optional settings are detailed in the {{man|1|qemu}} man page.<br />
<br />
At the bare minimum, one need to choose an audio backend and set an id, for [[PulseAudio]] for example:<br />
<br />
-audiodev pa,id=snd0<br />
<br />
=== Using the audio backend ===<br />
<br />
==== Intel HD Audio ====<br />
<br />
For Intel HD Audio emulation, add both controller and codec devices. To list the available Intel HDA Audio devices:<br />
<br />
$ qemu-system-x86_64 -device help | grep hda<br />
<br />
Add the audio controller:<br />
<br />
-device ich9-intel-hda<br />
<br />
Also, add the audio codec and map it to a host audio backend id:<br />
<br />
-device hda-output,audiodev=snd0<br />
<br />
==== Intel 82801AA AC97 ====<br />
<br />
For AC97 emulation just add the audio card device and map it to a host audio backend id<br />
<br />
-device AC97,audiodev=snd0<br />
<br />
{{Note|<br />
* If the audiodev backend is not provided, QEMU looks up for it and adds it automatically, this only works for a single audiodev. For example {{ic|-device intel-hda -device hda-duplex}} will emulate {{ic|intel-hda}} on the guest using the default audiodev backend.<br />
* Video graphic card emulated drivers for the guest machine may also cause a problem with the sound quality. Test one by one to make it work. You can list possible options with {{ic|<nowiki>qemu-system-x86_64 -h | grep vga</nowiki>}}.<br />
}}<br />
<br />
==== VirtIO sound ====<br />
<br />
VirtIO sound is also available since QEMU 8.2.0. The usage is:<br />
<br />
-device virtio-sound-pci,audiodev=my_audiodev -audiodev alsa,id=my_audiodev<br />
<br />
More information can be found in [https://qemu-project.gitlab.io/qemu/system/devices/virtio-snd.html QEMU documentation].<br />
<br />
== Installing virtio drivers ==<br />
<br />
QEMU offers guests the ability to use paravirtualized block and network devices using the [https://wiki.libvirt.org/page/Virtio virtio] drivers, which provide better performance and lower overhead.<br />
<br />
* A virtio block device requires the option {{ic|-drive}} for passing a disk image, with parameter {{ic|1=if=virtio}}:<br />
$ qemu-system-x86_64 -drive file=''disk_image'',if='''virtio'''<br />
<br />
* Almost the same goes for the network:<br />
$ qemu-system-x86_64 -nic user,model='''virtio-net-pci'''<br />
<br />
{{Note|This will only work if the guest machine has drivers for virtio devices. Linux does, and the required drivers are included in Arch Linux, but there is no guarantee that virtio devices will work with other operating systems.}}<br />
<br />
=== Preparing an Arch Linux guest ===<br />
<br />
To use virtio devices after an Arch Linux guest has been installed, the following modules must be loaded in the guest: {{ic|virtio}}, {{ic|virtio_pci}}, {{ic|virtio_blk}}, {{ic|virtio_net}}, and {{ic|virtio_ring}}. For 32-bit guests, the specific "virtio" module is not necessary.<br />
<br />
If you want to boot from a virtio disk, the initial ramdisk must contain the necessary modules. By default, this is handled by [[mkinitcpio]]'s {{ic|autodetect}} hook. Otherwise use the {{ic|MODULES}} array in {{ic|/etc/mkinitcpio.conf}} to include the necessary modules and rebuild the initial ramdisk.<br />
<br />
{{hc|/etc/mkinitcpio.conf|2=<br />
MODULES=(virtio virtio_blk virtio_pci virtio_net)}}<br />
<br />
Virtio disks are recognized with the prefix {{ic|'''v'''}} (e.g. {{ic|'''v'''da}}, {{ic|'''v'''db}}, etc.); therefore, changes must be made in at least {{ic|/etc/fstab}} and {{ic|/boot/grub/grub.cfg}} when booting from a virtio disk.<br />
<br />
{{Tip|When referencing disks by [[UUID]] in both {{ic|/etc/fstab}} and boot loader, nothing has to be done.}}<br />
<br />
Further information on paravirtualization with KVM can be found [https://www.linux-kvm.org/page/Boot_from_virtio_block_device here].<br />
<br />
You might also want to install {{Pkg|qemu-guest-agent}} to implement support for QMP commands that will enhance the hypervisor management capabilities.<br />
<br />
=== Preparing a Windows guest ===<br />
<br />
==== Virtio drivers for Windows ====<br />
<br />
Windows does not come with the virtio drivers. The latest and stable versions of the drivers are regularly built by Fedora, details on downloading the drivers are given on [https://github.com/virtio-win/virtio-win-pkg-scripts/blob/master/README.md virtio-win on GitHub]. In the following sections we will mostly use the stable ISO file provided here: [https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/stable-virtio/virtio-win.iso virtio-win.iso]. Alternatively, use {{AUR|virtio-win}}.<br />
<br />
==== Block device drivers ====<br />
<br />
===== New Install of Windows =====<br />
<br />
The drivers need to be loaded during installation, the procedure is to load the ISO image with the virtio drivers in a cdrom device along with the primary disk device and the Windows ISO install media:<br />
<br />
$ qemu-system-x86_64 ... \<br />
-drive file=''disk_image'',index=0,media=disk,if=virtio \<br />
-drive file=''windows.iso'',index=2,media=cdrom \<br />
-drive file=''virtio-win.iso'',index=3,media=cdrom \<br />
...<br />
<br />
During the installation, at some stage, the Windows installer will ask "Where do you want to install Windows?", it will give a warning that no disks are found. Follow the example instructions below (based on Windows Server 2012 R2 with Update).<br />
<br />
* Select the option ''Load Drivers''.<br />
* Uncheck the box for ''Hide drivers that are not compatible with this computer's hardware''.<br />
* Click the browse button and open the CDROM for the virtio iso, usually named "virtio-win-XX".<br />
* Now browse to {{ic|E:\viostor\[your-os]\amd64}}, select it, and confirm.<br />
<br />
You should now see your virtio disk(s) listed here, ready to be selected, formatted and installed to.<br />
<br />
===== Change existing Windows virtual machine to use virtio =====<br />
<br />
Modifying an existing Windows guest for booting from virtio disk requires that the virtio driver is loaded by the guest at boot time.<br />
We will therefore need to teach Windows to load the virtio driver at boot time before being able to boot a disk image in virtio mode.<br />
<br />
To achieve that, first create a new disk image that will be attached in virtio mode and trigger the search for the driver:<br />
<br />
$ qemu-img create -f qcow2 ''dummy.qcow2'' 1G<br />
<br />
Run the original Windows guest with the boot disk still in IDE mode, the fake disk in virtio mode and the driver ISO image.<br />
<br />
$ qemu-system-x86_64 -m 4G -drive file=''disk_image'',if=ide -drive file=''dummy.qcow2'',if=virtio -cdrom virtio-win.iso<br />
<br />
Windows will detect the fake disk and look for a suitable driver. If it fails, go to ''Device Manager'', locate the SCSI drive with an exclamation mark icon (should be open), click ''Update driver'' and select the virtual CD-ROM. Do not navigate to the driver folder within the CD-ROM, simply select the CD-ROM drive and Windows will find the appropriate driver automatically (tested for Windows 7 SP1).<br />
<br />
Request Windows to boot in safe mode next time it starts up. This can be done using the ''msconfig.exe'' tool in Windows. In safe mode all the drivers will be loaded at boot time including the new virtio driver. Once Windows knows that the virtio driver is required at boot it will memorize it for future boot.<br />
<br />
Once instructed to boot in safe mode, you can turn off the virtual machine and launch it again, now with the boot disk attached in virtio mode:<br />
<br />
$ qemu-system-x86_64 -m 4G -drive file=''disk_image'',if=virtio<br />
<br />
You should boot in safe mode with virtio driver loaded, you can now return to ''msconfig.exe'' disable safe mode boot and restart Windows.<br />
<br />
{{Note|If you encounter the blue screen of death using the {{ic|1=if=virtio}} parameter, it probably means the virtio disk driver is not installed or not loaded at boot time, reboot in safe mode and check your driver configuration.}}<br />
<br />
==== Network drivers ====<br />
<br />
Installing virtio network drivers is a bit easier, simply add the {{ic|-nic}} argument.<br />
<br />
$ qemu-system-x86_64 -m 4G -drive file=''windows_disk_image'',if=virtio -nic user,model=virtio-net-pci -cdrom virtio-win.iso<br />
<br />
Windows will detect the network adapter and try to find a driver for it. If it fails, go to the ''Device Manager'', locate the network adapter with an exclamation mark icon (should be open), click ''Update driver'' and select the virtual CD-ROM. Do not forget to select the checkbox which says to search for directories recursively.<br />
<br />
==== Balloon driver ====<br />
<br />
If you want to track you guest memory state (for example via {{ic|virsh}} command {{ic|dommemstat}}) or change guest's memory size in runtime (you still will not be able to change memory size, but can limit memory usage via inflating balloon driver) you will need to install guest balloon driver.<br />
<br />
For this you will need to go to ''Device Manager'', locate ''PCI standard RAM Controller'' in ''System devices'' (or unrecognized PCI controller from ''Other devices'') and choose ''Update driver''. In opened window you will need to choose ''Browse my computer...'' and select the CD-ROM (and do not forget the ''Include subdirectories'' checkbox). Reboot after installation. This will install the driver and you will be able to inflate the balloon (for example via hmp command {{ic|balloon ''memory_size''}}, which will cause balloon to take as much memory as possible in order to shrink the guest's available memory size to ''memory_size''). However, you still will not be able to track guest memory state. In order to do this you will need to install ''Balloon'' service properly. For that open command line as administrator, go to the CD-ROM, ''Balloon'' directory and deeper, depending on your system and architecture. Once you are in ''amd64'' (''x86'') directory, run {{ic|blnsrv.exe -i}} which will do the installation. After that {{ic|virsh}} command {{ic|dommemstat}} should be outputting all supported values.<br />
<br />
=== Preparing a FreeBSD guest ===<br />
<br />
Install the {{ic|emulators/virtio-kmod}} port if you are using FreeBSD 8.3 or later up until 10.0-CURRENT where they are included into the kernel. After installation, add the following to your {{ic|/boot/loader.conf}} file:<br />
<br />
{{bc|1=<br />
virtio_load="YES"<br />
virtio_pci_load="YES"<br />
virtio_blk_load="YES"<br />
if_vtnet_load="YES"<br />
virtio_balloon_load="YES"<br />
}}<br />
<br />
Then modify your {{ic|/etc/fstab}} by doing the following:<br />
<br />
# sed -ibak "s/ada/vtbd/g" /etc/fstab<br />
<br />
And verify that {{ic|/etc/fstab}} is consistent. If anything goes wrong, just boot into a rescue CD and copy {{ic|/etc/fstab.bak}} back to {{ic|/etc/fstab}}.<br />
<br />
== QEMU monitor ==<br />
<br />
While QEMU is running, a monitor console is provided in order to provide several ways to interact with the virtual machine running. The QEMU monitor offers interesting capabilities such as obtaining information about the current virtual machine, hotplugging devices, creating snapshots of the current state of the virtual machine, etc. To see the list of all commands, run {{ic|help}} or {{ic|?}} in the QEMU monitor console or review the relevant section of the [https://www.qemu.org/docs/master/system/monitor.html official QEMU documentation].<br />
<br />
=== Accessing the monitor console ===<br />
<br />
==== Graphical view ====<br />
<br />
When using the {{ic|std}} default graphics option, one can access the QEMU monitor by pressing {{ic|Ctrl+Alt+2}} or by clicking ''View > compatmonitor0'' in the QEMU window. To return to the virtual machine graphical view either press {{ic|Ctrl+Alt+1}} or click ''View > VGA''.<br />
<br />
However, the standard method of accessing the monitor is not always convenient and does not work in all graphic outputs QEMU supports.<br />
<br />
==== Telnet ====<br />
<br />
To enable [[telnet]], run QEMU with the {{ic|-monitor telnet:127.0.0.1:''port'',server,nowait}} parameter. When the virtual machine is started you will be able to access the monitor via telnet:<br />
<br />
$ telnet 127.0.0.1 ''port''<br />
<br />
{{Note|If {{ic|127.0.0.1}} is specified as the IP to listen it will be only possible to connect to the monitor from the same host QEMU is running on. If connecting from remote hosts is desired, QEMU must be told to listen {{ic|0.0.0.0}} as follows: {{ic|-monitor telnet:0.0.0.0:''port'',server,nowait}}. Keep in mind that it is recommended to have a [[firewall]] configured in this case or make sure your local network is completely trustworthy since this connection is completely unauthenticated and unencrypted.}}<br />
<br />
==== UNIX socket ====<br />
<br />
Run QEMU with the {{ic|-monitor unix:''socketfile'',server,nowait}} parameter. Then you can connect with either {{Pkg|socat}}, {{Pkg|nmap}} or {{Pkg|openbsd-netcat}}.<br />
<br />
For example, if QEMU is run via:<br />
<br />
$ qemu-system-x86_64 -monitor unix:/tmp/monitor.sock,server,nowait ''[...]''<br />
<br />
It is possible to connect to the monitor with:<br />
<br />
$ socat - UNIX-CONNECT:/tmp/monitor.sock<br />
<br />
Or with:<br />
<br />
$ nc -U /tmp/monitor.sock<br />
<br />
Alternatively with {{Pkg|nmap}}:<br />
<br />
$ ncat -U /tmp/monitor.sock<br />
<br />
==== TCP ====<br />
<br />
You can expose the monitor over TCP with the argument {{ic|-monitor tcp:127.0.0.1:''port'',server,nowait}}. Then connect with netcat, either {{Pkg|openbsd-netcat}} or {{Pkg|gnu-netcat}} by running:<br />
<br />
$ nc 127.0.0.1 ''port''<br />
<br />
{{Note|In order to be able to connect to the tcp socket from other devices other than the same host QEMU is being run on you need to listen to {{ic|0.0.0.0}} like explained in the telnet case. The same security warnings apply in this case as well.}}<br />
<br />
==== Standard I/O ====<br />
<br />
It is possible to access the monitor automatically from the same terminal QEMU is being run by running it with the argument {{ic|-monitor stdio}}.<br />
<br />
=== Sending keyboard presses to the virtual machine using the monitor console ===<br />
<br />
Some combinations of keys may be difficult to perform on virtual machines due to the host intercepting them instead in some configurations (a notable example is the {{ic|Ctrl+Alt+F*}} key combinations, which change the active tty). To avoid this problem, the problematic combination of keys may be sent via the monitor console instead. Switch to the monitor and use the {{ic|sendkey}} command to forward the necessary keypresses to the virtual machine. For example:<br />
<br />
(qemu) sendkey ctrl-alt-f2<br />
<br />
=== Creating and managing snapshots via the monitor console ===<br />
<br />
{{Note|This feature will '''only''' work when the virtual machine disk image is in ''qcow2'' format. It will not work with ''raw'' images.}}<br />
<br />
It is sometimes desirable to save the current state of a virtual machine and having the possibility of reverting the state of the virtual machine to that of a previously saved snapshot at any time. The QEMU monitor console provides the user with the necessary utilities to create snapshots, manage them, and revert the machine state to a saved snapshot.<br />
<br />
* Use {{ic|savevm ''name''}} in order to create a snapshot with the tag ''name''.<br />
* Use {{ic|loadvm ''name''}} to revert the virtual machine to the state of the snapshot ''name''.<br />
* Use {{ic|delvm ''name''}} to delete the snapshot tagged as ''name''.<br />
* Use {{ic|info snapshots}} to see a list of saved snapshots. Snapshots are identified by both an auto-incremented ID number and a text tag (set by the user on snapshot creation).<br />
<br />
=== Running the virtual machine in immutable mode ===<br />
<br />
It is possible to run a virtual machine in a frozen state so that all changes will be discarded when the virtual machine is powered off just by running QEMU with the {{ic|-snapshot}} parameter. When the disk image is written by the guest, changes will be saved in a temporary file in {{ic|/tmp}} and will be discarded when QEMU halts.<br />
<br />
However, if a machine is running in frozen mode it is still possible to save the changes to the disk image if it is afterwards desired by using the monitor console and running the following command:<br />
<br />
(qemu) commit all<br />
<br />
If snapshots are created when running in frozen mode they will be discarded as soon as QEMU is exited unless changes are explicitly commited to disk, as well.<br />
<br />
=== Pause and power options via the monitor console ===<br />
<br />
Some operations of a physical machine can be emulated by QEMU using some monitor commands:<br />
<br />
* {{ic|system_powerdown}} will send an ACPI shutdown request to the virtual machine. This effect is similar to the power button in a physical machine.<br />
* {{ic|system_reset}} will reset the virtual machine similarly to a reset button in a physical machine. This operation can cause data loss and file system corruption since the virtual machine is not cleanly restarted.<br />
* {{ic|stop}} will pause the virtual machine.<br />
* {{ic|cont}} will resume a virtual machine previously paused.<br />
<br />
=== Taking screenshots of the virtual machine ===<br />
<br />
Screenshots of the virtual machine graphic display can be obtained in the PPM format by running the following command in the monitor console:<br />
<br />
(qemu) screendump ''file.ppm''<br />
<br />
== QEMU machine protocol ==<br />
<br />
The QEMU machine protocol (QMP) is a JSON-based protocol which allows applications to control a QEMU instance. Similarly to the [[#QEMU monitor]] it offers ways to interact with a running machine and the JSON protocol allows to do it programmatically. The description of all the QMP commands can be found in [https://raw.githubusercontent.com/coreos/qemu/master/qmp-commands.hx qmp-commands].<br />
<br />
=== Start QMP ===<br />
<br />
The usual way to control the guest using the QMP protocol, is to open a TCP socket when launching the machine using the {{ic|-qmp}} option. Here it is using for example the TCP port 4444:<br />
<br />
$ qemu-system-x86_64 ''[...]'' -qmp tcp:localhost:4444,server,nowait<br />
<br />
Then one way to communicate with the QMP agent is to use [[netcat]]:<br />
<br />
{{hc|nc localhost 4444|{"QMP": {"version": {"qemu": {"micro": 0, "minor": 1, "major": 3}, "package": ""}, "capabilities": []} } }}<br />
<br />
At this stage, the only command that can be recognized is {{ic|qmp_capabilities}}, so that QMP enters into command mode. Type:<br />
<br />
{"execute": "qmp_capabilities"}<br />
<br />
Now, QMP is ready to receive commands, to retrieve the list of recognized commands, use:<br />
<br />
{"execute": "query-commands"}<br />
<br />
=== Live merging of child image into parent image ===<br />
<br />
It is possible to merge a running snapshot into its parent by issuing a {{ic|block-commit}} command. In its simplest form the following line will commit the child into its parent:<br />
<br />
{"execute": "block-commit", "arguments": {"device": "''devicename''"}}<br />
<br />
Upon reception of this command, the handler looks for the base image and converts it from read only to read write mode and then runs the commit job.<br />
<br />
Once the ''block-commit'' operation has completed, the event {{ic|BLOCK_JOB_READY}} will be emitted, signalling that the synchronization has finished. The job can then be gracefully completed by issuing the command {{ic|block-job-complete}}:<br />
<br />
{"execute": "block-job-complete", "arguments": {"device": "''devicename''"}}<br />
<br />
Until such a command is issued, the ''commit'' operation remains active.<br />
After successful completion, the base image remains in read write mode and becomes the new active layer. On the other hand, the child image becomes invalid and it is the responsibility of the user to clean it up.<br />
<br />
{{Tip|The list of device and their names can be retrieved by executing the command {{ic|query-block}} and parsing the results. The device name is in the {{ic|device}} field, for example {{ic|ide0-hd0}} for the hard disk in this example: {{hc|{"execute": "query-block"}|{"return": [{"io-status": "ok", "device": "'''ide0-hd0'''", "locked": false, "removable": false, "inserted": {"iops_rd": 0, "detect_zeroes": "off", "image": {"backing-image": {"virtual-size": 27074281472, "filename": "parent.qcow2", ... } }} }}<br />
<br />
=== Live creation of a new snapshot ===<br />
<br />
To create a new snapshot out of a running image, run the command:<br />
<br />
{"execute": "blockdev-snapshot-sync", "arguments": {"device": "''devicename''","snapshot-file": "''new_snapshot_name''.qcow2"}}<br />
<br />
This creates an overlay file named {{ic|''new_snapshot_name''.qcow2}} which then becomes the new active layer.<br />
<br />
== Tips and tricks ==<br />
<br />
=== Improve virtual machine performance ===<br />
<br />
There are a number of techniques that you can use to improve the performance of the virtual machine. For example:<br />
<br />
* Apply [[#Enabling KVM]] for full virtualization.<br />
* Use the {{ic|-cpu host}} option to make QEMU emulate the host's exact CPU rather than a more generic CPU.<br />
* Especially for Windows guests, enable [https://blog.wikichoon.com/2014/07/enabling-hyper-v-enlightenments-with-kvm.html Hyper-V enlightenments]: {{ic|1=-cpu host,hv_relaxed,hv_spinlocks=0x1fff,hv_vapic,hv_time}}. See the [https://www.qemu.org/docs/master/system/i386/hyperv.html QEMU documentation] for more information and flags.<br />
* multiple cores can be assigned to the guest using the {{ic|-smp cores{{=}}x,threads{{=}}y,sockets{{=}}1,maxcpus{{=}}z}} option. The threads parameter is used to assign [https://www.tomshardware.com/reviews/simultaneous-multithreading-definition,5762.html SMT cores]. Leaving a physical core for QEMU, the hypervisor and the host system to operate unimpeded is highly beneficial.<br />
* Make sure you have assigned the virtual machine enough memory. By default, QEMU only assigns 128 MiB of memory to each virtual machine. Use the {{ic|-m}} option to assign more memory. For example, {{ic|-m 1024}} runs a virtual machine with 1024 MiB of memory.<br />
* If supported by drivers in the guest operating system, use virtio for network and/or block devices, see [[#Installing virtio drivers]].<br />
* Use TAP devices instead of user-mode networking, see [[#Tap networking with QEMU]].<br />
* If the guest OS is doing heavy writing to its disk, you may benefit from certain mount options on the host's file system. For example, you can mount an [[Ext4|ext4 file system]] with the option {{ic|1=barrier=0}}. You should read the documentation for any options that you change because sometimes performance-enhancing options for file systems come at the cost of data integrity.<br />
* If you have a raw disk or partition, you may want to disable the cache: {{bc|1=$ qemu-system-x86_64 -drive file=/dev/''disk'',if=virtio,'''cache=none'''}}<br />
* Use the native Linux AIO: {{bc|1=$ qemu-system-x86_64 -drive file=''disk_image'',if=virtio''',aio=native,cache.direct=on'''}}<br />
* If you are running multiple virtual machines concurrently that all have the same operating system installed, you can save memory by enabling [[wikipedia:Kernel_SamePage_Merging_(KSM)|kernel same-page merging]]. See [[#Enabling KSM]].<br />
* In some cases, memory can be reclaimed from running virtual machines by running a memory ballooning driver in the guest operating system and launching QEMU using {{ic|-device virtio-balloon}}.<br />
* It is possible to use a emulation layer for an ICH-9 AHCI controller (although it may be unstable). The AHCI emulation supports [[Wikipedia:Native_Command_Queuing|NCQ]], so multiple read or write requests can be outstanding at the same time: {{bc|1=$ qemu-system-x86_64 -drive id=disk,file=''disk_image'',if=none -device ich9-ahci,id=ahci -device ide-drive,drive=disk,bus=ahci.0}}<br />
<br />
See https://www.linux-kvm.org/page/Tuning_KVM for more information.<br />
<br />
=== Starting QEMU virtual machines on boot ===<br />
<br />
==== With libvirt ====<br />
<br />
If a virtual machine is set up with [[libvirt]], it can be configured with {{ic|virsh autostart}} or through the ''virt-manager'' GUI to start at host boot by going to the Boot Options for the virtual machine and selecting "Start virtual machine on host boot up".<br />
<br />
==== With systemd service ====<br />
<br />
To run QEMU virtual machines on boot, you can use following systemd unit and config.<br />
<br />
{{hc|/etc/systemd/system/qemu@.service|2=<br />
[Unit]<br />
Description=QEMU virtual machine<br />
<br />
[Service]<br />
Environment="haltcmd=kill -INT $MAINPID"<br />
EnvironmentFile=/etc/conf.d/qemu.d/%i<br />
ExecStart=/usr/bin/qemu-system-x86_64 -name %i -enable-kvm -m 512 -nographic $args<br />
ExecStop=/usr/bin/bash -c ${haltcmd}<br />
ExecStop=/usr/bin/bash -c 'while nc localhost 7100; do sleep 1; done'<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
}}<br />
<br />
{{Note|This service will wait for the console port to be released, which means that the virtual machine has been shutdown, to graciously end.}}<br />
<br />
Then create per-VM configuration files, named {{ic|/etc/conf.d/qemu.d/''vm_name''}}, with the variables {{ic|args}} and {{ic|haltcmd}} set. Example configs:<br />
<br />
{{hc|/etc/conf.d/qemu.d/one|2=<br />
args="-hda /dev/vg0/vm1 -serial telnet:localhost:7000,server,nowait,nodelay \<br />
-monitor telnet:localhost:7100,server,nowait,nodelay -vnc :0"<br />
<br />
haltcmd="echo 'system_powerdown' {{!}} nc localhost 7100" # or netcat/ncat}}<br />
<br />
{{hc|/etc/conf.d/qemu.d/two|2=<br />
args="-hda /srv/kvm/vm2 -serial telnet:localhost:7001,server,nowait,nodelay -vnc :1"<br />
<br />
haltcmd="ssh powermanager@vm2 sudo poweroff"}}<br />
<br />
The description of the variables is the following:<br />
<br />
* {{ic|args}} - QEMU command line arguments to be used.<br />
* {{ic|haltcmd}} - Command to shut down a virtual machine safely. In the first example, the QEMU monitor is exposed via telnet using {{ic|-monitor telnet:..}} and the virtual machines are powered off via ACPI by sending {{ic|system_powerdown}} to monitor with the {{ic|nc}} command. In the other example, SSH is used.<br />
<br />
To set which virtual machines will start on boot-up, [[enable]] the {{ic|qemu@''vm_name''.service}} systemd unit.<br />
<br />
=== Mouse integration ===<br />
<br />
To prevent the mouse from being grabbed when clicking on the guest operating system's window, add the options {{ic|-usb -device usb-tablet}}. This means QEMU is able to report the mouse position without having to grab the mouse. This also overrides PS/2 mouse emulation when activated. For example:<br />
<br />
$ qemu-system-x86_64 -hda ''disk_image'' -m 512 -usb -device usb-tablet<br />
<br />
If that does not work, try using {{ic|-vga qxl}} parameter, also look at the instructions [[#Mouse cursor is jittery or erratic]].<br />
<br />
=== Pass-through host USB device ===<br />
<br />
It is possible to access the physical device connected to a USB port of the host from the guest. The first step is to identify where the device is connected, this can be found running the {{ic|lsusb}} command. For example:<br />
<br />
{{hc|$ lsusb|<br />
...<br />
Bus '''003''' Device '''007''': ID '''0781''':'''5406''' SanDisk Corp. Cruzer Micro U3<br />
}}<br />
<br />
The outputs in bold above will be useful to identify respectively the ''host_bus'' and ''host_addr'' or the ''vendor_id'' and ''product_id''.<br />
<br />
In qemu, the idea is to emulate an EHCI (USB 2) or XHCI (USB 1.1 USB 2 USB 3) controller with the option {{ic|1=-device usb-ehci,id=ehci}} or {{ic|1=-device qemu-xhci,id=xhci}} respectively and then attach the physical device to it with the option {{ic|1=-device usb-host,..}}. We will consider that ''controller_id'' is either {{ic|ehci}} or {{ic|xhci}} for the rest of this section.<br />
<br />
Then, there are two ways to connect to the USB of the host with qemu:<br />
<br />
# Identify the device and connect to it on any bus and address it is attached to on the host, the generic syntax is: {{bc|1=-device usb-host,bus=''controller_id''.0,vendorid=0x''vendor_id'',productid=0x''product_id''}}Applied to the device used in the example above, it becomes:{{bc|1=-device usb-ehci,id=ehci -device usb-host,bus=ehci.0,vendorid=0x'''0781''',productid=0x'''5406'''}}One can also add the {{ic|1=...,port=''port_number''}} setting to the previous option to specify in which physical port of the virtual controller the device should be attached, useful in the case one wants to add multiple USB devices to the virtual machine. Another option is to use the new {{ic|hostdevice}} property of {{ic|usb-host}} which is available since QEMU 5.1.0, the syntax is: {{bc|1=-device qemu-xhci,id=xhci -device usb-host,hostdevice=/dev/bus/usb/003/007}}<br />
# Attach whatever is connected to a given USB bus and address, the syntax is:{{bc|1=-device usb-host,bus=''controller_id''.0,hostbus=''host_bus'',host_addr=''host_addr''}}Applied to the bus and the address in the example above, it becomes:{{bc|1=-device usb-ehci,id=ehci -device usb-host,bus=ehci.0,hostbus='''3''',hostaddr='''7'''}}<br />
See [https://www.qemu.org/docs/master/system/devices/usb.html QEMU/USB emulation] for more information.<br />
{{Note|If you encounter permission errors when running QEMU, see [[udev#About udev rules]] for information on how to set permissions of the device.}}<br />
<br />
=== USB redirection with SPICE ===<br />
<br />
When using [[#SPICE]] it is possible to redirect USB devices from the client to the virtual machine without needing to specify them in the QEMU command. It is possible to configure the number of USB slots available for redirected devices (the number of slots will determine the maximum number of devices which can be redirected simultaneously). The main advantages of using SPICE for redirection compared to the previously-mentioned {{ic|-usbdevice}} method is the possibility of hot-swapping USB devices after the virtual machine has started, without needing to halt it in order to remove USB devices from the redirection or adding new ones. This method of USB redirection also allows us to redirect USB devices over the network, from the client to the server. In summary, it is the most flexible method of using USB devices in a QEMU virtual machine.<br />
<br />
We need to add one EHCI/UHCI controller per available USB redirection slot desired as well as one SPICE redirection channel per slot. For example, adding the following arguments to the QEMU command you use for starting the virtual machine in SPICE mode will start the virtual machine with three available USB slots for redirection:<br />
<br />
{{bc|1=<br />
-device ich9-usb-ehci1,id=usb \<br />
-device ich9-usb-uhci1,masterbus=usb.0,firstport=0,multifunction=on \<br />
-device ich9-usb-uhci2,masterbus=usb.0,firstport=2 \<br />
-device ich9-usb-uhci3,masterbus=usb.0,firstport=4 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev1 -device usb-redir,chardev=usbredirchardev1,id=usbredirdev1 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev2 -device usb-redir,chardev=usbredirchardev2,id=usbredirdev2 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev3 -device usb-redir,chardev=usbredirchardev3,id=usbredirdev3<br />
}}<br />
<br />
See [https://www.spice-space.org/usbredir.html SPICE/usbredir] for more information.<br />
<br />
Both {{ic|spicy}} from {{Pkg|spice-gtk}} (''Input > Select USB Devices for redirection'') and {{ic|remote-viewer}} from {{Pkg|virt-viewer}} (''File > USB device selection'') support this feature. Please make sure that you have installed the necessary SPICE Guest Tools on the virtual machine for this functionality to work as expected (see the [[#SPICE]] section for more information).<br />
<br />
{{Warning|Keep in mind that when a USB device is redirected from the client, it will not be usable from the client operating system itself until the redirection is stopped. It is specially important to never redirect the input devices (namely mouse and keyboard), since it will be then difficult to access the SPICE client menus to revert the situation, because the client will not respond to the input devices after being redirected to the virtual machine.}}<br />
<br />
==== Automatic USB forwarding with udev ====<br />
<br />
Normally, forwarded devices must be available at the boot time of the virtual machine to be forwarded. If that device is disconnected, it will not be forwarded anymore.<br />
<br />
You can use [[udev rule]]s to automatically attach a device when it comes online. Create a {{ic|hostdev}} entry somewhere on disk. [[chown]] it to root to prevent other users modifying it.<br />
<br />
{{hc|/usr/local/hostdev-mydevice.xml|2=<br />
<hostdev mode='subsystem' type='usb'><br />
<source><br />
<vendor id='0x03f0'/><br />
<product id='0x4217'/><br />
</source><br />
</hostdev><br />
}}<br />
<br />
Then create a ''udev'' rule which will attach/detach the device:<br />
<br />
{{hc|/usr/lib/udev/rules.d/90-libvirt-mydevice|2=<br />
ACTION=="add", \<br />
SUBSYSTEM=="usb", \<br />
ENV{ID_VENDOR_ID}=="03f0", \<br />
ENV{ID_MODEL_ID}=="4217", \<br />
RUN+="/usr/bin/virsh attach-device GUESTNAME /usr/local/hostdev-mydevice.xml"<br />
ACTION=="remove", \<br />
SUBSYSTEM=="usb", \<br />
ENV{ID_VENDOR_ID}=="03f0", \<br />
ENV{ID_MODEL_ID}=="4217", \<br />
RUN+="/usr/bin/virsh detach-device GUESTNAME /usr/local/hostdev-mydevice.xml"<br />
}}<br />
<br />
[https://rolandtapken.de/blog/2011-04/how-auto-hotplug-usb-devices-libvirt-vms-update-1 Source and further reading].<br />
<br />
=== Enabling KSM ===<br />
<br />
Kernel Samepage Merging (KSM) is a feature of the Linux kernel that allows for an application to register with the kernel to have its pages merged with other processes that also register to have their pages merged. The KSM mechanism allows for guest virtual machines to share pages with each other. In an environment where many of the guest operating systems are similar, this can result in significant memory savings.<br />
<br />
{{Note|Although KSM may reduce memory usage, it may increase CPU usage. Also note some security issues may occur, see [[Wikipedia:Kernel same-page merging]].}}<br />
<br />
To enable KSM:<br />
<br />
# echo 1 > /sys/kernel/mm/ksm/run<br />
<br />
To make it permanent, use [[systemd#systemd-tmpfiles - temporary files|systemd's temporary files]]:<br />
<br />
{{hc|/etc/tmpfiles.d/ksm.conf|<br />
w /sys/kernel/mm/ksm/run - - - - 1<br />
}}<br />
<br />
If KSM is running, and there are pages to be merged (i.e. at least two similar virtual machines are running), then {{ic|/sys/kernel/mm/ksm/pages_shared}} should be non-zero. See https://docs.kernel.org/admin-guide/mm/ksm.html for more information.<br />
<br />
{{Tip|An easy way to see how well KSM is performing is to simply print the contents of all the files in that directory:<br />
<br />
$ grep -r . /sys/kernel/mm/ksm/<br />
<br />
}}<br />
<br />
=== Multi-monitor support ===<br />
<br />
The Linux QXL driver supports four heads (virtual screens) by default. This can be changed via the {{ic|1=qxl.heads=N}} kernel parameter.<br />
<br />
The default VGA memory size for QXL devices is 16M (VRAM size is 64M). This is not sufficient if you would like to enable two 1920x1200 monitors since that requires 2 × 1920 × 4 (color depth) × 1200 = 17.6 MiB VGA memory. This can be changed by replacing {{ic|-vga qxl}} by {{ic|<nowiki>-vga none -device qxl-vga,vgamem_mb=32</nowiki>}}. If you ever increase vgamem_mb beyond 64M, then you also have to increase the {{ic|vram_size_mb}} option.<br />
<br />
=== Custom display resolution ===<br />
<br />
A custom display resolution can be set with {{ic|1=-device VGA,edid=on,xres=1280,yres=720}} (see [[wikipedia:Extended_Display_Identification_Data|EDID]] and [[wikipedia:Display_resolution|display resolution]]).<br />
<br />
=== Copy and paste ===<br />
<br />
==== SPICE ====<br />
<br />
One way to share the clipboard between the host and the guest is to enable the SPICE remote desktop protocol and access the client with a SPICE client.<br />
One needs to follow the steps described in [[#SPICE]]. A guest run this way will support copy paste with the host.<br />
<br />
==== qemu-vdagent ====<br />
<br />
QEMU provides its own implementation of the spice vdagent chardev called {{ic|qemu-vdagent}}. It interfaces with the spice-vdagent guest service and allows the guest and host share a clipboard.<br />
<br />
To access this shared clipboard with QEMU's GTK display, you will need to [[#Custom build|compile QEMU from source]] with the {{ic|--enable-gtk-clipboard}} configure parameter. It is sufficient to replace the installed {{ic|qemu-ui-gtk}} package.<br />
<br />
{{Note|<br />
* Feature request {{Bug|79716}} submitted to enable the functionality in the official package.<br />
* The shared clipboard in qemu-ui-gtk has been pushed back to experimental as it can [https://gitlab.com/qemu-project/qemu/-/issues/1150 freeze guests under certain circumstances]. A fix has been proposed to solve the issue upstream.<br />
}}<br />
<br />
Add the following QEMU command line arguments:<br />
<br />
-device virtio-serial,packed=on,ioeventfd=on<br />
-device virtserialport,name=com.redhat.spice.0,chardev=vdagent0<br />
-chardev qemu-vdagent,id=vdagent0,name=vdagent,clipboard=on,mouse=off<br />
<br />
These arguments are also valid if converted to [[Libvirt#QEMU command line arguments|libvirt form]].<br />
<br />
{{Note|While the spicevmc chardev will start the spice-vdagent service of the guest automatically, the qemu-vdagent chardev may not.}}<br />
<br />
On linux guests, you may [[start]] the {{ic|spice-vdagent.service}} [[user unit]] manually. On Windows guests, set the spice-agent startup type to automatic.<br />
<br />
=== Windows-specific notes ===<br />
<br />
QEMU can run any version of Windows from Windows 95 through Windows 11.<br />
<br />
It is possible to run [[Windows PE]] in QEMU.<br />
<br />
==== Fast startup ====<br />
<br />
{{Note|An administrator account is required to change power settings.}}<br />
<br />
For Windows 8 (or later) guests it is better to disable "Turn on fast startup (recommended)" from the Power Options of the Control Panel as explained in the following [https://www.tenforums.com/tutorials/4189-turn-off-fast-startup-windows-10-a.html forum page], as it causes the guest to hang during every other boot.<br />
<br />
Fast Startup may also need to be disabled for changes to the {{ic|-smp}} option to be properly applied.<br />
<br />
==== Remote Desktop Protocol ====<br />
<br />
If you use a MS Windows guest, you might want to use RDP to connect to your guest virtual machine. If you are using a VLAN or are not in the same network as the guest, use:<br />
<br />
$ qemu-system-x86_64 -nographic -nic user,hostfwd=tcp::5555-:3389<br />
<br />
Then connect with either {{Pkg|rdesktop}} or {{Pkg|freerdp}} to the guest. For example:<br />
<br />
$ xfreerdp -g 2048x1152 localhost:5555 -z -x lan<br />
<br />
=== Clone Linux system installed on physical equipment ===<br />
<br />
Linux system installed on physical equipment can be cloned for running on a QEMU virtual machine. See [https://coffeebirthday.wordpress.com/2018/09/14/clone-linux-system-for-qemu-virtual-machine/ Clone Linux system from hardware for QEMU virtual machine]<br />
<br />
=== Chrooting into arm/arm64 environment from x86_64 ===<br />
<br />
Sometimes it is easier to work directly on a disk image instead of the real ARM based device. This can be achieved by mounting an SD card/storage containing the ''root'' partition and chrooting into it.<br />
<br />
Another use case for an ARM chroot is building ARM packages on an x86_64 machine. Here, the chroot environment can be created from an image tarball from [https://archlinuxarm.org Arch Linux ARM] - see [https://nerdstuff.org/posts/2020/2020-003_simplest_way_to_create_an_arm_chroot/] for a detailed description of this approach.<br />
<br />
Either way, from the chroot it should be possible to run ''pacman'' and install more packages, compile large libraries etc. Since the executables are for the ARM architecture, the translation to x86 needs to be performed by [[QEMU]].<br />
<br />
Install {{Pkg|qemu-user-static}} on the x86_64 machine/host, and {{Pkg|qemu-user-static-binfmt}} to register the qemu binaries to binfmt service.<br />
<br />
''qemu-user-static'' is used to allow the execution of compiled programs from other architectures. This is similar to what is provided by {{Pkg|qemu-emulators-full}}, but the "static" variant is required for chroot. Examples:<br />
<br />
qemu-arm-static path_to_sdcard/usr/bin/ls<br />
qemu-aarch64-static path_to_sdcard/usr/bin/ls<br />
<br />
These two lines execute the {{ic|ls}} command compiled for 32-bit ARM and 64-bit ARM respectively. Note that this will not work without chrooting, because it will look for libraries not present in the host system.<br />
<br />
{{Pkg|qemu-user-static}} allows automatically prefixing the ARM exectuable with {{ic|qemu-arm-static}} or {{ic|qemu-aarch64-static}}.<br />
<br />
Make sure that the ARM executable support is active:<br />
<br />
{{hc|$ ls /proc/sys/fs/binfmt_misc|<br />
qemu-aarch64 qemu-arm qemu-cris qemu-microblaze qemu-mipsel qemu-ppc64 qemu-riscv64 qemu-sh4 qemu-sparc qemu-sparc64 status<br />
qemu-alpha qemu-armeb qemu-m68k qemu-mips qemu-ppc qemu-ppc64abi32 qemu-s390x qemu-sh4eb qemu-sparc32plus register<br />
}}<br />
<br />
Each executable must be listed.<br />
<br />
If it is not active, [[restart]] {{ic|systemd-binfmt.service}}.<br />
<br />
Mount the SD card to {{ic|/mnt/sdcard}} (the device name may be different).<br />
<br />
# mount --mkdir /dev/mmcblk0p2 /mnt/sdcard<br />
<br />
Mount boot partition if needed (again, use the suitable device name):<br />
<br />
# mount /dev/mmcblk0p1 /mnt/sdcard/boot<br />
<br />
Finally ''chroot'' into the SD card root as described in [[Change root#Using chroot]]:<br />
<br />
# chroot /mnt/sdcard /bin/bash<br />
<br />
Alternatively, you can use ''arch-chroot'' from {{Pkg|arch-install-scripts}}, as it will provide an easier way to get network support:<br />
<br />
# arch-chroot /mnt/sdcard /bin/bash<br />
<br />
You can also use [[systemd-nspawn]] to chroot into the ARM environment:<br />
<br />
# systemd-nspawn -D /mnt/sdcard -M myARMMachine --bind-ro=/etc/resolv.conf<br />
<br />
{{ic|1=--bind-ro=/etc/resolv.conf}} is optional and gives a working network DNS inside the chroot<br />
<br />
==== sudo in chroot ====<br />
<br />
If you install [[sudo]] in the chroot and receive the following error when trying to use it:<br />
<br />
sudo: effective uid is not 0, is /usr/bin/sudo on a file system with the 'nosuid' option set or an NFS file system without root privileges?<br />
<br />
then you may need to modify the binfmt flags, for example for {{ic|aarch64}}:<br />
<br />
# cp /usr/lib/binfmt.d/qemu-aarch64-static.conf /etc/binfmt.d/<br />
# vi /etc/binfmt.d/qemu-aarch64-static.conf<br />
<br />
and add a {{ic|C}} at the end of this file:<br />
<br />
:qemu-aarch64:M::\x7fELF\x02\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\xb7\x00:\xff\xff\xff\xff\xff\xff\xff\x00\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff\xff:/usr/bin/qemu-aarch64-static:FPC<br />
<br />
Then [[restart]] {{ic|systemd-binfmt.service}} and check that the changes have taken effect (note the {{ic|C}} on the {{ic|flags}} line):<br />
<br />
{{hc|# cat /proc/sys/fs/binfmt_misc/qemu-aarch64|<br />
enabled<br />
interpreter /usr/bin/qemu-aarch64-static<br />
flags: POCF<br />
offset 0<br />
magic 7f454c460201010000000000000000000200b700<br />
mask ffffffffffffff00fffffffffffffffffeffffff<br />
}}<br />
<br />
See the "flags" section of the [https://docs.kernel.org/admin-guide/binfmt-misc.html kernel binfmt documentation] for more information.<br />
<br />
=== Not grabbing mouse input ===<br />
<br />
{{Style|It is not explained what the option actually does. Is it causing or avoiding the side effect?}}<br />
<br />
Tablet mode has side effect of not grabbing mouse input in QEMU window:<br />
<br />
-usb -device usb-tablet<br />
<br />
It works with several {{ic|-vga}} backends one of which is virtio.<br />
<br />
== Troubleshooting ==<br />
<br />
{{Merge|QEMU/Troubleshooting|This section is long enough to be split into a dedicated subpage.}}<br />
<br />
=== Mouse cursor is jittery or erratic ===<br />
<br />
If the cursor jumps around the screen uncontrollably, entering this on the terminal before starting QEMU might help:<br />
<br />
$ export SDL_VIDEO_X11_DGAMOUSE=0<br />
<br />
If this helps, you can add this to your {{ic|~/.bashrc}} file.<br />
<br />
=== No visible Cursor ===<br />
<br />
Add {{ic|1=-display default,show-cursor=on}} to QEMU's options to see a mouse cursor.<br />
<br />
If that still does not work, make sure you have set your display device appropriately, for example: {{ic|-vga qxl}}.<br />
<br />
Another option to try is {{ic|-usb -device usb-tablet}} as mentioned in [[#Mouse integration]]. This overrides the default PS/2 mouse emulation and synchronizes pointer location between host and guest as an added bonus.<br />
<br />
=== Two different mouse cursors are visible ===<br />
<br />
Apply the tip [[#Mouse integration]].<br />
<br />
=== Keyboard issues when using VNC ===<br />
<br />
When using VNC, you might experience keyboard problems described (in gory details) [https://www.berrange.com/posts/2010/07/04/more-than-you-or-i-ever-wanted-to-know-about-virtual-keyboard-handling/ here]. The solution is ''not'' to use the {{ic|-k}} option on QEMU, and to use {{ic|gvncviewer}} from {{Pkg|gtk-vnc}}. See also [https://www.mail-archive.com/libvir-list@redhat.com/msg13340.html this] message posted on libvirt's mailing list.<br />
<br />
=== Keyboard seems broken or the arrow keys do not work ===<br />
<br />
Should you find that some of your keys do not work or "press" the wrong key (in particular, the arrow keys), you likely need to specify your keyboard layout as an option. The keyboard layouts can be found in {{ic|/usr/share/qemu/keymaps/}}.<br />
<br />
$ qemu-system-x86_64 -k ''keymap'' ''disk_image''<br />
<br />
=== Could not read keymap file ===<br />
<br />
qemu-system-x86_64: -display vnc=0.0.0.0:0: could not read keymap file: 'en'<br />
<br />
is caused by an invalid ''keymap'' passed to the {{ic|-k}} argument. For example, {{ic|en}} is invalid, but {{ic|en-us}} is valid - see {{ic|/usr/share/qemu/keymaps/}}.<br />
<br />
=== Guest display stretches on window resize ===<br />
<br />
To restore default window size, press {{ic|Ctrl+Alt+u}}.<br />
<br />
=== ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy ===<br />
<br />
If an error message like this is printed when starting QEMU with {{ic|-enable-kvm}} option:<br />
<br />
ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy<br />
failed to initialize KVM: Device or resource busy<br />
<br />
that means another [[hypervisor]] is currently running. It is not recommended or possible to run several hypervisors in parallel.<br />
<br />
=== libgfapi error message ===<br />
<br />
The error message displayed at startup:<br />
<br />
Failed to open module: libgfapi.so.0: cannot open shared object file: No such file or directory<br />
<br />
[[Install]] {{Pkg|glusterfs}} or ignore the error message as GlusterFS is a optional dependency.<br />
<br />
=== Kernel panic on LIVE-environments ===<br />
<br />
If you start a live-environment (or better: booting a system) you may encounter this:<br />
<br />
[ end Kernel panic - not syncing: VFS: Unable to mount root fs on unknown block(0,0)<br />
<br />
or some other boot hindering process (e.g. cannot unpack initramfs, cant start service foo).<br />
Try starting the virtual machine with the {{ic|-m VALUE}} switch and an appropriate amount of RAM, if the ram is to low you will probably encounter similar issues as above/without the memory-switch.<br />
<br />
=== Windows 7 guest suffers low-quality sound ===<br />
<br />
Using the {{ic|hda}} audio driver for Windows 7 guest may result in low-quality sound. Changing the audio driver to {{ic|ac97}} by passing the {{ic|-soundhw ac97}} arguments to QEMU and installing the AC97 driver from [https://www.realtek.com/en/component/zoo/category/pc-audio-codecs-ac-97-audio-codecs-software Realtek AC'97 Audio Codecs] in the guest may solve the problem. See [https://bugzilla.redhat.com/show_bug.cgi?id=1176761#c16 Red Hat Bugzilla – Bug 1176761] for more information.<br />
<br />
=== Could not access KVM kernel module: Permission denied ===<br />
<br />
If you encounter the following error:<br />
<br />
libvirtError: internal error: process exited while connecting to monitor: Could not access KVM kernel module: Permission denied failed to initialize KVM: Permission denied<br />
<br />
Systemd 234 assigns a dynamic ID for the {{ic|kvm}} group (see {{Bug|54943}}). To avoid this error, you need edit the file {{ic|/etc/libvirt/qemu.conf}} and change the line with {{ic|1=group = "78"}} to {{ic|1=group = "kvm"}}.<br />
<br />
=== "System Thread Exception Not Handled" when booting a Windows virtual machine ===<br />
<br />
Windows 8 or Windows 10 guests may raise a generic compatibility exception at boot, namely "System Thread Exception Not Handled", which tends to be caused by legacy drivers acting strangely on real machines. On KVM machines this issue can generally be solved by setting the CPU model to {{ic|core2duo}}.<br />
<br />
=== Certain Windows games/applications crashing/causing a bluescreen ===<br />
<br />
Occasionally, applications running in the virtual machine may crash unexpectedly, whereas they would run normally on a physical machine. If, while running {{ic|dmesg -wH}} as root, you encounter an error mentioning {{ic|MSR}}, the reason for those crashes is that KVM injects a [[wikipedia:General protection fault|General protection fault]] (GPF) when the guest tries to access unsupported [[wikipedia:Model-specific register|Model-specific registers]] (MSRs) - this often results in guest applications/OS crashing. A number of those issues can be solved by passing the {{ic|1=ignore_msrs=1}} option to the KVM module, which will ignore unimplemented MSRs.<br />
<br />
{{hc|/etc/modprobe.d/kvm.conf|2=<br />
...<br />
options kvm ignore_msrs=1<br />
...<br />
}}<br />
<br />
Cases where adding this option might help:<br />
<br />
* GeForce Experience complaining about an unsupported CPU being present.<br />
* StarCraft 2 and L.A. Noire reliably blue-screening Windows 10 with {{ic|KMODE_EXCEPTION_NOT_HANDLED}}. The blue screen information does not identify a driver file in these cases.<br />
<br />
{{Warning|While this is normally safe and some applications might not work without this, silently ignoring unknown MSR accesses could potentially break other software within the virtual machine or other virtual machine.}}<br />
<br />
=== Applications in the virtual machine experience long delays or take a long time to start ===<br />
<br />
{{Out of date|No longer true since kernel 5.6}}<br />
<br />
This may be caused by insufficient available entropy in the virtual machine. Consider allowing the guest to access the hosts's entropy pool by adding a [https://wiki.qemu.org/Features/VirtIORNG VirtIO RNG device] to the virtual machine, or by installing an entropy generating daemon such as [[Haveged]].<br />
<br />
Anecdotally, OpenSSH takes a while to start accepting connections under insufficient entropy, without the logs revealing why.<br />
<br />
=== High interrupt latency and microstuttering ===<br />
<br />
This problem manifests itself as small pauses (stutters) and is particularly noticeable in graphics-intensive applications, such as games.<br />
<br />
* One of the causes is CPU power saving features, which are controlled by [[CPU frequency scaling]]. Change this to {{ic|performance}} for all processor cores. <br />
* Another possible cause is PS/2 inputs. Switch from PS/2 to Virtio inputs, see [[PCI passthrough via OVMF#Passing keyboard/mouse via Evdev]].<br />
<br />
=== QXL video causes low resolution ===<br />
<br />
QEMU 4.1.0 introduced a regression where QXL video can fall back to low resolutions, when being displayed through spice. [https://bugs.launchpad.net/qemu/+bug/1843151] For example, when KMS starts, text resolution may become as low as 4x10 characters. When trying to increase GUI resolution, it may go to the lowest supported resolution.<br />
<br />
As a workaround, create your device in this form:<br />
<br />
-device qxl-vga,max_outputs=1...<br />
<br />
=== Virtual machine not booting when using a Secure Boot enabled OVMF ===<br />
<br />
{{ic|OVMF_CODE.secboot.4m.fd}} and {{ic|OVMF_CODE.secboot.fd}} files from {{Pkg|edk2-ovmf}} are built with [[Wikipedia:System Management Mode|SMM]] support. If S3 support is not disabled in the virtual machine, then the virtual machine might not boot at all.<br />
<br />
Add the {{ic|1=-global ICH9-LPC.disable_s3=1}} option to the ''qemu'' command.<br />
<br />
See {{Bug|59465}} and https://github.com/tianocore/edk2/blob/master/OvmfPkg/README for more details and the required options to use Secure Boot in QEMU.<br />
<br />
=== Virtual machine not booting into Arch ISO ===<br />
<br />
When trying to boot the virtual machine for the first time from an Arch ISO image, the boot process hangs. Adding {{ic|1=console=ttyS0}} to kernel boot options by pressing {{ic|e}} in the boot menu you will get more boot messages and the following error:<br />
<br />
:: Mounting '/dev/disk/by-label/ARCH_202204' to '/run/archiso/bootmnt'<br />
Waiting 30 seconds for device /dev/disk/by-label/ARCH_202204 ...<br />
ERROR: '/dev/disk/by-label/ARCH_202204' device did not show up after 30 seconds...<br />
Falling back to interactive prompt<br />
You can try to fix the problem manually, log out when you are finished<br />
sh: can't access tty; job control turned off<br />
<br />
The error message does not give a good clue as to what the real issue is. The problem is with the default 128MB of RAM that QEMU allocates to the virtual machine. Increasing the limit to 1024MB with {{ic|-m 1024}} solves the issue and lets the system boot. You can continue installing Arch Linux as usual after that. Once the installation is complete, the memory allocation for the virtual machine can be decreased. The need for 1024MB is due to RAM disk requirements and size of the installation media. See [https://lists.archlinux.org/archives/list/arch-releng@lists.archlinux.org/message/D5HSGOFTPGYI6IZUEB3ZNAX4D3F3ID37/ this message on the arch-releng mailing list] and [https://bbs.archlinux.org/viewtopic.php?id=204023 this forum thread].<br />
<br />
=== Guest CPU interrupts are not firing ===<br />
<br />
If you are writing your own operating system by following the [https://wiki.osdev.org/ OSDev wiki], or are simply getting stepping through the guest architecture assembly code using QEMU's {{ic|gdb}} interface using the {{ic|-s}} flag, it is useful to know that many emulators, QEMU included, usually implement some CPU interrupts leaving many hardware interrupts unimplemented. One way to know if your code is firing an interrupt, is by using:<br />
<br />
-d int<br />
<br />
to enable showing interrupts/exceptions on stdout.<br />
<br />
To see what other guest debugging features QEMU has to offer, see:<br />
<br />
qemu-system-x86_64 -d help<br />
<br />
or replace {{ic|x86_64}} for your chosen guest architecture.<br />
<br />
=== KDE with sddm does not start spice-vdagent at login automatically ===<br />
<br />
Remove or comment out {{ic|X-GNOME-Autostart-Phase{{=}}WindowManager}} from {{ic|/etc/xdg/autostart/spice-vdagent.desktop}}. [https://github.com/systemd/systemd/issues/18791]<br />
<br />
=== Error starting domain: Requested operation is not valid: network 'default' is not active ===<br />
<br />
If for any reason the default network is deactivated, you will not be able to start any guest virtual machines which are configured to use the network. Your first attempt can be simply trying to start the network with virsh.<br />
<br />
# virsh net-start default<br />
<br />
For additional troubleshooting steps, see [https://www.xmodulo.com/network-default-is-not-active.html].<br />
<br />
== See also ==<br />
<br />
* [https://qemu.org Official QEMU website]<br />
* [https://www.linux-kvm.org Official KVM website]<br />
* [https://qemu.weilnetz.de/doc/6.0/ QEMU Emulator User Documentation]<br />
* [[Wikibooks:QEMU|QEMU Wikibook]]<br />
* [http://alien.slackbook.org/dokuwiki/doku.php?id=slackware:qemu Hardware virtualization with QEMU] by AlienBOB (last updated in 2008)<br />
* [http://blog.falconindy.com/articles/build-a-virtual-army.html Building a Virtual Army] by Falconindy<br />
* [https://git.qemu.org/?p=qemu.git;a=tree;f=docs Lastest docs]<br />
* [https://qemu.weilnetz.de/ QEMU on Windows]<br />
* [[wikipedia:Qemu|Wikipedia]]<br />
* [[debian:QEMU|Debian Wiki - QEMU]]<br />
* [https://people.gnome.org/~markmc/qemu-networking.html QEMU Networking on gnome.org]{{Dead link|2022|09|22|status=404}}<br />
* [http://bsdwiki.reedmedia.net/wiki/networking_qemu_virtual_bsd_systems.html Networking QEMU Virtual BSD Systems]<br />
* [https://www.gnu.org/software/hurd/hurd/running/qemu.html QEMU on gnu.org]<br />
* [https://wiki.freebsd.org/qemu QEMU on FreeBSD as host]<br />
* [https://wiki.mikejung.biz/KVM_/_Xen KVM/QEMU Virtio Tuning and SSD VM Optimization Guide]{{Dead link|2022|09|22|status=404}}<br />
* [https://doc.opensuse.org/documentation/leap/virtualization/html/book-virt/part-virt-qemu.html Managing Virtual Machines with QEMU - openSUSE documentation]<br />
* [https://www.ibm.com/support/knowledgecenter/en/linuxonibm/liaat/liaatkvm.htm KVM on IBM Knowledge Center]</div>Malcontenthttps://wiki.archlinux.org/index.php?title=QEMU&diff=795996QEMU2024-01-04T08:55:49Z<p>Malcontent: Make it more consistent with other examples</p>
<hr />
<div>[[Category:Emulation]]<br />
[[Category:Hypervisors]]<br />
[[de:QEMU]]<br />
[[es:QEMU]]<br />
[[fr:QEMU]]<br />
[[ja:QEMU]]<br />
[[zh-hans:QEMU]]<br />
{{Related articles start}}<br />
{{Related|:Category:Hypervisors}}<br />
{{Related|Libvirt}}<br />
{{Related|QEMU/Guest graphics acceleration}}<br />
{{Related|PCI passthrough via OVMF}}<br />
{{Related articles end}}<br />
<br />
According to the [https://wiki.qemu.org/Main_Page QEMU about page], "QEMU is a generic and open source machine emulator and virtualizer."<br />
<br />
When used as a machine emulator, QEMU can run OSes and programs made for one machine (e.g. an ARM board) on a different machine (e.g. your x86 PC). By using dynamic translation, it achieves very good performance.<br />
<br />
QEMU can use other hypervisors like [[Xen]] or [[KVM]] to use CPU extensions ([[Wikipedia:Hardware-assisted virtualization|HVM]]) for virtualization. When used as a virtualizer, QEMU achieves near native performances by executing the guest code directly on the host CPU.<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|qemu-full}} package (or {{Pkg|qemu-base}} for the version without GUI) and below optional packages for your needs:<br />
<br />
* {{Pkg|qemu-block-gluster}} - [[Glusterfs]] block support<br />
* {{Pkg|qemu-block-iscsi}} - [[iSCSI]] block support<br />
* {{Pkg|samba}} - [[Samba|SMB/CIFS]] server support<br />
<br />
Alternatively, {{Pkg|qemu-user-static}} exists as a usermode and static variant.<br />
<br />
=== QEMU variants ===<br />
<br />
QEMU is offered in several variants suited for different use cases.<br />
<br />
As a first classification, QEMU is offered in full-system and usermode emulation modes:<br />
<br />
; Full-system emulation<br />
: In this mode, QEMU emulates a full system, including one or several processors and various peripherals. It is more accurate but slower, and does not require the emulated OS to be Linux.<br />
: QEMU commands for full-system emulation are named {{ic|qemu-system-''target_architecture''}}, e.g. {{ic|qemu-system-x86_64}} for emulating [[Wikipedia:x86_64|x86_64]] CPUs, {{ic|qemu-system-i386}} for Intel [[Wikipedia:i386|32-bit x86]] CPUs, {{ic|qemu-system-arm}} for [[Wikipedia:ARM architecture family#32-bit architecture|ARM (32 bits)]], {{ic|qemu-system-aarch64}} for [[Wikipedia:AArch64|ARM64]], etc.<br />
: If the target architecture matches the host CPU, this mode may still benefit from a significant speedup by using a hypervisor like [[#Enabling KVM|KVM]] or Xen.<br />
; [https://www.qemu.org/docs/master/user/main.html Usermode emulation]<br />
: In this mode, QEMU is able to invoke a Linux executable compiled for a (potentially) different architecture by leveraging the host system resources. There may be compatibility issues, e.g. some features may not be implemented, dynamically linked executables will not work out of the box (see [[#Chrooting into arm/arm64 environment from x86_64]] to address this) and only Linux is supported (although [https://wiki.winehq.org/Emulation Wine may be used] for running Windows executables).<br />
: QEMU commands for usermode emulation are named {{ic|qemu-''target_architecture''}}, e.g. {{ic|qemu-x86_64}} for emulating 64-bit CPUs.<br />
<br />
QEMU is offered in dynamically-linked and statically-linked variants:<br />
<br />
; Dynamically-linked (default): {{ic|qemu-*}} commands depend on the host OS libraries, so executables are smaller.<br />
; Statically-linked: {{ic|qemu-*}} commands can be copied to any Linux system with the same architecture.<br />
<br />
In the case of Arch Linux, full-system emulation is offered as:<br />
<br />
; Non-headless (default): This variant enables GUI features that require additional dependencies (like SDL or GTK).<br />
; Headless: This is a slimmer variant that does not require GUI (this is suitable e.g. for servers).<br />
<br />
Note that headless and non-headless versions install commands with the same name (e.g. {{ic|qemu-system-x86_64}}) and thus cannot be both installed at the same time.<br />
<br />
=== Details on packages available in Arch Linux ===<br />
<br />
* The {{Pkg|qemu-desktop}} package provides the {{ic|x86_64}} architecture emulators for full-system emulation ({{ic|qemu-system-x86_64}}). The {{Pkg|qemu-emulators-full}} package provides the {{ic|x86_64}} usermode variant ({{ic|qemu-x86_64}}) and also for the rest of supported architectures it includes both full-system and usermode variants (e.g. {{ic|qemu-system-arm}} and {{ic|qemu-arm}}).<br />
* The headless versions of these packages (only applicable to full-system emulation) are {{Pkg|qemu-base}} ({{ic|x86_64}}-only) and {{Pkg|qemu-emulators-full}} (rest of architectures).<br />
* Full-system emulation can be expanded with some QEMU modules present in separate packages: {{Pkg|qemu-block-gluster}}, {{Pkg|qemu-block-iscsi}} and {{Pkg|qemu-guest-agent}}.<br />
* {{Pkg|qemu-user-static}} provides a usermode and static variant for all target architectures supported by QEMU. The installed QEMU commands are named {{ic|qemu-''target_architecture''-static}}, for example, {{ic|qemu-x86_64-static}} for intel 64-bit CPUs.<br />
<br />
{{Note|At present, Arch does not offer a full-system mode and statically linked variant (neither officially nor via AUR), as this is usually not needed.}}<br />
<br />
=== Custom build ===<br />
<br />
{{Remove|Explaining how to use the [[Arch build system]] is out of scope here. There is no motivation for the customization in the first place.}}<br />
<br />
To obtain a customized version of QEMU, [[Git#Getting a Git repository|clone]] the package source of {{Pkg|qemu-common}} or {{AUR|qemu-git}}.<br />
<br />
The respective [[PKGBUILD]] file calls QEMU's [https://www.gnu.org/prep/standards/html_node/Configuration.html configure script] which accepts parameters obtainable by first manually running --help on it. <br />
To access this help beforehand, you may [[Makepkg#Usage|use makepkg]] to let it download and extract the QEMU source, canceling the build process as soon as the configure script begins.<br />
<br />
With the PKGBUILD file's configure script calls modified as desired, you may [[Makepkg#Usage|use makepkg]] (again) to let it build the packages, though it is inadvisable to let it install them as conflicting headless / static packages will be built as well and a typical user certainly won't need the additional system emulators for the other architectures.<br />
<br />
When the build process completes, it is advisable to instead copy your desired packages (see the [[#Removal|list for qemu-desktop in "Removal"]]{{Broken section link}}) to a different directory, [[Pacman#Additional commands|let pacman install them all]] and add them to the [[Pacman#Skip package from being upgraded|IgnorePkg]] list so you get to upgrade them manually.<br />
<br />
== Graphical front-ends for QEMU ==<br />
<br />
Unlike other virtualization programs such as [[VirtualBox]] and [[VMware]], QEMU does not provide a GUI to manage virtual machines (other than the window that appears when running a virtual machine), nor does it provide a way to create persistent virtual machines with saved settings. All parameters to run a virtual machine must be specified on the command line at every launch, unless you have created a custom script to start your virtual machine(s).<br />
<br />
[[Libvirt]] provides a convenient way to manage QEMU virtual machines. See [[Libvirt#Client|list of libvirt clients]] for available front-ends.<br />
<br />
== Creating new virtualized system ==<br />
<br />
=== Creating a hard disk image ===<br />
<br />
{{Accuracy|If I get the man page right the raw format only allocates the full size if the filesystem does not support "holes" or it is <br />
explicitly told to preallocate. See {{man|1|qemu-img|NOTES}}.}} <br />
<br />
{{Tip|See [[Wikibooks:QEMU/Images]] for more information on QEMU images.}}<br />
<br />
To run QEMU you will need a hard disk image, unless you are booting a live system from CD-ROM or the network (and not doing so to install an operating system to a hard disk image). A hard disk image is a file which stores the contents of the emulated hard disk.<br />
<br />
A hard disk image can be ''raw'', so that it is literally byte-by-byte the same as what the guest sees, and will always use the full capacity of the guest hard drive on the host. This method provides the least I/O overhead, but can waste a lot of space, as not-used space on the guest cannot be used on the host.<br />
<br />
Alternatively, the hard disk image can be in a format such as ''qcow2'' which only allocates space to the image file when the guest operating system actually writes to those sectors on its virtual hard disk. The image appears as the full size to the guest operating system, even though it may take up only a very small amount of space on the host system. This image format also supports QEMU snapshotting functionality (see [[#Creating and managing snapshots via the monitor console]] for details). However, using this format instead of ''raw'' will likely affect performance.<br />
<br />
QEMU provides the {{ic|qemu-img}} command to create hard disk images. For example to create a 4 GiB image in the ''raw'' format:<br />
<br />
$ qemu-img create -f raw ''image_file'' 4G<br />
<br />
You may use {{ic|-f qcow2}} to create a ''qcow2'' disk instead.<br />
<br />
{{Note|You can also simply create a ''raw'' image by creating a file of the needed size using {{ic|dd}} or {{ic|fallocate}}.}}<br />
<br />
{{Warning|If you store the hard disk images on a [[Btrfs]] file system, you should consider disabling [[Btrfs#Copy-on-Write (CoW)|Copy-on-Write]] for the directory before creating any images.}}<br />
<br />
==== Overlay storage images ====<br />
<br />
You can create a storage image once (the 'backing' image) and have QEMU keep mutations to this image in an overlay image. This allows you to revert to a previous state of this storage image. You could revert by creating a new overlay image at the time you wish to revert, based on the original backing image.<br />
<br />
To create an overlay image, issue a command like:<br />
<br />
$ qemu-img create -o backing_file=''img1.raw'',backing_fmt=''raw'' -f ''qcow2'' ''img1.cow''<br />
<br />
After that you can run your QEMU virtual machine as usual (see [[#Running virtualized system]]):<br />
<br />
$ qemu-system-x86_64 ''img1.cow''<br />
<br />
The backing image will then be left intact and mutations to this storage will be recorded in the overlay image file.<br />
<br />
When the path to the backing image changes, repair is required.<br />
<br />
{{Warning|The backing image's absolute filesystem path is stored in the (binary) overlay image file. Changing the backing image's path requires some effort.}}<br />
<br />
Make sure that the original backing image's path still leads to this image. If necessary, make a symbolic link at the original path to the new path. Then issue a command like:<br />
<br />
$ qemu-img rebase -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
At your discretion, you may alternatively perform an 'unsafe' rebase where the old path to the backing image is not checked:<br />
<br />
$ qemu-img rebase -u -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
==== Resizing an image ====<br />
<br />
{{Warning|Resizing an image containing an NTFS boot file system could make the operating system installed on it unbootable. It is recommended to create a backup first.}}<br />
<br />
The {{ic|qemu-img}} executable has the {{ic|resize}} option, which enables easy resizing of a hard drive image. It works for both ''raw'' and ''qcow2''. For example, to increase image space by 10 GiB, run:<br />
<br />
$ qemu-img resize ''disk_image'' +10G<br />
<br />
After enlarging the disk image, you must use file system and partitioning tools inside the virtual machine to actually begin using the new space. <br />
<br />
===== Shrinking an image =====<br />
<br />
When shrinking a disk image, you must first reduce the allocated file systems and partition sizes using the file system and partitioning tools inside the virtual machine and then shrink the disk image accordingly. For a Windows guest, this can be performed from the "create and format hard disk partitions" control panel.<br />
<br />
{{Warning|Proceeding to shrink the disk image without reducing the guest partition sizes will result in data loss.}}<br />
<br />
Then, to decrease image space by 10 GiB, run:<br />
<br />
$ qemu-img resize --shrink ''disk_image'' -10G<br />
<br />
==== Converting an image ====<br />
<br />
You can convert an image to other formats using {{ic|qemu-img convert}}. This example shows how to convert a ''raw'' image to ''qcow2'':<br />
<br />
$ qemu-img convert -f raw -O qcow2 ''input''.img ''output''.qcow2<br />
<br />
This will not remove the original input file.<br />
<br />
=== Preparing the installation media ===<br />
<br />
To install an operating system into your disk image, you need the installation medium (e.g. optical disc, USB-drive, or ISO image) for the operating system. The installation medium should not be mounted because QEMU accesses the media directly.<br />
<br />
{{Tip|If using an optical disc, it is a good idea to first dump the media to a file because this both improves performance and does not require you to have direct access to the devices (that is, you can run QEMU as a regular user without having to change access permissions on the media's device file). For example, if the CD-ROM device node is named {{ic|/dev/cdrom}}, you can dump it to a file with the command: {{bc|1=$ dd if=/dev/cdrom of=''cd_image.iso'' bs=4k}}}}<br />
<br />
=== Installing the operating system ===<br />
<br />
This is the first time you will need to start the emulator. To install the operating system on the disk image, you must attach both the disk image and the installation media to the virtual machine, and have it boot from the installation media.<br />
<br />
For example on i386 guests, to install from a bootable ISO file as CD-ROM and a raw disk image:<br />
<br />
$ qemu-system-x86_64 -cdrom ''iso_image'' -boot order=d -drive file=''disk_image'',format=raw<br />
<br />
See {{man|1|qemu}} for more information about loading other media types (such as floppy, disk images or physical drives) and [[#Running virtualized system]] for other useful options.<br />
<br />
After the operating system has finished installing, the QEMU image can be booted directly (see [[#Running virtualized system]]).<br />
<br />
{{Note|By default only 128 MiB of memory is assigned to the machine. The amount of memory can be adjusted with the {{ic|-m}} switch, for example {{ic|-m 512M}} or {{ic|-m 2G}}.}}<br />
<br />
{{Tip|<br />
* Instead of specifying {{ic|1=-boot order=x}}, some users may feel more comfortable using a boot menu: {{ic|1=-boot menu=on}}, at least during configuration and experimentation.<br />
* When running QEMU in headless mode, it starts a local VNC server on port 5900 per default. You can use [[TigerVNC]] to connect to the guest OS: {{ic|vncviewer :5900}}<br />
* If you need to replace floppies or CDs as part of the installation process, you can use the QEMU machine monitor (press {{ic|Ctrl+Alt+2}} in the virtual machine's window) to remove and attach storage devices to a virtual machine. Type {{ic|info block}} to see the block devices, and use the {{ic|change}} command to swap out a device. Press {{ic|Ctrl+Alt+1}} to go back to the virtual machine.<br />
}}<br />
<br />
== Running virtualized system ==<br />
<br />
{{ic|qemu-system-*}} binaries (for example {{ic|qemu-system-i386}} or {{ic|qemu-system-x86_64}}, depending on guest's architecture) are used to run the virtualized guest. The usage is:<br />
<br />
$ qemu-system-x86_64 ''options'' ''disk_image''<br />
<br />
Options are the same for all {{ic|qemu-system-*}} binaries, see {{man|1|qemu}} for documentation of all options.<br />
<br />
Usually, if an option has many possible values, you can use<br />
<br />
$ qemu-system-x86_64 ''option'' ''help''<br />
<br />
to list all possible values. If it supports properties, you can use<br />
<br />
$ qemu-system-x86_64 ''option'' ''value,help''<br />
<br />
to list all available properties.<br />
<br />
For example:<br />
$ qemu-system-x86_64 -machine help<br />
$ qemu-system-x86_64 -machine q35,help<br />
$ qemu-system-x86_64 -device help<br />
$ qemu-system-x86_64 -device qxl,help<br />
<br />
You can use these methods and the {{man|1|qemu}} documentation to understand the options used in follow sections.<br />
<br />
By default, QEMU will show the virtual machine's video output in a window. One thing to keep in mind: when you click inside the QEMU window, the mouse pointer is grabbed. To release it, press {{ic|Ctrl+Alt+g}}.<br />
<br />
{{Warning|QEMU should never be run as root. If you must launch it in a script as root, you should use the {{ic|-runas}} option to make QEMU drop root privileges.}}<br />
<br />
=== Enabling KVM ===<br />
<br />
KVM (''Kernel-based Virtual Machine'') full virtualization must be supported by your Linux kernel and your hardware, and necessary [[kernel modules]] must be loaded. See [[KVM]] for more information.<br />
<br />
To start QEMU in KVM mode, append {{ic|-accel kvm}} to the additional start options. To check if KVM is enabled for a running virtual machine, enter the [[#QEMU monitor]] and type {{ic|info kvm}}.<br />
<br />
{{Note|<br />
* The argument {{ic|1=accel=kvm}} of the {{ic|-machine}} option is equivalent to the {{ic|-enable-kvm}} or the {{ic|-accel kvm}} option.<br />
* CPU model {{ic|host}} requires KVM.<br />
* If you start your virtual machine with a GUI tool and experience very bad performance, you should check for proper KVM support, as QEMU may be falling back to software emulation.<br />
* KVM needs to be enabled in order to start Windows 7 or Windows 8 properly without a ''blue screen''.<br />
}}<br />
<br />
=== Enabling IOMMU (Intel VT-d/AMD-Vi) support ===<br />
<br />
First enable IOMMU, see [[PCI passthrough via OVMF#Setting up IOMMU]].<br />
<br />
Add {{ic|-device intel-iommu}} to create the IOMMU device:<br />
<br />
$ qemu-system-x86_64 '''-enable-kvm -machine q35 -device intel-iommu''' -cpu host ..<br />
<br />
{{Note|<br />
On Intel CPU based systems creating an IOMMU device in a QEMU guest with {{ic|-device intel-iommu}} will disable PCI passthrough with an error like: {{bc|Device at bus pcie.0 addr 09.0 requires iommu notifier which is currently not supported by intel-iommu emulation}} While adding the kernel parameter {{ic|1=intel_iommu=on}} is still needed for remapping IO (e.g. [[PCI passthrough via OVMF#Isolating the GPU|PCI passthrough with vfio-pci]]), {{ic|-device intel-iommu}} should not be set if PCI passthrough is required.<br />
}}<br />
<br />
=== Booting in UEFI mode ===<br />
<br />
The default firmware used by QEMU is [https://www.coreboot.org/SeaBIOS SeaBIOS], which is a Legacy BIOS implementation. QEMU uses {{ic|/usr/share/qemu/bios-256k.bin}} (provided by the {{Pkg|seabios}} package) as a default read-only (ROM) image. You can use the {{ic|-bios}} argument to select another firmware file. However, UEFI requires writable memory to work properly, so you need to emulate [https://wiki.qemu.org/Features/PC_System_Flash PC System Flash] instead.<br />
<br />
[https://github.com/tianocore/tianocore.github.io/wiki/OVMF OVMF] is a TianoCore project to enable UEFI support for Virtual Machines. It can be [[install]]ed with the {{Pkg|edk2-ovmf}} package.<br />
<br />
There are two ways to use OVMF as a firmware. The first is to copy {{ic|/usr/share/edk2/x64/OVMF.4m.fd}}, make it writable and use as a pflash drive:<br />
<br />
-drive if=pflash,format=raw,file=''/copy/of/OVMF.4m.fd''<br />
<br />
All changes to the UEFI settings will be saved directly to this file.<br />
<br />
Another and more preferable way is to split OVMF into two files. The first one will be read-only and store the firmware executable, and the second one will be used as a writable variable store. The advantage is that you can use the firmware file directly without copying, so it will be updated automatically by [[pacman]].<br />
<br />
Use {{ic|/usr/share/edk2/x64/OVMF_CODE.4m.fd}} as a first read-only pflash drive. Copy {{ic|/usr/share/edk2/x64/OVMF_VARS.4m.fd}}, make it writable and use as a second writable pflash drive:<br />
<br />
-drive if=pflash,format=raw,readonly=on,file=/usr/share/edk2/x64/OVMF_CODE.4m.fd \<br />
-drive if=pflash,format=raw,file=''/copy/of/OVMF_VARS.4m.fd''<br />
<br />
If secure boot is wanted, replace {{ic|/usr/share/edk2/x64/OVMF_CODE.4m.fd}} with {{ic|/usr/share/edk2/x64/OVMF_CODE.secboot.4m.fd}}.<br />
<br />
=== Trusted Platform Module emulation ===<br />
<br />
QEMU can emulate [[Trusted Platform Module]], which is required by some systems such as Windows 11 (which requires TPM 2.0).<br />
<br />
[[Install]] the {{Pkg|swtpm}} package, which provides a software TPM implementation. Create some directory for storing TPM data ({{ic|''/path/to/mytpm''}} will be used as an example). Run this command to start the emulator:<br />
<br />
$ swtpm socket --tpm2 --tpmstate dir=''/path/to/mytpm'' --ctrl type=unixio,path=''/path/to/mytpm/swtpm-sock''<br />
<br />
{{ic|''/path/to/mytpm/swtpm-sock''}} will be created by ''swtpm'': this is a UNIX socket to which QEMU will connect. You can put it in any directory.<br />
<br />
By default, ''swtpm'' starts a TPM version 1.2 emulator. The {{ic|--tpm2}} option enables TPM 2.0 emulation.<br />
<br />
Finally, add the following options to QEMU:<br />
<br />
-chardev socket,id=chrtpm,path=''/path/to/mytpm/swtpm-sock'' \<br />
-tpmdev emulator,id=tpm0,chardev=chrtpm \<br />
-device tpm-tis,tpmdev=tpm0<br />
<br />
and TPM will be available inside the virtual machine. After shutting down the virtual machine, ''swtpm'' will be automatically terminated.<br />
<br />
See [https://qemu-project.gitlab.io/qemu/specs/tpm.html the QEMU documentation] for more information. <br />
<br />
If guest OS still doesn't recognize the TPM device, try to adjust ''CPU Models and Topology'' options. It might cause problem.<br />
<br />
== Sharing data between host and guest ==<br />
<br />
=== Network ===<br />
<br />
Data can be shared between the host and guest OS using any network protocol that can transfer files, such as [[NFS]], [[SMB]], [[Wikipedia:Network block device|NBD]], HTTP, [[Very Secure FTP Daemon|FTP]], or [[SSH]], provided that you have set up the network appropriately and enabled the appropriate services.<br />
<br />
The default user-mode networking allows the guest to access the host OS at the IP address 10.0.2.2. Any servers that you are running on your host OS, such as a SSH server or SMB server, will be accessible at this IP address. So on the guests, you can mount directories exported on the host via [[SMB]] or [[NFS]], or you can access the host's HTTP server, etc.<br />
It will not be possible for the host OS to access servers running on the guest OS, but this can be done with other network configurations (see [[#Tap networking with QEMU]]).<br />
<br />
=== QEMU's port forwarding ===<br />
<br />
{{Note|QEMU's port forwarding is IPv4-only. IPv6 port forwarding is not implemented and the last patches were proposed in 2018.[https://lore.kernel.org/qemu-devel/1540512223-21199-1-git-send-email-max7255@yandex-team.ru/T/#u]}}<br />
<br />
QEMU can forward ports from the host to the guest to enable e.g. connecting from the host to an SSH server running on the guest.<br />
<br />
For example, to bind port 60022 on the host with port 22 (SSH) on the guest, start QEMU with a command like:<br />
<br />
$ qemu-system-x86_64 ''disk_image'' -nic user,hostfwd=tcp::60022-:22<br />
<br />
Make sure the sshd is running on the guest and connect with:<br />
<br />
$ ssh ''guest-user''@127.0.0.1 -p 60022<br />
<br />
You can use [[SSHFS]] to mount the guest's file system at the host for shared read and write access.<br />
<br />
To forward several ports, you just repeat the {{ic|hostfwd}} in the {{ic|-nic}} argument, e.g. for VNC's port:<br />
<br />
$ qemu-system-x86_64 ''disk_image'' -nic user,hostfwd=tcp::60022-:22,hostfwd=tcp::5900-:5900<br />
<br />
=== QEMU's built-in SMB server ===<br />
<br />
QEMU's documentation says it has a "built-in" SMB server, but actually it just starts up [[Samba]] on the host with an automatically generated {{ic|smb.conf}} file located in {{ic|/tmp/qemu-smb.''random_string''}} and makes it accessible to the guest at a different IP address (10.0.2.4 by default). This only works for user networking, and is useful when you do not want to start the normal [[Samba]] service on the host, which the guest can also access if you have set up shares on it.<br />
<br />
Only a single directory can be set as shared with the option {{ic|1=smb=}}, but adding more directories (even while the virtual machine is running) could be as easy as creating symbolic links in the shared directory if QEMU configured SMB to follow symbolic links. It does not do so, but the configuration of the running SMB server can be changed as described below.<br />
<br />
''Samba'' must be installed on the host. To enable this feature, start QEMU with a command like:<br />
<br />
$ qemu-system-x86_64 -nic user,id=nic0,smb=''shared_dir_path'' ''disk_image''<br />
<br />
where {{ic|''shared_dir_path''}} is a directory that you want to share between the guest and host.<br />
<br />
Then, in the guest, you will be able to access the shared directory on the host 10.0.2.4 with the share name "qemu". For example, in Windows Explorer you would go to {{ic|\\10.0.2.4\qemu}}.<br />
<br />
{{Note|<br />
* If you are using sharing options multiple times like {{ic|1=-net user,smb=''shared_dir_path1'' -net user,smb=''shared_dir_path2''}} or {{ic|1=-net user,smb=''shared_dir_path1'',smb=''shared_dir_path2''}} then it will share only the last defined one.<br />
* If you cannot access the shared folder and the guest system is Windows, check that the [http://ecross.mvps.org/howto/enable-netbios-over-tcp-ip-with-windows.htm NetBIOS protocol is enabled]{{Dead link|2023|05|06|status=domain name not resolved}} and that a firewall does not block [https://technet.microsoft.com/en-us/library/cc940063.aspx ports] used by the NetBIOS protocol.<br />
* If you cannot access the shared folder and the guest system is Windows 10 Enterprise or Education or Windows Server 2016, [https://support.microsoft.com/en-us/help/4046019 enable guest access].<br />
* If you use [[#Tap networking with QEMU]], use {{ic|1=-device virtio-net,netdev=vmnic -netdev user,id=vmnic,smb=''shared_dir_path''}} to get SMB.<br />
}}<br />
<br />
One way to share multiple directories and to add or remove them while the virtual machine is running, is to share an empty directory and create/remove symbolic links to the directories in the shared directory. For this to work, the configuration of the running SMB server can be changed with the following script, which also allows the execution of files on the guest that are not set executable on the host:<br />
<br />
#!/bin/sh<br />
eval $(ps h -C smbd -o pid,args | grep /tmp/qemu-smb | gawk '{print "pid="$1";conf="$6}')<br />
echo "[global]<br />
allow insecure wide links = yes<br />
[qemu]<br />
follow symlinks = yes<br />
wide links = yes<br />
acl allow execute always = yes" >> "$conf"<br />
# in case the change is not detected automatically:<br />
smbcontrol --configfile="$conf" "$pid" reload-config<br />
<br />
This can be applied to the running server started by qemu only after the guest has connected to the network drive the first time. An alternative to this method is to add additional shares to the configuration file like so:<br />
<br />
echo "[''myshare'']<br />
path=''another_path''<br />
read only=no<br />
guest ok=yes<br />
force user=''username''" >> $conf<br />
<br />
This share will be available on the guest as {{ic|\\10.0.2.4\''myshare''}}.<br />
<br />
=== Using filesystem passthrough and VirtFS ===<br />
<br />
See the [https://wiki.qemu.org/Documentation/9psetup QEMU documentation].<br />
<br />
=== Host file sharing with virtiofsd ===<br />
<br />
{{Style|See [[Help:Style/Formatting and punctuation]].}}<br />
<br />
virtiofsd is shipped with QEMU package. Documentation is available [https://qemu-stsquad.readthedocs.io/en/docs-next/tools/virtiofsd.html online]{{Dead link|2023|05|06|status=404}} or {{ic|/usr/share/doc/qemu/qemu/tools/virtiofsd.html}} on local file system with {{Pkg|qemu-docs}} installed.<br />
<br />
Add user that runs qemu to the 'kvm' [[user group]], because it needs to access the virtiofsd socket. You might have to logout for change to take effect.<br />
<br />
{{Accuracy|Running services as root is not secure. Also the process should be wrapped in a systemd service.}}<br />
<br />
Start as virtiofsd as root:<br />
<br />
# /usr/lib/virtiofsd --socket-path=/var/run/qemu-vm-001.sock --shared-dir /tmp/vm-001 --cache always<br />
<br />
where<br />
<br />
* {{ic|/var/run/qemu-vm-001.sock}} is a socket file,<br />
* {{ic|/tmp/vm-001}} is a shared directory between the host and the guest virtual machine.<br />
<br />
The created socket file has root only access permission. Give group kvm access to it with:<br />
<br />
# chgrp kvm qemu-vm-001.sock; chmod g+rxw qemu-vm-001.sock<br />
<br />
Add the following configuration options when starting the virtual machine:<br />
<br />
-object memory-backend-memfd,id=mem,size=4G,share=on \<br />
-numa node,memdev=mem \<br />
-chardev socket,id=char0,path=/var/run/qemu-vm-001.sock \<br />
-device vhost-user-fs-pci,chardev=char0,tag=myfs<br />
<br />
where<br />
<br />
{{Expansion|Explain the remaining options (or remove them if they are not necessary).}}<br />
<br />
* {{ic|1=size=4G}} shall match size specified with {{ic|-m 4G}} option,<br />
* {{ic|/var/run/qemu-vm-001.sock}} points to socket file started earlier,<br />
<br />
{{Style|The section should not be specific to Windows.}}<br />
<br />
Remember, that guest must be configured to enable sharing. For Windows there are [https://virtio-fs.gitlab.io/howto-windows.html instructions]. Once configured, Windows will have the {{ic|Z:}} drive mapped automatically with shared directory content.<br />
<br />
Your Windows 10 guest system is properly configured if it has:<br />
<br />
* VirtioFSSService windows service,<br />
* WinFsp.Launcher windows service,<br />
* VirtIO FS Device driver under "System devices" in Windows "Device Manager".<br />
<br />
If the above installed and {{ic|Z:}} drive is still not listed, try repairing "Virtio-win-guest-tools" in Windows ''Add/Remove programs''.<br />
<br />
=== Mounting a partition of the guest on the host ===<br />
<br />
It can be useful to mount a drive image under the host system, it can be a way to transfer files in and out of the guest. This should be done when the virtual machine is not running.<br />
<br />
The procedure to mount the drive on the host depends on the type of qemu image, ''raw'' or ''qcow2''. We detail thereafter the steps to mount a drive in the two formats in [[#Mounting a partition from a raw image]] and [[#Mounting a partition from a qcow2 image]]. For the full documentation see [[Wikibooks:QEMU/Images#Mounting an image on the host]].<br />
<br />
{{Warning|You must unmount the partitions before running the virtual machine again. Otherwise, data corruption is very likely to occur.}}<br />
<br />
==== Mounting a partition from a raw image ====<br />
<br />
It is possible to mount partitions that are inside a raw disk image file by setting them up as loopback devices.<br />
<br />
===== With manually specifying byte offset =====<br />
<br />
One way to mount a disk image partition is to mount the disk image at a certain offset using a command like the following:<br />
<br />
# mount -o loop,offset=32256 ''disk_image'' ''mountpoint''<br />
<br />
The {{ic|1=offset=32256}} option is actually passed to the {{ic|losetup}} program to set up a loopback device that starts at byte offset 32256 of the file and continues to the end. This loopback device is then mounted. You may also use the {{ic|sizelimit}} option to specify the exact size of the partition, but this is usually unnecessary.<br />
<br />
Depending on your disk image, the needed partition may not start at offset 32256. Run {{ic|fdisk -l ''disk_image''}} to see the partitions in the image. fdisk gives the start and end offsets in 512-byte sectors, so multiply by 512 to get the correct offset to pass to {{ic|mount}}.<br />
<br />
===== With loop module autodetecting partitions =====<br />
<br />
The Linux loop driver actually supports partitions in loopback devices, but it is disabled by default. To enable it, do the following:<br />
<br />
* Get rid of all your loopback devices (unmount all mounted images, etc.).<br />
* [[Kernel modules#Manual module handling|Unload]] the {{ic|loop}} kernel module, and load it with the {{ic|1=max_part=15}} parameter set. Additionally, the maximum number of loop devices can be controlled with the {{ic|max_loop}} parameter.<br />
<br />
{{Tip|You can put an entry in {{ic|/etc/modprobe.d}} to load the loop module with {{ic|1=max_part=15}} every time, or you can put {{ic|1=loop.max_part=15}} on the kernel command-line, depending on whether you have the {{ic|loop.ko}} module built into your kernel or not.}}<br />
<br />
Set up your image as a loopback device:<br />
<br />
# losetup -f -P ''disk_image''<br />
<br />
Then, if the device created was {{ic|/dev/loop0}}, additional devices {{ic|/dev/loop0p''X''}} will have been automatically created, where X is the number of the partition. These partition loopback devices can be mounted directly. For example:<br />
<br />
# mount /dev/loop0p1 ''mountpoint''<br />
<br />
To mount the disk image with ''udisksctl'', see [[Udisks#Mount loop devices]].<br />
<br />
===== With kpartx =====<br />
<br />
''kpartx'' from the {{Pkg|multipath-tools}} package can read a partition table on a device and create a new device for each partition. For example:<br />
<br />
# kpartx -a ''disk_image''<br />
<br />
This will setup the loopback device and create the necessary partition(s) device(s) in {{ic|/dev/mapper/}}.<br />
<br />
==== Mounting a partition from a qcow2 image ====<br />
<br />
We will use {{ic|qemu-nbd}}, which lets use the NBD (''network block device'') protocol to share the disk image.<br />
<br />
First, we need the ''nbd'' module loaded:<br />
<br />
# modprobe nbd max_part=16<br />
<br />
Then, we can share the disk and create the device entries:<br />
<br />
# qemu-nbd -c /dev/nbd0 ''/path/to/image.qcow2''<br />
<br />
Discover the partitions:<br />
<br />
# partprobe /dev/nbd0<br />
<br />
''fdisk'' can be used to get information regarding the different partitions in {{ic|''nbd0''}}:<br />
<br />
{{hc|# fdisk -l /dev/nbd0|2=<br />
Disk /dev/nbd0: 25.2 GiB, 27074281472 bytes, 52879456 sectors<br />
Units: sectors of 1 * 512 = 512 bytes<br />
Sector size (logical/physical): 512 bytes / 512 bytes<br />
I/O size (minimum/optimal): 512 bytes / 512 bytes<br />
Disklabel type: dos<br />
Disk identifier: 0xa6a4d542<br />
<br />
Device Boot Start End Sectors Size Id Type<br />
/dev/nbd0p1 * 2048 1026047 1024000 500M 7 HPFS/NTFS/exFAT<br />
/dev/nbd0p2 1026048 52877311 51851264 24.7G 7 HPFS/NTFS/exFAT}}<br />
<br />
Then mount any partition of the drive image, for example the partition 2:<br />
<br />
# mount /dev/nbd0'''p2''' ''mountpoint''<br />
<br />
After the usage, it is important to unmount the image and reverse previous steps, i.e. unmount the partition and disconnect the nbd device:<br />
<br />
# umount ''mountpoint''<br />
# qemu-nbd -d /dev/nbd0<br />
<br />
=== Using any real partition as the single primary partition of a hard disk image ===<br />
<br />
Sometimes, you may wish to use one of your system partitions from within QEMU. Using a raw partition for a virtual machine will improve performance, as the read and write operations do not go through the file system layer on the physical host. Such a partition also provides a way to share data between the host and guest.<br />
<br />
In Arch Linux, device files for raw partitions are, by default, owned by ''root'' and the ''disk'' group. If you would like to have a non-root user be able to read and write to a raw partition, you must either change the owner of the partition's device file to that user, add that user to the ''disk'' group, or use [[ACL]] for more fine-grained access control.<br />
<br />
{{Warning|<br />
* Although it is possible, it is not recommended to allow virtual machines to alter critical data on the host system, such as the root partition.<br />
* You must not mount a file system on a partition read-write on both the host and the guest at the same time. Otherwise, data corruption will result.<br />
}}<br />
<br />
After doing so, you can attach the partition to a QEMU virtual machine as a virtual disk.<br />
<br />
However, things are a little more complicated if you want to have the ''entire'' virtual machine contained in a partition. In that case, there would be no disk image file to actually boot the virtual machine since you cannot install a boot loader to a partition that is itself formatted as a file system and not as a partitioned device with an MBR. Such a virtual machine can be booted either by: [[#Specifying kernel and initrd manually]], [[#Simulating a virtual disk with MBR]], [[#Using the device-mapper]], [[#Using a linear RAID]] or [[#Using a Network Block Device]].<br />
<br />
==== Specifying kernel and initrd manually ====<br />
<br />
QEMU supports loading [[Kernels|Linux kernels]] and [[initramfs|init ramdisks]] directly, thereby circumventing boot loaders such as [[GRUB]]. It then can be launched with the physical partition containing the root file system as the virtual disk, which will not appear to be partitioned. This is done by issuing a command similar to the following:<br />
<br />
{{Note|In this example, it is the '''host's''' images that are being used, not the guest's. If you wish to use the guest's images, either mount {{ic|/dev/sda3}} read-only (to protect the file system from the host) and specify the {{ic|/full/path/to/images}} or use some kexec hackery in the guest to reload the guest's kernel (extends boot time). }}<br />
<br />
$ qemu-system-x86_64 -kernel /boot/vmlinuz-linux -initrd /boot/initramfs-linux.img -append root=/dev/sda /dev/sda3<br />
<br />
In the above example, the physical partition being used for the guest's root file system is {{ic|/dev/sda3}} on the host, but it shows up as {{ic|/dev/sda}} on the guest.<br />
<br />
You may, of course, specify any kernel and initrd that you want, and not just the ones that come with Arch Linux.<br />
<br />
When there are multiple [[kernel parameters]] to be passed to the {{ic|-append}} option, they need to be quoted using single or double quotes. For example:<br />
<br />
... -append 'root=/dev/sda1 console=ttyS0'<br />
<br />
==== Simulating a virtual disk with MBR ====<br />
<br />
A more complicated way to have a virtual machine use a physical partition, while keeping that partition formatted as a file system and not just having the guest partition the partition as if it were a disk, is to simulate an MBR for it so that it can boot using a boot loader such as GRUB.<br />
<br />
For the following, suppose you have a plain, unmounted {{ic|/dev/hda''N''}} partition with some file system on it you wish to make part of a QEMU disk image. The trick is to dynamically prepend a master boot record (MBR) to the real partition you wish to embed in a QEMU raw disk image. More generally, the partition can be any part of a larger simulated disk, in particular a block device that simulates the original physical disk but only exposes {{ic|/dev/hda''N''}} to the virtual machine.<br />
<br />
A virtual disk of this type can be represented by a VMDK file that contains references to (a copy of) the MBR and the partition, but QEMU does not support this VMDK format. For instance, a virtual disk [https://www.virtualbox.org/manual/ch09.html#rawdisk created by]<br />
<br />
$ VBoxManage internalcommands createrawvmdk -filename ''/path/to/file.vmdk'' -rawdisk /dev/hda<br />
<br />
will be rejected by QEMU with the error message<br />
<br />
Unsupported image type 'partitionedDevice'<br />
<br />
Note that {{ic|VBoxManage}} creates two files, {{ic|''file.vmdk''}} and {{ic|''file-pt.vmdk''}}, the latter being a copy of the MBR, to which the text file {{ic|file.vmdk}} points. Read operations outside the target partition or the MBR would give zeros, while written data would be discarded.<br />
<br />
===== Using the device-mapper =====<br />
<br />
A method that is similar to the use of a VMDK descriptor file uses the [https://docs.kernel.org/admin-guide/device-mapper/index.html device-mapper] to prepend a loop device attached to the MBR file to the target partition. In case we do not need our virtual disk to have the same size as the original, we first create a file to hold the MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=2048<br />
<br />
Here, a 1 MiB (2048 * 512 bytes) file is created in accordance with partition alignment policies used by modern disk partitioning tools. For compatibility with older partitioning software, 63 sectors instead of 2048 might be required. The MBR only needs a single 512 bytes block, the additional free space can be used for a BIOS boot partition and, in the case of a hybrid partitioning scheme, for a GUID Partition Table. Then, we attach a loop device to the MBR file:<br />
<br />
{{hc|# losetup --show -f ''/path/to/mbr''|/dev/loop0}}<br />
<br />
In this example, the resulting device is {{ic|/dev/loop0}}. The device mapper is now used to join the MBR and the partition:<br />
<br />
# echo "0 2048 linear /dev/loop0 0<br />
2048 `blockdev --getsz /dev/hda''N''` linear /dev/hda''N'' 0" | dmsetup create qemu<br />
<br />
The resulting {{ic|/dev/mapper/qemu}} is what we will use as a QEMU raw disk image. Additional steps are required to create a partition table (see the section that describes the use of a linear RAID for an example) and boot loader code on the virtual disk (which will be stored in {{ic|''/path/to/mbr''}}).<br />
<br />
The following setup is an example where the position of {{ic|/dev/hda''N''}} on the virtual disk is to be the same as on the physical disk and the rest of the disk is hidden, except for the MBR, which is provided as a copy:<br />
<br />
# dd if=/dev/hda count=1 of=''/path/to/mbr''<br />
# loop=`losetup --show -f ''/path/to/mbr''`<br />
# start=`blockdev --report /dev/hda''N'' | tail -1 | awk '{print $5}'`<br />
# size=`blockdev --getsz /dev/hda''N''`<br />
# disksize=`blockdev --getsz /dev/hda`<br />
# echo "0 1 linear $loop 0<br />
1 $((start-1)) zero<br />
$start $size linear /dev/hda''N'' 0<br />
$((start+size)) $((disksize-start-size)) zero" | dmsetup create qemu<br />
<br />
The table provided as standard input to {{ic|dmsetup}} has a similar format as the table in a VDMK descriptor file produced by {{ic|VBoxManage}} and can alternatively be loaded from a file with {{ic|dmsetup create qemu --table ''table_file''}}. To the virtual machine, only {{ic|/dev/hda''N''}} is accessible, while the rest of the hard disk reads as zeros and discards written data, except for the first sector. We can print the table for {{ic|/dev/mapper/qemu}} with {{ic|dmsetup table qemu}} (use {{ic|udevadm info -rq name /sys/dev/block/''major'':''minor''}} to translate {{ic|''major'':''minor''}} to the corresponding {{ic|/dev/''blockdevice''}} name). Use {{ic|dmsetup remove qemu}} and {{ic|losetup -d $loop}} to delete the created devices.<br />
<br />
A situation where this example would be useful is an existing Windows XP installation in a multi-boot configuration and maybe a hybrid partitioning scheme (on the physical hardware, Windows XP could be the only operating system that uses the MBR partition table, while more modern operating systems installed on the same computer could use the GUID Partition Table). Windows XP supports hardware profiles, so that that the same installation can be used with different hardware configurations alternatingly (in this case bare metal vs. virtual) with Windows needing to install drivers for newly detected hardware only once for every profile. Note that in this example the boot loader code in the copied MBR needs to be updated to directly load Windows XP from {{ic|/dev/hda''N''}} instead of trying to start the multi-boot capable boot loader (like GRUB) present in the original system. Alternatively, a copy of the boot partition containing the boot loader installation can be included in the virtual disk the same way as the MBR.<br />
<br />
===== Using a linear RAID =====<br />
<br />
{{Out of date|[[Wikipedia:Cylinder-head-sector|CHS]] has been obsolete for decades.}}<br />
<br />
You can also do this using software [[RAID]] in linear mode (you need the {{ic|linear.ko}} kernel driver) and a loopback device: <br />
<br />
First, you create some small file to hold the MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=32<br />
<br />
Here, a 16 KiB (32 * 512 bytes) file is created. It is important not to make it too small (even if the MBR only needs a single 512 bytes block), since the smaller it will be, the smaller the chunk size of the software RAID device will have to be, which could have an impact on performance. Then, you setup a loopback device to the MBR file:<br />
<br />
# losetup -f ''/path/to/mbr''<br />
<br />
Let us assume the resulting device is {{ic|/dev/loop0}}, because we would not already have been using other loopbacks. Next step is to create the "merged" MBR + {{ic|/dev/hda''N''}} disk image using software RAID:<br />
<br />
# modprobe linear<br />
# mdadm --build --verbose /dev/md0 --chunk=16 --level=linear --raid-devices=2 /dev/loop0 /dev/hda''N''<br />
<br />
The resulting {{ic|/dev/md0}} is what you will use as a QEMU raw disk image (do not forget to set the permissions so that the emulator can access it). The last (and somewhat tricky) step is to set the disk configuration (disk geometry and partitions table) so that the primary partition start point in the MBR matches the one of {{ic|/dev/hda''N''}} inside {{ic|/dev/md0}} (an offset of exactly 16 * 512 = 16384 bytes in this example). Do this using {{ic|fdisk}} on the host machine, not in the emulator: the default raw disc detection routine from QEMU often results in non-kibibyte-roundable offsets (such as 31.5 KiB, as in the previous section) that cannot be managed by the software RAID code. Hence, from the host:<br />
<br />
# fdisk /dev/md0<br />
<br />
Press {{ic|X}} to enter the expert menu. Set number of 's'ectors per track so that the size of one cylinder matches the size of your MBR file. For two heads and a sector size of 512, the number of sectors per track should be 16, so we get cylinders of size 2x16x512=16k.<br />
<br />
Now, press {{ic|R}} to return to the main menu.<br />
<br />
Press {{ic|P}} and check that the cylinder size is now 16k.<br />
<br />
Now, create a single primary partition corresponding to {{ic|/dev/hda''N''}}. It should start at cylinder 2 and end at the end of the disk (note that the number of cylinders now differs from what it was when you entered fdisk.<br />
<br />
Finally, 'w'rite the result to the file: you are done. You now have a partition you can mount directly from your host, as well as part of a QEMU disk image:<br />
<br />
$ qemu-system-x86_64 -hdc /dev/md0 ''[...]''<br />
<br />
You can, of course, safely set any boot loader on this disk image using QEMU, provided the original {{ic|/dev/hda''N''}} partition contains the necessary tools.<br />
<br />
===== Using a Network Block Device =====<br />
<br />
With [https://docs.kernel.org/admin-guide/blockdev/nbd.html Network Block Device], Linux can use a remote server as one of its block device. You may use {{ic|nbd-server}} (from the {{Pkg|nbd}} package) to create an MBR wrapper for QEMU.<br />
<br />
Assuming you have already set up your MBR wrapper file like above, rename it to {{ic|wrapper.img.0}}. Then create a symbolic link named {{ic|wrapper.img.1}} in the same directory, pointing to your partition. Then put the following script in the same directory:<br />
<br />
{{bc|1=<br />
#!/bin/sh<br />
dir="$(realpath "$(dirname "$0")")"<br />
cat >wrapper.conf <<EOF<br />
[generic]<br />
allowlist = true<br />
listenaddr = 127.713705<br />
port = 10809<br />
<br />
[wrap]<br />
exportname = $dir/wrapper.img<br />
multifile = true<br />
EOF<br />
<br />
nbd-server \<br />
-C wrapper.conf \<br />
-p wrapper.pid \<br />
"$@"<br />
}}<br />
<br />
The {{ic|.0}} and {{ic|.1}} suffixes are essential; the rest can be changed. After running the above script (which you may need to do as root to make sure nbd-server is able to access the partition), you can launch QEMU with:<br />
<br />
qemu-system-x86_64 -drive file=nbd:127.713705:10809:exportname=wrap ''[...]''<br />
<br />
=== Using an entire physical disk device inside the virtual machine ===<br />
<br />
{{Style|Duplicates [[#Using any real partition as the single primary partition of a hard disk image]], libvirt instructions do not belong to this page.}}<br />
<br />
You may have a second disk with a different OS (like Windows) on it and may want to gain the ability to also boot it inside a virtual machine.<br />
Since the disk access is raw, the disk will perform quite well inside the virtual machine.<br />
<br />
==== Windows virtual machine boot prerequisites ====<br />
<br />
Be sure to install the [https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/archive-virtio/ virtio drivers] inside the OS on that disk before trying to boot it in the virtual machine.<br />
For Win 7 use version [https://askubuntu.com/questions/1310440/using-virtio-win-drivers-with-win7-sp1-x64 0.1.173-4].<br />
Some singular drivers from newer virtio builds may be used on Win 7 but you will have to install them manually via device manager.<br />
For Win 10 you can use the latest virtio build.<br />
<br />
===== Set up the windows disk interface drivers =====<br />
<br />
You may get a {{ic|0x0000007B}} bluescreen when trying to boot the virtual machine. This means Windows can not access the drive during the early boot stage because the disk interface driver it would need for that is not loaded / is set to start manually.<br />
<br />
The solution is to [https://superuser.com/a/1032769 enable these drivers to start at boot].<br />
<br />
In {{ic|HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services}}, find the folders {{ic|aliide, amdide, atapi, cmdide, iastor (may not exist), iastorV, intelide, LSI_SAS, msahci, pciide and viaide}}.<br />
Inside each of those, set all their "start" values to 0 in order to enable them at boot.<br />
If your drive is a PCIe NVMe drive, also enable that driver (should it exist).<br />
<br />
==== Find the unique path of your disk ====<br />
<br />
Run {{ic|ls /dev/disk/by-id/}}: tere you pick out the ID of the drive you want to insert into the virtual machine, for example {{ic|ata-TS512GMTS930L_C199211383}}.<br />
Now add that ID to {{ic|/dev/disk/by-id/}} so you get {{ic|/dev/disk/by-id/ata-TS512GMTS930L_C199211383}}.<br />
That is the unique path to that disk.<br />
<br />
==== Add the disk in QEMU CLI ====<br />
<br />
In QEMU CLI that would probably be:<br />
<br />
{{ic|1=-drive file=/dev/disk/by-id/ata-TS512GMTS930L_C199211383,format=raw,media=disk}}<br />
<br />
Just modify {{ic|file{{=}}}} to be the unique path of your drive.<br />
<br />
==== Add the disk in libvirt ====<br />
<br />
In libvirt XML that translates to<br />
<br />
{{hc|$ virsh edit ''vmname''|<nowiki><br />
...<br />
<disk type="block" device="disk"><br />
<driver name="qemu" type="raw" cache="none" io="native"/><br />
<source dev="/dev/disk/by-id/ata-TS512GMTS930L_C199211383"/><br />
<target dev="sda" bus="sata"/><br />
<address type="drive" controller="0" bus="0" target="0" unit="0"/><br />
</disk><br />
...<br />
</nowiki>}}<br />
<br />
Just modify "source dev" to be the unique path of your drive.<br />
<br />
==== Add the disk in virt-manager ====<br />
<br />
When creating a virtual machine, select "import existing drive" and just paste that unique path.<br />
If you already have the virtual machine, add a device, storage, then select or create custom storage.<br />
Now paste the unique path.<br />
<br />
== Networking ==<br />
<br />
{{Style|Network topologies (sections [[#Host-only networking]], [[#Internal networking]] and info spread out across other sections) should not be described alongside the various virtual interfaces implementations, such as [[#User-mode networking]], [[#Tap networking with QEMU]], [[#Networking with VDE2]].}}<br />
<br />
The performance of virtual networking should be better with tap devices and bridges than with user-mode networking or vde because tap devices and bridges are implemented in-kernel.<br />
<br />
In addition, networking performance can be improved by assigning virtual machines a [https://wiki.libvirt.org/page/Virtio virtio] network device rather than the default emulation of an e1000 NIC. See [[#Installing virtio drivers]] for more information.<br />
<br />
=== Link-level address caveat ===<br />
<br />
By giving the {{ic|-net nic}} argument to QEMU, it will, by default, assign a virtual machine a network interface with the link-level address {{ic|52:54:00:12:34:56}}. However, when using bridged networking with multiple virtual machines, it is essential that each virtual machine has a unique link-level (MAC) address on the virtual machine side of the tap device. Otherwise, the bridge will not work correctly, because it will receive packets from multiple sources that have the same link-level address. This problem occurs even if the tap devices themselves have unique link-level addresses because the source link-level address is not rewritten as packets pass through the tap device.<br />
<br />
Make sure that each virtual machine has a unique link-level address, but it should always start with {{ic|52:54:}}. Use the following option, replace ''X'' with arbitrary hexadecimal digit:<br />
<br />
$ qemu-system-x86_64 -net nic,macaddr=52:54:''XX:XX:XX:XX'' -net vde ''disk_image''<br />
<br />
Generating unique link-level addresses can be done in several ways:<br />
<br />
* Manually specify unique link-level address for each NIC. The benefit is that the DHCP server will assign the same IP address each time the virtual machine is run, but it is unusable for large number of virtual machines.<br />
* Generate random link-level address each time the virtual machine is run. Practically zero probability of collisions, but the downside is that the DHCP server will assign a different IP address each time. You can use the following command in a script to generate random link-level address in a {{ic|macaddr}} variable:<br />
<br />
{{bc|1=<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
qemu-system-x86_64 -net nic,macaddr="$macaddr" -net vde ''disk_image''<br />
}}<br />
<br />
* Use the following script {{ic|qemu-mac-hasher.py}} to generate the link-level address from the virtual machine name using a hashing function. Given that the names of virtual machines are unique, this method combines the benefits of the aforementioned methods: it generates the same link-level address each time the script is run, yet it preserves the practically zero probability of collisions.<br />
<br />
{{hc|qemu-mac-hasher.py|2=<br />
#!/usr/bin/env python<br />
# usage: qemu-mac-hasher.py <VMName><br />
<br />
import sys<br />
import zlib<br />
<br />
crc = str(hex(zlib.crc32(sys.argv[1].encode("utf-8")))).replace("x", "")[-8:]<br />
print("52:54:%s%s:%s%s:%s%s:%s%s" % tuple(crc))<br />
}}<br />
<br />
In a script, you can use for example:<br />
<br />
vm_name="''VM Name''"<br />
qemu-system-x86_64 -name "$vm_name" -net nic,macaddr=$(qemu-mac-hasher.py "$vm_name") -net vde ''disk_image''<br />
<br />
=== User-mode networking ===<br />
<br />
By default, without any {{ic|-netdev}} arguments, QEMU will use user-mode networking with a built-in DHCP server. Your virtual machines will be assigned an IP address when they run their DHCP client, and they will be able to access the physical host's network through IP masquerading done by QEMU.<br />
<br />
{{Note|ICMPv6 will not work, as support for it is not implemented: {{ic|Slirp: external icmpv6 not supported yet}}. [[Ping]]ing an IPv6 address will not work.}}<br />
<br />
This default configuration allows your virtual machines to easily access the Internet, provided that the host is connected to it, but the virtual machines will not be directly visible on the external network, nor will virtual machines be able to talk to each other if you start up more than one concurrently.<br />
<br />
QEMU's user-mode networking can offer more capabilities such as built-in TFTP or SMB servers, redirecting host ports to the guest (for example to allow SSH connections to the guest) or attaching guests to VLANs so that they can talk to each other. See the QEMU documentation on the {{ic|-net user}} flag for more details.<br />
<br />
However, user-mode networking has limitations in both utility and performance. More advanced network configurations require the use of tap devices or other methods.<br />
<br />
{{Note|If the host system uses [[systemd-networkd]], make sure to symlink the {{ic|/etc/resolv.conf}} file as described in [[systemd-networkd#Required services and setup]], otherwise the DNS lookup in the guest system will not work.}}<br />
<br />
{{Tip|<br />
* To use the virtio driver with user-mode networking, the option is: {{ic|1=-nic user,model=virtio-net-pci}}.<br />
* You can isolate user-mode networking from the host and the outside world by adding {{ic|1=restrict=y}}, for example: {{ic|1=-net user,restrict=y}}<br />
}}<br />
<br />
=== Tap networking with QEMU ===<br />
<br />
[[wikipedia:TUN/TAP|Tap devices]] are a Linux kernel feature that allows you to create virtual network interfaces that appear as real network interfaces. Packets sent to a tap interface are delivered to a userspace program, such as QEMU, that has bound itself to the interface.<br />
<br />
QEMU can use tap networking for a virtual machine so that packets sent to the tap interface will be sent to the virtual machine and appear as coming from a network interface (usually an Ethernet interface) in the virtual machine. Conversely, everything that the virtual machine sends through its network interface will appear on the tap interface.<br />
<br />
Tap devices are supported by the Linux bridge drivers, so it is possible to bridge together tap devices with each other and possibly with other host interfaces such as {{ic|eth0}}. This is desirable if you want your virtual machines to be able to talk to each other, or if you want other machines on your LAN to be able to talk to the virtual machines.<br />
<br />
{{Warning|If you bridge together tap device and some host interface, such as {{ic|eth0}}, your virtual machines will appear directly on the external network, which will expose them to possible attack. Depending on what resources your virtual machines have access to, you may need to take all the [[Firewalls|precautions]] you normally would take in securing a computer to secure your virtual machines. If the risk is too great, virtual machines have little resources or you set up multiple virtual machines, a better solution might be to use [[#Host-only networking|host-only networking]] and set up NAT. In this case you only need one firewall on the host instead of multiple firewalls for each guest.}}<br />
<br />
As indicated in the user-mode networking section, tap devices offer higher networking performance than user-mode. If the guest OS supports virtio network driver, then the networking performance will be increased considerably as well. Supposing the use of the tap0 device, that the virtio driver is used on the guest, and that no scripts are used to help start/stop networking, next is part of the qemu command one should see:<br />
<br />
-device virtio-net,netdev=network0 -netdev tap,id=network0,ifname=tap0,script=no,downscript=no<br />
<br />
But if already using a tap device with virtio networking driver, one can even boost the networking performance by enabling vhost, like:<br />
<br />
-device virtio-net,netdev=network0 -netdev tap,id=network0,ifname=tap0,script=no,downscript=no,vhost=on<br />
<br />
See [https://web.archive.org/web/20160222161955/http://www.linux-kvm.com:80/content/how-maximize-virtio-net-performance-vhost-net] for more information.<br />
<br />
==== Host-only networking ====<br />
<br />
If the bridge is given an IP address and traffic destined for it is allowed, but no real interface (e.g. {{ic|eth0}}) is connected to the bridge, then the virtual machines will be able to talk to each other and the host system. However, they will not be able to talk to anything on the external network, provided that you do not set up IP masquerading on the physical host. This configuration is called ''host-only networking'' by other virtualization software such as [[VirtualBox]].<br />
<br />
{{Tip|<br />
* If you want to set up IP masquerading, e.g. NAT for virtual machines, see the [[Internet sharing#Enable NAT]] page.<br />
* See [[Network bridge]] for information on creating bridge.<br />
* You may want to have a DHCP server running on the bridge interface to service the virtual network. For example, to use the {{ic|172.20.0.1/16}} subnet with [[dnsmasq]] as the DHCP server:<br />
<br />
{{bc|1=<br />
# ip addr add 172.20.0.1/16 dev br0<br />
# ip link set br0 up<br />
# dnsmasq --interface=br0 --bind-interfaces --dhcp-range=172.20.0.2,172.20.255.254<br />
}}<br />
}}<br />
<br />
==== Internal networking ====<br />
<br />
If you do not give the bridge an IP address and add an [[iptables]] rule to drop all traffic to the bridge in the INPUT chain, then the virtual machines will be able to talk to each other, but not to the physical host or to the outside network. This configuration is called ''internal networking'' by other virtualization software such as [[VirtualBox]]. You will need to either assign static IP addresses to the virtual machines or run a DHCP server on one of them.<br />
<br />
By default iptables would drop packets in the bridge network. You may need to use such iptables rule to allow packets in a bridged network:<br />
<br />
# iptables -I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Bridged networking using qemu-bridge-helper ====<br />
<br />
This method does not require a start-up script and readily accommodates multiple taps and multiple bridges. It uses {{ic|/usr/lib/qemu/qemu-bridge-helper}} binary, which allows creating tap devices on an existing bridge.<br />
<br />
{{Tip|<br />
* See [[Network bridge]] for information on creating bridge.<br />
* See https://wiki.qemu.org/Features/HelperNetworking for more information on QEMU's network helper.<br />
}}<br />
<br />
First, create a configuration file containing the names of all bridges to be used by QEMU:<br />
<br />
{{hc|/etc/qemu/bridge.conf|<br />
allow ''br0''<br />
allow ''br1''<br />
...}}<br />
<br />
Make sure {{ic|/etc/qemu/}} has {{ic|755}} [[permissions]]. [https://gitlab.com/qemu-project/qemu/-/issues/515 QEMU issues] and [https://www.gns3.com/community/discussions/gns3-cannot-work-with-qemu GNS3 issues] may arise if this is not the case.<br />
<br />
Now start the virtual machine; the most basic usage to run QEMU with the default network helper and default bridge {{ic|br0}}:<br />
<br />
$ qemu-system-x86_64 -nic bridge ''[...]''<br />
<br />
Using the bridge {{ic|br1}} and the virtio driver:<br />
<br />
$ qemu-system-x86_64 -nic bridge,br=''br1'',model=virtio-net-pci ''[...]''<br />
<br />
==== Creating bridge manually ====<br />
<br />
{{Style|This section needs serious cleanup and may contain out-of-date information.}}<br />
<br />
{{Tip|Since QEMU 1.1, the [https://wiki.qemu.org/Features/HelperNetworking network bridge helper] can set tun/tap up for you without the need for additional scripting. See [[#Bridged networking using qemu-bridge-helper]].}}<br />
<br />
The following describes how to bridge a virtual machine to a host interface such as {{ic|eth0}}, which is probably the most common configuration. This configuration makes it appear that the virtual machine is located directly on the external network, on the same Ethernet segment as the physical host machine.<br />
<br />
We will replace the normal Ethernet adapter with a bridge adapter and bind the normal Ethernet adapter to it.<br />
<br />
* Install {{Pkg|bridge-utils}}, which provides {{ic|brctl}} to manipulate bridges.<br />
<br />
* Enable IPv4 forwarding:<br />
<br />
# sysctl -w net.ipv4.ip_forward=1<br />
<br />
To make the change permanent, change {{ic|1=net.ipv4.ip_forward = 0}} to {{ic|1=net.ipv4.ip_forward = 1}} in {{ic|/etc/sysctl.d/99-sysctl.conf}}.<br />
<br />
* Load the {{ic|tun}} module and configure it to be loaded on boot. See [[Kernel modules]] for details.<br />
<br />
* Optionally create the bridge. See [[Bridge with netctl]] for details. Remember to name your bridge as {{ic|br0}}, or change the scripts below to your bridge's name. In the {{ic|run-qemu}} script below, {{ic|br0}} is set up if not listed, as it is assumed that by default the host is not accessing network via the bridge.<br />
<br />
* Create the script that QEMU uses to bring up the tap adapter with {{ic|root:kvm}} 750 permissions:<br />
<br />
{{hc|/etc/qemu-ifup|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifup"<br />
echo "Bringing up $1 for bridged mode..."<br />
sudo /usr/bin/ip link set $1 up promisc on<br />
echo "Adding $1 to br0..."<br />
sudo /usr/bin/brctl addif br0 $1<br />
sleep 2<br />
</nowiki>}}<br />
<br />
* Create the script that QEMU uses to bring down the tap adapter in {{ic|/etc/qemu-ifdown}} with {{ic|root:kvm}} 750 permissions:<br />
{{hc|/etc/qemu-ifdown|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifdown"<br />
sudo /usr/bin/ip link set $1 down<br />
sudo /usr/bin/brctl delif br0 $1<br />
sudo /usr/bin/ip link delete dev $1<br />
</nowiki>}}<br />
<br />
* Use {{ic|visudo}} to add the following to your {{ic|sudoers}} file:<br />
<br />
{{bc|<nowiki><br />
Cmnd_Alias QEMU=/usr/bin/ip,/usr/bin/modprobe,/usr/bin/brctl<br />
%kvm ALL=NOPASSWD: QEMU<br />
</nowiki>}}<br />
<br />
* You launch QEMU using the following {{ic|run-qemu}} script:<br />
<br />
{{hc|run-qemu|<nowiki><br />
#!/bin/bash<br />
: '<br />
e.g. with img created via:<br />
qemu-img create -f qcow2 example.img 90G<br />
run-qemu -cdrom archlinux-x86_64.iso -boot order=d -drive file=example.img,format=qcow2 -m 4G -enable-kvm -cpu host -smp 4<br />
run-qemu -drive file=example.img,format=qcow2 -m 4G -enable-kvm -cpu host -smp 4<br />
'<br />
<br />
nicbr0() {<br />
sudo ip link set dev $1 promisc on up &> /dev/null<br />
sudo ip addr flush dev $1 scope host &>/dev/null<br />
sudo ip addr flush dev $1 scope site &>/dev/null<br />
sudo ip addr flush dev $1 scope global &>/dev/null<br />
sudo ip link set dev $1 master br0 &> /dev/null<br />
}<br />
_nicbr0() {<br />
sudo ip link set $1 promisc off down &> /dev/null<br />
sudo ip link set dev $1 nomaster &> /dev/null<br />
}<br />
<br />
HASBR0="$( ip link show | grep br0 )"<br />
if [ -z $HASBR0 ] ; then<br />
ROUTER="192.168.1.1"<br />
SUBNET="192.168.1."<br />
NIC=$(ip link show | grep en | grep 'state UP' | head -n 1 | cut -d":" -f 2 | xargs)<br />
IPADDR=$(ip addr show | grep -o "inet $SUBNET\([0-9]*\)" | cut -d ' ' -f2)<br />
sudo ip link add name br0 type bridge &> /dev/null<br />
sudo ip link set dev br0 up<br />
sudo ip addr add $IPADDR/24 brd + dev br0<br />
sudo ip route del default &> /dev/null<br />
sudo ip route add default via $ROUTER dev br0 onlink<br />
nicbr0 $NIC<br />
sudo iptables -I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
fi<br />
<br />
USERID=$(whoami)<br />
precreationg=$(ip tuntap list | cut -d: -f1 | sort)<br />
sudo ip tuntap add user $USERID mode tap<br />
postcreation=$(ip tuntap list | cut -d: -f1 | sort)<br />
TAP=$(comm -13 <(echo "$precreationg") <(echo "$postcreation"))<br />
nicbr0 $TAP<br />
<br />
printf -v MACADDR "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
qemu-system-x86_64 -net nic,macaddr=$MACADDR,model=virtio \<br />
-net tap,ifname=$TAP,script=no,downscript=no,vhost=on \<br />
$@<br />
<br />
_nicbr0 $TAP<br />
sudo ip link set dev $TAP down &> /dev/null<br />
sudo ip tuntap del $TAP mode tap<br />
<br />
if [ -z $HASBR0 ] ; then<br />
_nicbr0 $NIC<br />
sudo ip addr del dev br0 $IPADDR/24 &> /dev/null<br />
sudo ip link set dev br0 down<br />
sudo ip link delete br0 type bridge &> /dev/null<br />
sudo ip route del default &> /dev/null<br />
sudo ip link set dev $NIC up<br />
sudo ip route add default via $ROUTER dev $NIC onlink &> /dev/null<br />
fi<br />
</nowiki>}}<br />
<br />
Then to launch a virtual machine, do something like this<br />
<br />
$ run-qemu -hda ''myvm.img'' -m 512<br />
<br />
* It is recommended for performance and security reasons to disable the [http://ebtables.netfilter.org/documentation/bridge-nf.html firewall on the bridge]:<br />
<br />
{{hc|/etc/sysctl.d/10-disable-firewall-on-bridge.conf|<nowiki><br />
net.bridge.bridge-nf-call-ip6tables = 0<br />
net.bridge.bridge-nf-call-iptables = 0<br />
net.bridge.bridge-nf-call-arptables = 0<br />
</nowiki>}}<br />
<br />
In order to apply the parameters described above on boot, you will also need to load the br-netfilter module on boot. Otherwise, the parameters will not exist when sysctl will try to modify them.<br />
<br />
{{hc|/etc/modules-load.d/br_netfilter.conf|<nowiki><br />
br_netfilter<br />
</nowiki>}}<br />
<br />
Run {{ic|sysctl -p /etc/sysctl.d/10-disable-firewall-on-bridge.conf}} to apply the changes immediately.<br />
<br />
See the [https://wiki.libvirt.org/page/Networking#Creating_network_initscripts libvirt wiki] and [https://bugzilla.redhat.com/show_bug.cgi?id=512206 Fedora bug 512206]. If you get errors by sysctl during boot about non-existing files, make the {{ic|bridge}} module load at boot. See [[Kernel module#systemd]].<br />
<br />
Alternatively, you can configure [[iptables]] to allow all traffic to be forwarded across the bridge by adding a rule like this:<br />
<br />
-I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Network sharing between physical device and a Tap device through iptables ====<br />
<br />
{{Merge|Internet_sharing|Duplication, not specific to QEMU.}}<br />
<br />
Bridged networking works fine between a wired interface (Eg. eth0), and it is easy to setup. However if the host gets connected to the network through a wireless device, then bridging is not possible.<br />
<br />
See [[Network bridge#Wireless interface on a bridge]] as a reference.<br />
<br />
One way to overcome that is to setup a tap device with a static IP, making linux automatically handle the routing for it, and then forward traffic between the tap interface and the device connected to the network through iptables rules.<br />
<br />
See [[Internet sharing]] as a reference.<br />
<br />
There you can find what is needed to share the network between devices, included tap and tun ones. The following just hints further on some of the host configurations required. As indicated in the reference above, the client needs to be configured for a static IP, using the IP assigned to the tap interface as the gateway. The caveat is that the DNS servers on the client might need to be manually edited if they change when changing from one host device connected to the network to another.<br />
<br />
To allow IP forwarding on every boot, one need to add the following lines to sysctl configuration file inside {{ic|/etc/sysctl.d}}:<br />
<br />
net.ipv4.ip_forward = 1<br />
net.ipv6.conf.default.forwarding = 1<br />
net.ipv6.conf.all.forwarding = 1<br />
<br />
The iptables rules can look like:<br />
<br />
# Forwarding from/to outside<br />
iptables -A FORWARD -i ${INT} -o ${EXT_0} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_1} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_2} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_0} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_1} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_2} -o ${INT} -j ACCEPT<br />
# NAT/Masquerade (network address translation)<br />
iptables -t nat -A POSTROUTING -o ${EXT_0} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_1} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_2} -j MASQUERADE<br />
<br />
The prior supposes there are 3 devices connected to the network sharing traffic with one internal device, where for example:<br />
<br />
INT=tap0<br />
EXT_0=eth0<br />
EXT_1=wlan0<br />
EXT_2=tun0<br />
<br />
The prior shows a forwarding that would allow sharing wired and wireless connections with the tap device.<br />
<br />
The forwarding rules shown are stateless, and for pure forwarding. One could think of restricting specific traffic, putting a firewall in place to protect the guest and others. However those would decrease the networking performance, while a simple bridge does not include any of that.<br />
<br />
Bonus: Whether the connection is wired or wireless, if one gets connected through VPN to a remote site with a tun device, supposing the tun device opened for that connection is tun0, and the prior iptables rules are applied, then the remote connection gets also shared with the guest. This avoids the need for the guest to also open a VPN connection. Again, as the guest networking needs to be static, then if connecting the host remotely this way, one most probably will need to edit the DNS servers on the guest.<br />
<br />
=== Networking with VDE2 ===<br />
<br />
{{Style|This section needs serious cleanup and may contain out-of-date information.}}<br />
<br />
==== What is VDE? ====<br />
<br />
VDE stands for Virtual Distributed Ethernet. It started as an enhancement of [[User-mode Linux|uml]]_switch. It is a toolbox to manage virtual networks.<br />
<br />
The idea is to create virtual switches, which are basically sockets, and to "plug" both physical and virtual machines in them. The configuration we show here is quite simple; However, VDE is much more powerful than this, it can plug virtual switches together, run them on different hosts and monitor the traffic in the switches. You are invited to read [https://wiki.virtualsquare.org/ the documentation of the project].<br />
<br />
The advantage of this method is you do not have to add sudo privileges to your users. Regular users should not be allowed to run modprobe.<br />
<br />
==== Basics ====<br />
<br />
VDE support can be [[install]]ed via the {{Pkg|vde2}} package.<br />
<br />
In our config, we use tun/tap to create a virtual interface on my host. Load the {{ic|tun}} module (see [[Kernel modules]] for details):<br />
<br />
# modprobe tun<br />
<br />
Now create the virtual switch:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
<br />
This line creates the switch, creates {{ic|tap0}}, "plugs" it, and allows the users of the group {{ic|users}} to use it.<br />
<br />
The interface is plugged in but not configured yet. To configure it, run this command:<br />
<br />
# ip addr add 192.168.100.254/24 dev tap0<br />
<br />
Now, you just have to run KVM with these {{ic|-net}} options as a normal user:<br />
<br />
$ qemu-system-x86_64 -net nic -net vde -hda ''[...]''<br />
<br />
Configure networking for your guest as you would do in a physical network.<br />
<br />
{{Tip|You might want to set up NAT on tap device to access the internet from the virtual machine. See [[Internet sharing#Enable NAT]] for more information.}}<br />
<br />
==== Startup scripts ====<br />
<br />
Example of main script starting VDE:<br />
<br />
{{hc|/etc/systemd/scripts/qemu-network-env|<nowiki><br />
#!/bin/sh<br />
# QEMU/VDE network environment preparation script<br />
<br />
# The IP configuration for the tap device that will be used for<br />
# the virtual machine network:<br />
<br />
TAP_DEV=tap0<br />
TAP_IP=192.168.100.254<br />
TAP_MASK=24<br />
TAP_NETWORK=192.168.100.0<br />
<br />
# Host interface<br />
NIC=eth0<br />
<br />
case "$1" in<br />
start)<br />
echo -n "Starting VDE network for QEMU: "<br />
<br />
# If you want tun kernel module to be loaded by script uncomment here<br />
#modprobe tun 2>/dev/null<br />
## Wait for the module to be loaded<br />
#while ! lsmod | grep -q "^tun"; do echo "Waiting for tun device"; sleep 1; done<br />
<br />
# Start tap switch<br />
vde_switch -tap "$TAP_DEV" -daemon -mod 660 -group users<br />
<br />
# Bring tap interface up<br />
ip address add "$TAP_IP"/"$TAP_MASK" dev "$TAP_DEV"<br />
ip link set "$TAP_DEV" up<br />
<br />
# Start IP Forwarding<br />
echo "1" > /proc/sys/net/ipv4/ip_forward<br />
iptables -t nat -A POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
;;<br />
stop)<br />
echo -n "Stopping VDE network for QEMU: "<br />
# Delete the NAT rules<br />
iptables -t nat -D POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
<br />
# Bring tap interface down<br />
ip link set "$TAP_DEV" down<br />
<br />
# Kill VDE switch<br />
pgrep vde_switch | xargs kill -TERM<br />
;;<br />
restart|reload)<br />
$0 stop<br />
sleep 1<br />
$0 start<br />
;;<br />
*)<br />
echo "Usage: $0 {start|stop|restart|reload}"<br />
exit 1<br />
esac<br />
exit 0<br />
</nowiki>}}<br />
<br />
Example of systemd service using the above script:<br />
<br />
{{hc|/etc/systemd/system/qemu-network-env.service|<nowiki><br />
[Unit]<br />
Description=Manage VDE Switch<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/etc/systemd/scripts/qemu-network-env start<br />
ExecStop=/etc/systemd/scripts/qemu-network-env stop<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
Change permissions for {{ic|qemu-network-env}} to be [[executable]]. <br />
<br />
You can [[start]] {{ic|qemu-network-env.service}} as usual.<br />
<br />
==== Alternative method ====<br />
<br />
If the above method does not work or you do not want to mess with kernel configs, TUN, dnsmasq, and iptables you can do the following for the same result.<br />
<br />
# vde_switch -daemon -mod 660 -group users<br />
# slirpvde --dhcp --daemon<br />
<br />
Then, to start the virtual machine with a connection to the network of the host:<br />
<br />
$ qemu-system-x86_64 -net nic,macaddr=52:54:00:00:EE:03 -net vde ''disk_image''<br />
<br />
=== VDE2 Bridge ===<br />
<br />
Based on [https://selamatpagicikgu.wordpress.com/2011/06/08/quickhowto-qemu-networking-using-vde-tuntap-and-bridge/ quickhowto: qemu networking using vde, tun/tap, and bridge] graphic. Any virtual machine connected to vde is externally exposed. For example, each virtual machine can receive DHCP configuration directly from your ADSL router.<br />
<br />
==== Basics ====<br />
<br />
Remember that you need {{ic|tun}} module and {{Pkg|bridge-utils}} package.<br />
<br />
Create the vde2/tap device:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
# ip link set tap0 up<br />
<br />
Create bridge:<br />
<br />
# brctl addbr br0<br />
<br />
Add devices:<br />
<br />
# brctl addif br0 eth0<br />
# brctl addif br0 tap0<br />
<br />
And configure bridge interface:<br />
<br />
# dhcpcd br0<br />
<br />
==== Startup scripts ====<br />
<br />
All devices must be set up. And only the bridge needs an IP address. For physical devices on the bridge (e.g. {{ic|eth0}}), this can be done with [[netctl]] using a custom Ethernet profile with:<br />
<br />
{{hc|/etc/netctl/ethernet-noip|2=<br />
Description='A more versatile static Ethernet connection'<br />
Interface=eth0<br />
Connection=ethernet<br />
IP=no<br />
}}<br />
<br />
The following custom systemd service can be used to create and activate a VDE2 tap interface for users in the {{ic|users}} user group.<br />
<br />
{{hc|/etc/systemd/system/vde2@.service|2=<br />
[Unit]<br />
Description=Network Connectivity for %i<br />
Wants=network.target<br />
Before=network.target<br />
<br />
[Service]<br />
Type=oneshot<br />
RemainAfterExit=yes<br />
ExecStart=/usr/bin/vde_switch -tap %i -daemon -mod 660 -group users<br />
ExecStart=/usr/bin/ip link set dev %i up<br />
ExecStop=/usr/bin/ip addr flush dev %i<br />
ExecStop=/usr/bin/ip link set dev %i down<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
}}<br />
<br />
And finally, you can create the [[Bridge with netctl|bridge interface with netctl]].<br />
<br />
=== Shorthand configuration ===<br />
<br />
If you are using QEMU with various networking options a lot, you probably have created a lot of {{ic|-netdev}} and {{ic|-device}} argument pairs, which gets quite repetitive. You can instead use the {{ic|-nic}} argument to combine {{ic|-netdev}} and {{ic|-device}} together, so that, for example, these arguments:<br />
<br />
-netdev tap,id=network0,ifname=tap0,script=no,downscript=no,vhost=on -device virtio-net-pci,netdev=network0<br />
<br />
become:<br />
<br />
-nic tap,script=no,downscript=no,vhost=on,model=virtio-net-pci<br />
<br />
Notice the lack of network IDs, and that the device was created with {{ic|1=model=}}. The first half of the {{ic|-nic}} parameters are {{ic|-netdev}} parameters, whereas the second half (after {{ic|1=model=}}) are related with the device. The same parameters (for example, {{ic|1=smb=}}) are used. To completely disable the networking use {{ic|-nic none}}.<br />
<br />
See [https://qemu.weilnetz.de/doc/6.0/system/net.html QEMU networking documentation] for more information on parameters you can use.<br />
<br />
== Graphic card ==<br />
<br />
QEMU can emulate a standard graphic card text mode using {{ic|-display curses}} command line option. This allows to type text and see text output directly inside a text terminal. Alternatively, {{ic|-nographic}} serves a similar purpose.<br />
<br />
QEMU can emulate several types of VGA card. The card type is passed in the {{ic|-vga ''type''}} command line option and can be {{ic|std}}, {{ic|qxl}}, {{ic|vmware}}, {{ic|virtio}}, {{ic|cirrus}} or {{ic|none}}.<br />
<br />
=== std ===<br />
<br />
With {{ic|-vga std}} you can get a resolution of up to 2560 x 1600 pixels without requiring guest drivers. This is the default since QEMU 2.2.<br />
<br />
=== qxl ===<br />
<br />
QXL is a paravirtual graphics driver with 2D support. To use it, pass the {{ic|-vga qxl}} option and install drivers in the guest. You may want to use [[#SPICE]] for improved graphical performance when using QXL.<br />
<br />
On Linux guests, the {{ic|qxl}} and {{ic|bochs_drm}} kernel modules must be loaded in order to gain a decent performance.<br />
<br />
Default VGA memory size for QXL devices is 16M which is sufficient to drive resolutions approximately up to QHD (2560x1440). To enable higher resolutions, [[#Multi-monitor support|increase vga_memmb]].<br />
<br />
=== vmware ===<br />
<br />
Although it is a bit buggy, it performs better than std and cirrus. Install the VMware drivers {{Pkg|xf86-video-vmware}} and {{Pkg|xf86-input-vmmouse}} for Arch Linux guests.<br />
<br />
=== virtio ===<br />
<br />
{{ic|virtio-vga}} / {{ic|virtio-gpu}} is a paravirtual 3D graphics driver based on [https://virgil3d.github.io/ virgl]. It's mature, currently supporting only Linux guests with {{Pkg|mesa}} compiled with the option {{ic|1=gallium-drivers=virgl}}.<br />
<br />
To enable 3D acceleration on the guest system, select this vga with {{ic|-device virtio-vga-gl}} and enable the OpenGL context in the display device with {{ic|1=-display sdl,gl=on}} or {{ic|1=-display gtk,gl=on}} for the SDL and GTK display output respectively. Successful configuration can be confirmed looking at the kernel log in the guest:<br />
<br />
{{hc|# dmesg {{!}} grep drm |<br />
[drm] pci: virtio-vga detected<br />
[drm] virgl 3d acceleration enabled<br />
}}<br />
<br />
=== cirrus ===<br />
<br />
The cirrus graphical adapter was the default [https://wiki.qemu.org/ChangeLog/2.2#VGA before 2.2]. It [https://www.kraxel.org/blog/2014/10/qemu-using-cirrus-considered-harmful/ should not] be used on modern systems.<br />
<br />
=== none ===<br />
<br />
This is like a PC that has no VGA card at all. You would not even be able to access it with the {{ic|-vnc}} option. Also, this is different from the {{ic|-nographic}} option which lets QEMU emulate a VGA card, but disables the SDL display.<br />
<br />
== SPICE ==<br />
<br />
The [https://www.spice-space.org/ SPICE project] aims to provide a complete open source solution for remote access to virtual machines in a seamless way.<br />
<br />
=== Enabling SPICE support on the host ===<br />
<br />
The following is an example of booting with SPICE as the remote desktop protocol, including the support for copy and paste from host:<br />
<br />
$ qemu-system-x86_64 -vga qxl -device virtio-serial-pci -spice port=5930,disable-ticketing=on -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
The parameters have the following meaning:<br />
<br />
# {{ic|-device virtio-serial-pci}} adds a virtio-serial device<br />
# {{ic|1=-spice port=5930,disable-ticketing=on}} set TCP port {{ic|5930}} for spice channels listening and allow client to connect without authentication{{Tip|Using [[wikipedia:Unix_socket|Unix sockets]] instead of TCP ports does not involve using network stack on the host system. It does not imply that packets are encapsulated and decapsulated to use the network and the related protocol. The sockets are identified solely by the inodes on the hard drive. It is therefore considered better for performance. Use instead {{ic|1=-spice unix=on,addr=/tmp/vm_spice.socket,disable-ticketing=on}}.}}<br />
# {{ic|1=-device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0}} opens a port for spice vdagent in the virtio-serial device,<br />
# {{ic|1=-chardev spicevmc,id=spicechannel0,name=vdagent}} adds a spicevmc chardev for that port. It is important that the {{ic|1=chardev=}} option of the {{ic|virtserialport}} device matches the {{ic|1=id=}} option given to the {{ic|chardev}} option ({{ic|spicechannel0}} in this example). It is also important that the port name is {{ic|com.redhat.spice.0}}, because that is the namespace where vdagent is looking for in the guest. And finally, specify {{ic|1=name=vdagent}} so that spice knows what this channel is for.<br />
<br />
=== Connecting to the guest with a SPICE client ===<br />
<br />
A SPICE client is necessary to connect to the guest. In Arch, the following clients are available:<br />
<br />
* {{App|virt-viewer|SPICE client recommended by the protocol developers, a subset of the virt-manager project.|https://virt-manager.org/|{{Pkg|virt-viewer}}}}<br />
* {{App|spice-gtk|SPICE GTK client, a subset of the SPICE project. Embedded into other applications as a widget.|https://www.spice-space.org/|{{Pkg|spice-gtk}}}}<br />
<br />
For clients that run on smartphone or on other platforms, refer to the ''Other clients'' section in [https://www.spice-space.org/download.html spice-space download].<br />
<br />
==== Manually running a SPICE client ====<br />
<br />
One way of connecting to a guest listening on Unix socket {{ic|/tmp/vm_spice.socket}} is to manually run the SPICE client using {{ic|$ remote-viewer spice+unix:///tmp/vm_spice.socket}} or {{ic|1=$ spicy --uri="spice+unix:///tmp/vm_spice.socket"}}, depending on the desired client. Since QEMU in SPICE mode acts similarly to a remote desktop server, it may be more convenient to run QEMU in daemon mode with the {{ic|-daemonize}} parameter.<br />
<br />
{{Tip|<br />
To connect to the guest through SSH tunneling, the following type of command can be used: {{bc|$ ssh -fL 5999:localhost:5930 ''my.domain.org'' sleep 10; spicy -h 127.0.0.1 -p 5999}}<br />
This example connects ''spicy'' to the local port {{ic|5999}} which is forwarded through SSH to the guest's SPICE server located at the address ''my.domain.org'', port {{ic|5930}}.<br />
Note the {{ic|-f}} option that requests ssh to execute the command {{ic|sleep 10}} in the background. This way, the ssh session runs while the client is active and auto-closes once the client ends.<br />
}}<br />
<br />
==== Running a SPICE client with QEMU ====<br />
<br />
QEMU can automatically start a SPICE client with an appropriate socket, if the display is set to SPICE with the {{ic|-display spice-app}} parameter. This will use the system's default SPICE client as the viewer, determined by your [[XDG MIME Applications#mimeapps.list|mimeapps.list]] files.<br />
<br />
=== Enabling SPICE support on the guest ===<br />
<br />
For '''Arch Linux guests''', for improved support for multiple monitors or clipboard sharing, the following packages should be installed:<br />
* {{Pkg|spice-vdagent}}: Spice agent xorg client that enables copy and paste between client and X-session and more. (Refer to this [https://github.com/systemd/systemd/issues/18791 issue], until fixed, for workarounds to get this to work on non-GNOME desktops.)<br />
* {{Pkg|xf86-video-qxl}}: Xorg X11 qxl video driver<br />
* {{AUR|x-resize}}: Desktop environments other than GNOME do not react automatically when the SPICE client window is resized. This package uses a [[udev]] rule and [[xrandr]] to implement auto-resizing for all X11-based desktop environments and window managers.<br />
For guests under '''other operating systems''', refer to the ''Guest'' section in spice-space [https://www.spice-space.org/download.html download].<br />
<br />
=== Password authentication with SPICE ===<br />
<br />
If you want to enable password authentication with SPICE you need to remove {{ic|disable-ticketing}} from the {{ic|-spice}} argument and instead add {{ic|1=password=''yourpassword''}}. For example:<br />
<br />
$ qemu-system-x86_64 -vga qxl -spice port=5900,password=''yourpassword'' -device virtio-serial-pci -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
Your SPICE client should now ask for the password to be able to connect to the SPICE server.<br />
<br />
=== TLS encrypted communication with SPICE ===<br />
<br />
You can also configure TLS encryption for communicating with the SPICE server. First, you need to have a directory which contains the following files (the names must be exactly as indicated):<br />
<br />
* {{ic|ca-cert.pem}}: the CA master certificate.<br />
* {{ic|server-cert.pem}}: the server certificate signed with {{ic|ca-cert.pem}}.<br />
* {{ic|server-key.pem}}: the server private key.<br />
<br />
An example of generation of self-signed certificates with your own generated CA for your server is shown in the [https://www.spice-space.org/spice-user-manual.html#_generating_self_signed_certificates Spice User Manual].<br />
<br />
Afterwards, you can run QEMU with SPICE as explained above but using the following {{ic|-spice}} argument: {{ic|1=-spice tls-port=5901,password=''yourpassword'',x509-dir=''/path/to/pki_certs''}}, where {{ic|''/path/to/pki_certs''}} is the directory path that contains the three needed files shown earlier.<br />
<br />
It is now possible to connect to the server using {{Pkg|virt-viewer}}:<br />
<br />
$ remote-viewer spice://''hostname''?tls-port=5901 --spice-ca-file=''/path/to/ca-cert.pem'' --spice-host-subject="C=''XX'',L=''city'',O=''organization'',CN=''hostname''" --spice-secure-channels=all<br />
<br />
Keep in mind that the {{ic|--spice-host-subject}} parameter needs to be set according to your {{ic|server-cert.pem}} subject. You also need to copy {{ic|ca-cert.pem}} to every client to verify the server certificate.<br />
<br />
{{Tip|You can get the subject line of the server certificate in the correct format for {{ic|--spice-host-subject}} (with entries separated by commas) using the following command: {{bc|<nowiki>$ openssl x509 -noout -subject -in server-cert.pem | cut -d' ' -f2- | sed 's/\///' | sed 's/\//,/g'</nowiki>}}<br />
}}<br />
<br />
The equivalent {{Pkg|spice-gtk}} command is:<br />
<br />
$ spicy -h ''hostname'' -s 5901 --spice-ca-file=ca-cert.pem --spice-host-subject="C=''XX'',L=''city'',O=''organization'',CN=''hostname''" --spice-secure-channels=all<br />
<br />
== VNC ==<br />
<br />
One can add the {{ic|-vnc :''X''}} option to have QEMU redirect the VGA display to the VNC session. Substitute {{ic|''X''}} for the number of the display (0 will then listen on 5900, 1 on 5901...).<br />
<br />
$ qemu-system-x86_64 -vnc :0<br />
<br />
An example is also provided in the [[#Starting QEMU virtual machines on boot]] section.<br />
<br />
{{Warning|The default VNC server setup does not use any form of authentication. Any user can connect from any host.}}<br />
<br />
=== Basic password authentication ===<br />
<br />
An access password can be setup easily by using the {{ic|password}} option. The password must be indicated in the QEMU monitor and connection is only possible once the password is provided.<br />
<br />
$ qemu-system-x86_64 -vnc :0,password -monitor stdio<br />
<br />
In the QEMU monitor, password is set using the command {{ic|change vnc password}} and then indicating the password.<br />
<br />
The following command line directly runs vnc with a password:<br />
<br />
$ printf "change vnc password\n%s\n" MYPASSWORD | qemu-system-x86_64 -vnc :0,password -monitor stdio<br />
<br />
{{Note|The password is limited to 8 characters and can be guessed through brute force attack. More elaborated protection is strongly recommended for public network.}}<br />
<br />
== Audio ==<br />
<br />
=== Creating an audio backend ===<br />
<br />
The {{ic|-audiodev}} flag sets the audio backend driver on the host and its options.<br />
<br />
To list availabe audio backend drivers:<br />
<br />
$ qemu-system-x86_64 -audiodev help<br />
<br />
Their optional settings are detailed in the {{man|1|qemu}} man page.<br />
<br />
At the bare minimum, one need to choose an audio backend and set an id, for [[PulseAudio]] for example:<br />
<br />
-audiodev pa,id=snd0<br />
<br />
=== Using the audio backend ===<br />
<br />
==== Intel HD Audio ====<br />
<br />
For Intel HD Audio emulation, add both controller and codec devices. To list the available Intel HDA Audio devices:<br />
<br />
$ qemu-system-x86_64 -device help | grep hda<br />
<br />
Add the audio controller:<br />
<br />
-device ich9-intel-hda<br />
<br />
Also add the audio codec and map it to a host audio backend id:<br />
<br />
-device hda-output,audiodev=snd0<br />
<br />
==== Intel 82801AA AC97 ====<br />
<br />
For AC97 emulation just add the audio card device and map it to a host audio backend id<br />
<br />
-device AC97,audiodev=snd0<br />
<br />
{{Note|<br />
* If the audiodev backend is not provided, QEMU looks up for it and adds it automatically, this only works for a single audiodev. For example {{ic|-device intel-hda -device hda-duplex}} will emulate {{ic|intel-hda}} on the guest using the default audiodev backend.<br />
* Video graphic card emulated drivers for the guest machine may also cause a problem with the sound quality. Test one by one to make it work. You can list possible options with {{ic|<nowiki>qemu-system-x86_64 -h | grep vga</nowiki>}}.<br />
}}<br />
<br />
==== VirtIO-Sound ====<br />
<br />
VirtIO sound is also available since QEMU 8.2.0. The usage is:<br />
<br />
-device virtio-sound-pci,audiodev=my_audiodev \<br />
-audiodev alsa,id=my_audiodev<br />
<br />
More information can be found [https://qemu-project.gitlab.io/qemu/system/devices/virtio-snd.html here].<br />
<br />
== Installing virtio drivers ==<br />
<br />
QEMU offers guests the ability to use paravirtualized block and network devices using the [https://wiki.libvirt.org/page/Virtio virtio] drivers, which provide better performance and lower overhead.<br />
<br />
* A virtio block device requires the option {{ic|-drive}} for passing a disk image, with parameter {{ic|1=if=virtio}}:<br />
$ qemu-system-x86_64 -drive file=''disk_image'',if='''virtio'''<br />
<br />
* Almost the same goes for the network:<br />
$ qemu-system-x86_64 -nic user,model='''virtio-net-pci'''<br />
<br />
{{Note|This will only work if the guest machine has drivers for virtio devices. Linux does, and the required drivers are included in Arch Linux, but there is no guarantee that virtio devices will work with other operating systems.}}<br />
<br />
=== Preparing an Arch Linux guest ===<br />
<br />
To use virtio devices after an Arch Linux guest has been installed, the following modules must be loaded in the guest: {{ic|virtio}}, {{ic|virtio_pci}}, {{ic|virtio_blk}}, {{ic|virtio_net}}, and {{ic|virtio_ring}}. For 32-bit guests, the specific "virtio" module is not necessary.<br />
<br />
If you want to boot from a virtio disk, the initial ramdisk must contain the necessary modules. By default, this is handled by [[mkinitcpio]]'s {{ic|autodetect}} hook. Otherwise use the {{ic|MODULES}} array in {{ic|/etc/mkinitcpio.conf}} to include the necessary modules and rebuild the initial ramdisk.<br />
<br />
{{hc|/etc/mkinitcpio.conf|2=<br />
MODULES=(virtio virtio_blk virtio_pci virtio_net)}}<br />
<br />
Virtio disks are recognized with the prefix {{ic|'''v'''}} (e.g. {{ic|'''v'''da}}, {{ic|'''v'''db}}, etc.); therefore, changes must be made in at least {{ic|/etc/fstab}} and {{ic|/boot/grub/grub.cfg}} when booting from a virtio disk.<br />
<br />
{{Tip|When referencing disks by [[UUID]] in both {{ic|/etc/fstab}} and boot loader, nothing has to be done.}}<br />
<br />
Further information on paravirtualization with KVM can be found [https://www.linux-kvm.org/page/Boot_from_virtio_block_device here].<br />
<br />
You might also want to install {{Pkg|qemu-guest-agent}} to implement support for QMP commands that will enhance the hypervisor management capabilities.<br />
<br />
=== Preparing a Windows guest ===<br />
<br />
==== Virtio drivers for Windows ====<br />
<br />
Windows does not come with the virtio drivers. The latest and stable versions of the drivers are regularly built by Fedora, details on downloading the drivers are given on [https://github.com/virtio-win/virtio-win-pkg-scripts/blob/master/README.md virtio-win on GitHub]. In the following sections we will mostly use the stable ISO file provided here: [https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/stable-virtio/virtio-win.iso virtio-win.iso]. Alternatively, use {{AUR|virtio-win}}.<br />
<br />
==== Block device drivers ====<br />
<br />
===== New Install of Windows =====<br />
<br />
The drivers need to be loaded during installation, the procedure is to load the ISO image with the virtio drivers in a cdrom device along with the primary disk device and the Windows ISO install media:<br />
<br />
$ qemu-system-x86_64 ... \<br />
-drive file=''disk_image'',index=0,media=disk,if=virtio \<br />
-drive file=''windows.iso'',index=2,media=cdrom \<br />
-drive file=''virtio-win.iso'',index=3,media=cdrom \<br />
...<br />
<br />
During the installation, at some stage, the Windows installer will ask "Where do you want to install Windows?", it will give a warning that no disks are found. Follow the example instructions below (based on Windows Server 2012 R2 with Update).<br />
<br />
* Select the option ''Load Drivers''.<br />
* Uncheck the box for ''Hide drivers that are not compatible with this computer's hardware''.<br />
* Click the browse button and open the CDROM for the virtio iso, usually named "virtio-win-XX".<br />
* Now browse to {{ic|E:\viostor\[your-os]\amd64}}, select it, and confirm.<br />
<br />
You should now see your virtio disk(s) listed here, ready to be selected, formatted and installed to.<br />
<br />
===== Change existing Windows virtual machine to use virtio =====<br />
<br />
Modifying an existing Windows guest for booting from virtio disk requires that the virtio driver is loaded by the guest at boot time.<br />
We will therefore need to teach Windows to load the virtio driver at boot time before being able to boot a disk image in virtio mode.<br />
<br />
To achieve that, first create a new disk image that will be attached in virtio mode and trigger the search for the driver:<br />
<br />
$ qemu-img create -f qcow2 ''dummy.qcow2'' 1G<br />
<br />
Run the original Windows guest with the boot disk still in IDE mode, the fake disk in virtio mode and the driver ISO image.<br />
<br />
$ qemu-system-x86_64 -m 4G -drive file=''disk_image'',if=ide -drive file=''dummy.qcow2'',if=virtio -cdrom virtio-win.iso<br />
<br />
Windows will detect the fake disk and look for a suitable driver. If it fails, go to ''Device Manager'', locate the SCSI drive with an exclamation mark icon (should be open), click ''Update driver'' and select the virtual CD-ROM. Do not navigate to the driver folder within the CD-ROM, simply select the CD-ROM drive and Windows will find the appropriate driver automatically (tested for Windows 7 SP1).<br />
<br />
Request Windows to boot in safe mode next time it starts up. This can be done using the ''msconfig.exe'' tool in Windows. In safe mode all the drivers will be loaded at boot time including the new virtio driver. Once Windows knows that the virtio driver is required at boot it will memorize it for future boot.<br />
<br />
Once instructed to boot in safe mode, you can turn off the virtual machine and launch it again, now with the boot disk attached in virtio mode:<br />
<br />
$ qemu-system-x86_64 -m 4G -drive file=''disk_image'',if=virtio<br />
<br />
You should boot in safe mode with virtio driver loaded, you can now return to ''msconfig.exe'' disable safe mode boot and restart Windows.<br />
<br />
{{Note|If you encounter the blue screen of death using the {{ic|1=if=virtio}} parameter, it probably means the virtio disk driver is not installed or not loaded at boot time, reboot in safe mode and check your driver configuration.}}<br />
<br />
==== Network drivers ====<br />
<br />
Installing virtio network drivers is a bit easier, simply add the {{ic|-nic}} argument.<br />
<br />
$ qemu-system-x86_64 -m 4G -drive file=''windows_disk_image'',if=virtio -nic user,model=virtio-net-pci -cdrom virtio-win.iso<br />
<br />
Windows will detect the network adapter and try to find a driver for it. If it fails, go to the ''Device Manager'', locate the network adapter with an exclamation mark icon (should be open), click ''Update driver'' and select the virtual CD-ROM. Do not forget to select the checkbox which says to search for directories recursively.<br />
<br />
==== Balloon driver ====<br />
<br />
If you want to track you guest memory state (for example via {{ic|virsh}} command {{ic|dommemstat}}) or change guest's memory size in runtime (you still will not be able to change memory size, but can limit memory usage via inflating balloon driver) you will need to install guest balloon driver.<br />
<br />
For this you will need to go to ''Device Manager'', locate ''PCI standard RAM Controller'' in ''System devices'' (or unrecognized PCI controller from ''Other devices'') and choose ''Update driver''. In opened window you will need to choose ''Browse my computer...'' and select the CD-ROM (and do not forget the ''Include subdirectories'' checkbox). Reboot after installation. This will install the driver and you will be able to inflate the balloon (for example via hmp command {{ic|balloon ''memory_size''}}, which will cause balloon to take as much memory as possible in order to shrink the guest's available memory size to ''memory_size''). However, you still will not be able to track guest memory state. In order to do this you will need to install ''Balloon'' service properly. For that open command line as administrator, go to the CD-ROM, ''Balloon'' directory and deeper, depending on your system and architecture. Once you are in ''amd64'' (''x86'') directory, run {{ic|blnsrv.exe -i}} which will do the installation. After that {{ic|virsh}} command {{ic|dommemstat}} should be outputting all supported values.<br />
<br />
=== Preparing a FreeBSD guest ===<br />
<br />
Install the {{ic|emulators/virtio-kmod}} port if you are using FreeBSD 8.3 or later up until 10.0-CURRENT where they are included into the kernel. After installation, add the following to your {{ic|/boot/loader.conf}} file:<br />
<br />
{{bc|1=<br />
virtio_load="YES"<br />
virtio_pci_load="YES"<br />
virtio_blk_load="YES"<br />
if_vtnet_load="YES"<br />
virtio_balloon_load="YES"<br />
}}<br />
<br />
Then modify your {{ic|/etc/fstab}} by doing the following:<br />
<br />
# sed -ibak "s/ada/vtbd/g" /etc/fstab<br />
<br />
And verify that {{ic|/etc/fstab}} is consistent. If anything goes wrong, just boot into a rescue CD and copy {{ic|/etc/fstab.bak}} back to {{ic|/etc/fstab}}.<br />
<br />
== QEMU monitor ==<br />
<br />
While QEMU is running, a monitor console is provided in order to provide several ways to interact with the virtual machine running. The QEMU monitor offers interesting capabilities such as obtaining information about the current virtual machine, hotplugging devices, creating snapshots of the current state of the virtual machine, etc. To see the list of all commands, run {{ic|help}} or {{ic|?}} in the QEMU monitor console or review the relevant section of the [https://www.qemu.org/docs/master/system/monitor.html official QEMU documentation].<br />
<br />
=== Accessing the monitor console ===<br />
<br />
==== Graphical view ====<br />
<br />
When using the {{ic|std}} default graphics option, one can access the QEMU monitor by pressing {{ic|Ctrl+Alt+2}} or by clicking ''View > compatmonitor0'' in the QEMU window. To return to the virtual machine graphical view either press {{ic|Ctrl+Alt+1}} or click ''View > VGA''.<br />
<br />
However, the standard method of accessing the monitor is not always convenient and does not work in all graphic outputs QEMU supports.<br />
<br />
==== Telnet ====<br />
<br />
To enable [[telnet]], run QEMU with the {{ic|-monitor telnet:127.0.0.1:''port'',server,nowait}} parameter. When the virtual machine is started you will be able to access the monitor via telnet:<br />
<br />
$ telnet 127.0.0.1 ''port''<br />
<br />
{{Note|If {{ic|127.0.0.1}} is specified as the IP to listen it will be only possible to connect to the monitor from the same host QEMU is running on. If connecting from remote hosts is desired, QEMU must be told to listen {{ic|0.0.0.0}} as follows: {{ic|-monitor telnet:0.0.0.0:''port'',server,nowait}}. Keep in mind that it is recommended to have a [[firewall]] configured in this case or make sure your local network is completely trustworthy since this connection is completely unauthenticated and unencrypted.}}<br />
<br />
==== UNIX socket ====<br />
<br />
Run QEMU with the {{ic|-monitor unix:''socketfile'',server,nowait}} parameter. Then you can connect with either {{Pkg|socat}}, {{Pkg|nmap}} or {{Pkg|openbsd-netcat}}.<br />
<br />
For example, if QEMU is run via:<br />
<br />
$ qemu-system-x86_64 -monitor unix:/tmp/monitor.sock,server,nowait ''[...]''<br />
<br />
It is possible to connect to the monitor with:<br />
<br />
$ socat - UNIX-CONNECT:/tmp/monitor.sock<br />
<br />
Or with:<br />
<br />
$ nc -U /tmp/monitor.sock<br />
<br />
Alternatively with {{Pkg|nmap}}:<br />
<br />
$ ncat -U /tmp/monitor.sock<br />
<br />
==== TCP ====<br />
<br />
You can expose the monitor over TCP with the argument {{ic|-monitor tcp:127.0.0.1:''port'',server,nowait}}. Then connect with netcat, either {{Pkg|openbsd-netcat}} or {{Pkg|gnu-netcat}} by running:<br />
<br />
$ nc 127.0.0.1 ''port''<br />
<br />
{{Note|In order to be able to connect to the tcp socket from other devices other than the same host QEMU is being run on you need to listen to {{ic|0.0.0.0}} like explained in the telnet case. The same security warnings apply in this case as well.}}<br />
<br />
==== Standard I/O ====<br />
<br />
It is possible to access the monitor automatically from the same terminal QEMU is being run by running it with the argument {{ic|-monitor stdio}}.<br />
<br />
=== Sending keyboard presses to the virtual machine using the monitor console ===<br />
<br />
Some combinations of keys may be difficult to perform on virtual machines due to the host intercepting them instead in some configurations (a notable example is the {{ic|Ctrl+Alt+F*}} key combinations, which change the active tty). To avoid this problem, the problematic combination of keys may be sent via the monitor console instead. Switch to the monitor and use the {{ic|sendkey}} command to forward the necessary keypresses to the virtual machine. For example:<br />
<br />
(qemu) sendkey ctrl-alt-f2<br />
<br />
=== Creating and managing snapshots via the monitor console ===<br />
<br />
{{Note|This feature will '''only''' work when the virtual machine disk image is in ''qcow2'' format. It will not work with ''raw'' images.}}<br />
<br />
It is sometimes desirable to save the current state of a virtual machine and having the possibility of reverting the state of the virtual machine to that of a previously saved snapshot at any time. The QEMU monitor console provides the user with the necessary utilities to create snapshots, manage them, and revert the machine state to a saved snapshot.<br />
<br />
* Use {{ic|savevm ''name''}} in order to create a snapshot with the tag ''name''.<br />
* Use {{ic|loadvm ''name''}} to revert the virtual machine to the state of the snapshot ''name''.<br />
* Use {{ic|delvm ''name''}} to delete the snapshot tagged as ''name''.<br />
* Use {{ic|info snapshots}} to see a list of saved snapshots. Snapshots are identified by both an auto-incremented ID number and a text tag (set by the user on snapshot creation).<br />
<br />
=== Running the virtual machine in immutable mode ===<br />
<br />
It is possible to run a virtual machine in a frozen state so that all changes will be discarded when the virtual machine is powered off just by running QEMU with the {{ic|-snapshot}} parameter. When the disk image is written by the guest, changes will be saved in a temporary file in {{ic|/tmp}} and will be discarded when QEMU halts.<br />
<br />
However, if a machine is running in frozen mode it is still possible to save the changes to the disk image if it is afterwards desired by using the monitor console and running the following command:<br />
<br />
(qemu) commit all<br />
<br />
If snapshots are created when running in frozen mode they will be discarded as soon as QEMU is exited unless changes are explicitly commited to disk, as well.<br />
<br />
=== Pause and power options via the monitor console ===<br />
<br />
Some operations of a physical machine can be emulated by QEMU using some monitor commands:<br />
<br />
* {{ic|system_powerdown}} will send an ACPI shutdown request to the virtual machine. This effect is similar to the power button in a physical machine.<br />
* {{ic|system_reset}} will reset the virtual machine similarly to a reset button in a physical machine. This operation can cause data loss and file system corruption since the virtual machine is not cleanly restarted.<br />
* {{ic|stop}} will pause the virtual machine.<br />
* {{ic|cont}} will resume a virtual machine previously paused.<br />
<br />
=== Taking screenshots of the virtual machine ===<br />
<br />
Screenshots of the virtual machine graphic display can be obtained in the PPM format by running the following command in the monitor console:<br />
<br />
(qemu) screendump ''file.ppm''<br />
<br />
== QEMU machine protocol ==<br />
<br />
The QEMU machine protocol (QMP) is a JSON-based protocol which allows applications to control a QEMU instance. Similarly to the [[#QEMU monitor]] it offers ways to interact with a running machine and the JSON protocol allows to do it programmatically. The description of all the QMP commands can be found in [https://raw.githubusercontent.com/coreos/qemu/master/qmp-commands.hx qmp-commands].<br />
<br />
=== Start QMP ===<br />
<br />
The usual way to control the guest using the QMP protocol, is to open a TCP socket when launching the machine using the {{ic|-qmp}} option. Here it is using for example the TCP port 4444:<br />
<br />
$ qemu-system-x86_64 ''[...]'' -qmp tcp:localhost:4444,server,nowait<br />
<br />
Then one way to communicate with the QMP agent is to use [[netcat]]:<br />
<br />
{{hc|nc localhost 4444|{"QMP": {"version": {"qemu": {"micro": 0, "minor": 1, "major": 3}, "package": ""}, "capabilities": []} } }}<br />
<br />
At this stage, the only command that can be recognized is {{ic|qmp_capabilities}}, so that QMP enters into command mode. Type:<br />
<br />
{"execute": "qmp_capabilities"}<br />
<br />
Now, QMP is ready to receive commands, to retrieve the list of recognized commands, use:<br />
<br />
{"execute": "query-commands"}<br />
<br />
=== Live merging of child image into parent image ===<br />
<br />
It is possible to merge a running snapshot into its parent by issuing a {{ic|block-commit}} command. In its simplest form the following line will commit the child into its parent:<br />
<br />
{"execute": "block-commit", "arguments": {"device": "''devicename''"}}<br />
<br />
Upon reception of this command, the handler looks for the base image and converts it from read only to read write mode and then runs the commit job.<br />
<br />
Once the ''block-commit'' operation has completed, the event {{ic|BLOCK_JOB_READY}} will be emitted, signalling that the synchronization has finished. The job can then be gracefully completed by issuing the command {{ic|block-job-complete}}:<br />
<br />
{"execute": "block-job-complete", "arguments": {"device": "''devicename''"}}<br />
<br />
Until such a command is issued, the ''commit'' operation remains active.<br />
After successful completion, the base image remains in read write mode and becomes the new active layer. On the other hand, the child image becomes invalid and it is the responsibility of the user to clean it up.<br />
<br />
{{Tip|The list of device and their names can be retrieved by executing the command {{ic|query-block}} and parsing the results. The device name is in the {{ic|device}} field, for example {{ic|ide0-hd0}} for the hard disk in this example: {{hc|{"execute": "query-block"}|{"return": [{"io-status": "ok", "device": "'''ide0-hd0'''", "locked": false, "removable": false, "inserted": {"iops_rd": 0, "detect_zeroes": "off", "image": {"backing-image": {"virtual-size": 27074281472, "filename": "parent.qcow2", ... } }} }}<br />
<br />
=== Live creation of a new snapshot ===<br />
<br />
To create a new snapshot out of a running image, run the command:<br />
<br />
{"execute": "blockdev-snapshot-sync", "arguments": {"device": "''devicename''","snapshot-file": "''new_snapshot_name''.qcow2"}}<br />
<br />
This creates an overlay file named {{ic|''new_snapshot_name''.qcow2}} which then becomes the new active layer.<br />
<br />
== Tips and tricks ==<br />
<br />
=== Improve virtual machine performance ===<br />
<br />
There are a number of techniques that you can use to improve the performance of the virtual machine. For example:<br />
<br />
* Apply [[#Enabling KVM]] for full virtualization.<br />
* Use the {{ic|-cpu host}} option to make QEMU emulate the host's exact CPU rather than a more generic CPU.<br />
* Especially for Windows guests, enable [https://blog.wikichoon.com/2014/07/enabling-hyper-v-enlightenments-with-kvm.html Hyper-V enlightenments]: {{ic|1=-cpu host,hv_relaxed,hv_spinlocks=0x1fff,hv_vapic,hv_time}}. See the [https://www.qemu.org/docs/master/system/i386/hyperv.html QEMU documentation] for more information and flags.<br />
* multiple cores can be assigned to the guest using the {{ic|-smp cores{{=}}x,threads{{=}}y,sockets{{=}}1,maxcpus{{=}}z}} option. The threads parameter is used to assign [https://www.tomshardware.com/reviews/simultaneous-multithreading-definition,5762.html SMT cores]. Leaving a physical core for QEMU, the hypervisor and the host system to operate unimpeded is highly beneficial.<br />
* Make sure you have assigned the virtual machine enough memory. By default, QEMU only assigns 128 MiB of memory to each virtual machine. Use the {{ic|-m}} option to assign more memory. For example, {{ic|-m 1024}} runs a virtual machine with 1024 MiB of memory.<br />
* If supported by drivers in the guest operating system, use virtio for network and/or block devices, see [[#Installing virtio drivers]].<br />
* Use TAP devices instead of user-mode networking, see [[#Tap networking with QEMU]].<br />
* If the guest OS is doing heavy writing to its disk, you may benefit from certain mount options on the host's file system. For example, you can mount an [[Ext4|ext4 file system]] with the option {{ic|1=barrier=0}}. You should read the documentation for any options that you change because sometimes performance-enhancing options for file systems come at the cost of data integrity.<br />
* If you have a raw disk or partition, you may want to disable the cache: {{bc|1=$ qemu-system-x86_64 -drive file=/dev/''disk'',if=virtio,'''cache=none'''}}<br />
* Use the native Linux AIO: {{bc|1=$ qemu-system-x86_64 -drive file=''disk_image'',if=virtio''',aio=native,cache.direct=on'''}}<br />
* If you are running multiple virtual machines concurrently that all have the same operating system installed, you can save memory by enabling [[wikipedia:Kernel_SamePage_Merging_(KSM)|kernel same-page merging]]. See [[#Enabling KSM]].<br />
* In some cases, memory can be reclaimed from running virtual machines by running a memory ballooning driver in the guest operating system and launching QEMU using {{ic|-device virtio-balloon}}.<br />
* It is possible to use a emulation layer for an ICH-9 AHCI controller (although it may be unstable). The AHCI emulation supports [[Wikipedia:Native_Command_Queuing|NCQ]], so multiple read or write requests can be outstanding at the same time: {{bc|1=$ qemu-system-x86_64 -drive id=disk,file=''disk_image'',if=none -device ich9-ahci,id=ahci -device ide-drive,drive=disk,bus=ahci.0}}<br />
<br />
See https://www.linux-kvm.org/page/Tuning_KVM for more information.<br />
<br />
=== Starting QEMU virtual machines on boot ===<br />
<br />
==== With libvirt ====<br />
<br />
If a virtual machine is set up with [[libvirt]], it can be configured with {{ic|virsh autostart}} or through the ''virt-manager'' GUI to start at host boot by going to the Boot Options for the virtual machine and selecting "Start virtual machine on host boot up".<br />
<br />
==== With systemd service ====<br />
<br />
To run QEMU virtual machines on boot, you can use following systemd unit and config.<br />
<br />
{{hc|/etc/systemd/system/qemu@.service|2=<br />
[Unit]<br />
Description=QEMU virtual machine<br />
<br />
[Service]<br />
Environment="haltcmd=kill -INT $MAINPID"<br />
EnvironmentFile=/etc/conf.d/qemu.d/%i<br />
ExecStart=/usr/bin/qemu-system-x86_64 -name %i -enable-kvm -m 512 -nographic $args<br />
ExecStop=/usr/bin/bash -c ${haltcmd}<br />
ExecStop=/usr/bin/bash -c 'while nc localhost 7100; do sleep 1; done'<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
}}<br />
<br />
{{Note|This service will wait for the console port to be released, which means that the virtual machine has been shutdown, to graciously end.}}<br />
<br />
Then create per-VM configuration files, named {{ic|/etc/conf.d/qemu.d/''vm_name''}}, with the variables {{ic|args}} and {{ic|haltcmd}} set. Example configs:<br />
<br />
{{hc|/etc/conf.d/qemu.d/one|2=<br />
args="-hda /dev/vg0/vm1 -serial telnet:localhost:7000,server,nowait,nodelay \<br />
-monitor telnet:localhost:7100,server,nowait,nodelay -vnc :0"<br />
<br />
haltcmd="echo 'system_powerdown' {{!}} nc localhost 7100" # or netcat/ncat}}<br />
<br />
{{hc|/etc/conf.d/qemu.d/two|2=<br />
args="-hda /srv/kvm/vm2 -serial telnet:localhost:7001,server,nowait,nodelay -vnc :1"<br />
<br />
haltcmd="ssh powermanager@vm2 sudo poweroff"}}<br />
<br />
The description of the variables is the following:<br />
<br />
* {{ic|args}} - QEMU command line arguments to be used.<br />
* {{ic|haltcmd}} - Command to shut down a virtual machine safely. In the first example, the QEMU monitor is exposed via telnet using {{ic|-monitor telnet:..}} and the virtual machines are powered off via ACPI by sending {{ic|system_powerdown}} to monitor with the {{ic|nc}} command. In the other example, SSH is used.<br />
<br />
To set which virtual machines will start on boot-up, [[enable]] the {{ic|qemu@''vm_name''.service}} systemd unit.<br />
<br />
=== Mouse integration ===<br />
<br />
To prevent the mouse from being grabbed when clicking on the guest operating system's window, add the options {{ic|-usb -device usb-tablet}}. This means QEMU is able to report the mouse position without having to grab the mouse. This also overrides PS/2 mouse emulation when activated. For example:<br />
<br />
$ qemu-system-x86_64 -hda ''disk_image'' -m 512 -usb -device usb-tablet<br />
<br />
If that does not work, try using {{ic|-vga qxl}} parameter, also look at the instructions [[#Mouse cursor is jittery or erratic]].<br />
<br />
=== Pass-through host USB device ===<br />
<br />
It is possible to access the physical device connected to a USB port of the host from the guest. The first step is to identify where the device is connected, this can be found running the {{ic|lsusb}} command. For example:<br />
<br />
{{hc|$ lsusb|<br />
...<br />
Bus '''003''' Device '''007''': ID '''0781''':'''5406''' SanDisk Corp. Cruzer Micro U3<br />
}}<br />
<br />
The outputs in bold above will be useful to identify respectively the ''host_bus'' and ''host_addr'' or the ''vendor_id'' and ''product_id''.<br />
<br />
In qemu, the idea is to emulate an EHCI (USB 2) or XHCI (USB 1.1 USB 2 USB 3) controller with the option {{ic|1=-device usb-ehci,id=ehci}} or {{ic|1=-device qemu-xhci,id=xhci}} respectively and then attach the physical device to it with the option {{ic|1=-device usb-host,..}}. We will consider that ''controller_id'' is either {{ic|ehci}} or {{ic|xhci}} for the rest of this section.<br />
<br />
Then, there are two ways to connect to the USB of the host with qemu:<br />
<br />
# Identify the device and connect to it on any bus and address it is attached to on the host, the generic syntax is: {{bc|1=-device usb-host,bus=''controller_id''.0,vendorid=0x''vendor_id'',productid=0x''product_id''}}Applied to the device used in the example above, it becomes:{{bc|1=-device usb-ehci,id=ehci -device usb-host,bus=ehci.0,vendorid=0x'''0781''',productid=0x'''5406'''}}One can also add the {{ic|1=...,port=''port_number''}} setting to the previous option to specify in which physical port of the virtual controller the device should be attached, useful in the case one wants to add multiple USB devices to the virtual machine. Another option is to use the new {{ic|hostdevice}} property of {{ic|usb-host}} which is available since QEMU 5.1.0, the syntax is: {{bc|1=-device qemu-xhci,id=xhci -device usb-host,hostdevice=/dev/bus/usb/003/007}}<br />
# Attach whatever is connected to a given USB bus and address, the syntax is:{{bc|1=-device usb-host,bus=''controller_id''.0,hostbus=''host_bus'',host_addr=''host_addr''}}Applied to the bus and the address in the example above, it becomes:{{bc|1=-device usb-ehci,id=ehci -device usb-host,bus=ehci.0,hostbus='''3''',hostaddr='''7'''}}<br />
See [https://www.qemu.org/docs/master/system/devices/usb.html QEMU/USB emulation] for more information.<br />
{{Note|If you encounter permission errors when running QEMU, see [[udev#About udev rules]] for information on how to set permissions of the device.}}<br />
<br />
=== USB redirection with SPICE ===<br />
<br />
When using [[#SPICE]] it is possible to redirect USB devices from the client to the virtual machine without needing to specify them in the QEMU command. It is possible to configure the number of USB slots available for redirected devices (the number of slots will determine the maximum number of devices which can be redirected simultaneously). The main advantages of using SPICE for redirection compared to the previously-mentioned {{ic|-usbdevice}} method is the possibility of hot-swapping USB devices after the virtual machine has started, without needing to halt it in order to remove USB devices from the redirection or adding new ones. This method of USB redirection also allows us to redirect USB devices over the network, from the client to the server. In summary, it is the most flexible method of using USB devices in a QEMU virtual machine.<br />
<br />
We need to add one EHCI/UHCI controller per available USB redirection slot desired as well as one SPICE redirection channel per slot. For example, adding the following arguments to the QEMU command you use for starting the virtual machine in SPICE mode will start the virtual machine with three available USB slots for redirection:<br />
<br />
{{bc|1=<br />
-device ich9-usb-ehci1,id=usb \<br />
-device ich9-usb-uhci1,masterbus=usb.0,firstport=0,multifunction=on \<br />
-device ich9-usb-uhci2,masterbus=usb.0,firstport=2 \<br />
-device ich9-usb-uhci3,masterbus=usb.0,firstport=4 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev1 -device usb-redir,chardev=usbredirchardev1,id=usbredirdev1 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev2 -device usb-redir,chardev=usbredirchardev2,id=usbredirdev2 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev3 -device usb-redir,chardev=usbredirchardev3,id=usbredirdev3<br />
}}<br />
<br />
See [https://www.spice-space.org/usbredir.html SPICE/usbredir] for more information.<br />
<br />
Both {{ic|spicy}} from {{Pkg|spice-gtk}} (''Input > Select USB Devices for redirection'') and {{ic|remote-viewer}} from {{Pkg|virt-viewer}} (''File > USB device selection'') support this feature. Please make sure that you have installed the necessary SPICE Guest Tools on the virtual machine for this functionality to work as expected (see the [[#SPICE]] section for more information).<br />
<br />
{{Warning|Keep in mind that when a USB device is redirected from the client, it will not be usable from the client operating system itself until the redirection is stopped. It is specially important to never redirect the input devices (namely mouse and keyboard), since it will be then difficult to access the SPICE client menus to revert the situation, because the client will not respond to the input devices after being redirected to the virtual machine.}}<br />
<br />
==== Automatic USB forwarding with udev ====<br />
<br />
Normally, forwarded devices must be available at the boot time of the virtual machine to be forwarded. If that device is disconnected, it will not be forwarded anymore.<br />
<br />
You can use [[udev rule]]s to automatically attach a device when it comes online. Create a {{ic|hostdev}} entry somewhere on disk. [[chown]] it to root to prevent other users modifying it.<br />
<br />
{{hc|/usr/local/hostdev-mydevice.xml|2=<br />
<hostdev mode='subsystem' type='usb'><br />
<source><br />
<vendor id='0x03f0'/><br />
<product id='0x4217'/><br />
</source><br />
</hostdev><br />
}}<br />
<br />
Then create a ''udev'' rule which will attach/detach the device:<br />
<br />
{{hc|/usr/lib/udev/rules.d/90-libvirt-mydevice|2=<br />
ACTION=="add", \<br />
SUBSYSTEM=="usb", \<br />
ENV{ID_VENDOR_ID}=="03f0", \<br />
ENV{ID_MODEL_ID}=="4217", \<br />
RUN+="/usr/bin/virsh attach-device GUESTNAME /usr/local/hostdev-mydevice.xml"<br />
ACTION=="remove", \<br />
SUBSYSTEM=="usb", \<br />
ENV{ID_VENDOR_ID}=="03f0", \<br />
ENV{ID_MODEL_ID}=="4217", \<br />
RUN+="/usr/bin/virsh detach-device GUESTNAME /usr/local/hostdev-mydevice.xml"<br />
}}<br />
<br />
[https://rolandtapken.de/blog/2011-04/how-auto-hotplug-usb-devices-libvirt-vms-update-1 Source and further reading].<br />
<br />
=== Enabling KSM ===<br />
<br />
Kernel Samepage Merging (KSM) is a feature of the Linux kernel that allows for an application to register with the kernel to have its pages merged with other processes that also register to have their pages merged. The KSM mechanism allows for guest virtual machines to share pages with each other. In an environment where many of the guest operating systems are similar, this can result in significant memory savings.<br />
<br />
{{Note|Although KSM may reduce memory usage, it may increase CPU usage. Also note some security issues may occur, see [[Wikipedia:Kernel same-page merging]].}}<br />
<br />
To enable KSM:<br />
<br />
# echo 1 > /sys/kernel/mm/ksm/run<br />
<br />
To make it permanent, use [[systemd#systemd-tmpfiles - temporary files|systemd's temporary files]]:<br />
<br />
{{hc|/etc/tmpfiles.d/ksm.conf|<br />
w /sys/kernel/mm/ksm/run - - - - 1<br />
}}<br />
<br />
If KSM is running, and there are pages to be merged (i.e. at least two similar virtual machines are running), then {{ic|/sys/kernel/mm/ksm/pages_shared}} should be non-zero. See https://docs.kernel.org/admin-guide/mm/ksm.html for more information.<br />
<br />
{{Tip|An easy way to see how well KSM is performing is to simply print the contents of all the files in that directory:<br />
<br />
$ grep -r . /sys/kernel/mm/ksm/<br />
<br />
}}<br />
<br />
=== Multi-monitor support ===<br />
<br />
The Linux QXL driver supports four heads (virtual screens) by default. This can be changed via the {{ic|1=qxl.heads=N}} kernel parameter.<br />
<br />
The default VGA memory size for QXL devices is 16M (VRAM size is 64M). This is not sufficient if you would like to enable two 1920x1200 monitors since that requires 2 × 1920 × 4 (color depth) × 1200 = 17.6 MiB VGA memory. This can be changed by replacing {{ic|-vga qxl}} by {{ic|<nowiki>-vga none -device qxl-vga,vgamem_mb=32</nowiki>}}. If you ever increase vgamem_mb beyond 64M, then you also have to increase the {{ic|vram_size_mb}} option.<br />
<br />
=== Custom display resolution ===<br />
<br />
A custom display resolution can be set with {{ic|1=-device VGA,edid=on,xres=1280,yres=720}} (see [[wikipedia:Extended_Display_Identification_Data|EDID]] and [[wikipedia:Display_resolution|display resolution]]).<br />
<br />
=== Copy and paste ===<br />
<br />
==== SPICE ====<br />
<br />
One way to share the clipboard between the host and the guest is to enable the SPICE remote desktop protocol and access the client with a SPICE client.<br />
One needs to follow the steps described in [[#SPICE]]. A guest run this way will support copy paste with the host.<br />
<br />
==== qemu-vdagent ====<br />
<br />
QEMU provides its own implementation of the spice vdagent chardev called {{ic|qemu-vdagent}}. It interfaces with the spice-vdagent guest service and allows the guest and host share a clipboard.<br />
<br />
To access this shared clipboard with QEMU's GTK display, you will need to [[#Custom build|compile QEMU from source]] with the {{ic|--enable-gtk-clipboard}} configure parameter. It is sufficient to replace the installed {{ic|qemu-ui-gtk}} package.<br />
<br />
{{Note|<br />
* Feature request {{Bug|79716}} submitted to enable the functionality in the official package.<br />
* The shared clipboard in qemu-ui-gtk has been pushed back to experimental as it can [https://gitlab.com/qemu-project/qemu/-/issues/1150 freeze guests under certain circumstances]. A fix has been proposed to solve the issue upstream.<br />
}}<br />
<br />
Add the following QEMU command line arguments:<br />
<br />
-device virtio-serial,packed=on,ioeventfd=on<br />
-device virtserialport,name=com.redhat.spice.0,chardev=vdagent0<br />
-chardev qemu-vdagent,id=vdagent0,name=vdagent,clipboard=on,mouse=off<br />
<br />
These arguments are also valid if converted to [[Libvirt#QEMU command line arguments|libvirt form]].<br />
<br />
{{Note|While the spicevmc chardev will start the spice-vdagent service of the guest automatically, the qemu-vdagent chardev may not.}}<br />
<br />
On linux guests, you may [[start]] the {{ic|spice-vdagent.service}} [[user unit]] manually. On Windows guests, set the spice-agent startup type to automatic.<br />
<br />
=== Windows-specific notes ===<br />
<br />
QEMU can run any version of Windows from Windows 95 through Windows 11.<br />
<br />
It is possible to run [[Windows PE]] in QEMU.<br />
<br />
==== Fast startup ====<br />
<br />
{{Note|An administrator account is required to change power settings.}}<br />
<br />
For Windows 8 (or later) guests it is better to disable "Turn on fast startup (recommended)" from the Power Options of the Control Panel as explained in the following [https://www.tenforums.com/tutorials/4189-turn-off-fast-startup-windows-10-a.html forum page], as it causes the guest to hang during every other boot.<br />
<br />
Fast Startup may also need to be disabled for changes to the {{ic|-smp}} option to be properly applied.<br />
<br />
==== Remote Desktop Protocol ====<br />
<br />
If you use a MS Windows guest, you might want to use RDP to connect to your guest virtual machine. If you are using a VLAN or are not in the same network as the guest, use:<br />
<br />
$ qemu-system-x86_64 -nographic -nic user,hostfwd=tcp::5555-:3389<br />
<br />
Then connect with either {{Pkg|rdesktop}} or {{Pkg|freerdp}} to the guest. For example:<br />
<br />
$ xfreerdp -g 2048x1152 localhost:5555 -z -x lan<br />
<br />
=== Clone Linux system installed on physical equipment ===<br />
<br />
Linux system installed on physical equipment can be cloned for running on a QEMU virtual machine. See [https://coffeebirthday.wordpress.com/2018/09/14/clone-linux-system-for-qemu-virtual-machine/ Clone Linux system from hardware for QEMU virtual machine]<br />
<br />
=== Chrooting into arm/arm64 environment from x86_64 ===<br />
<br />
Sometimes it is easier to work directly on a disk image instead of the real ARM based device. This can be achieved by mounting an SD card/storage containing the ''root'' partition and chrooting into it.<br />
<br />
Another use case for an ARM chroot is building ARM packages on an x86_64 machine. Here, the chroot environment can be created from an image tarball from [https://archlinuxarm.org Arch Linux ARM] - see [https://nerdstuff.org/posts/2020/2020-003_simplest_way_to_create_an_arm_chroot/] for a detailed description of this approach.<br />
<br />
Either way, from the chroot it should be possible to run ''pacman'' and install more packages, compile large libraries etc. Since the executables are for the ARM architecture, the translation to x86 needs to be performed by [[QEMU]].<br />
<br />
Install {{Pkg|qemu-user-static}} on the x86_64 machine/host, and {{Pkg|qemu-user-static-binfmt}} to register the qemu binaries to binfmt service.<br />
<br />
''qemu-user-static'' is used to allow the execution of compiled programs from other architectures. This is similar to what is provided by {{Pkg|qemu-emulators-full}}, but the "static" variant is required for chroot. Examples:<br />
<br />
qemu-arm-static path_to_sdcard/usr/bin/ls<br />
qemu-aarch64-static path_to_sdcard/usr/bin/ls<br />
<br />
These two lines execute the {{ic|ls}} command compiled for 32-bit ARM and 64-bit ARM respectively. Note that this will not work without chrooting, because it will look for libraries not present in the host system.<br />
<br />
{{Pkg|qemu-user-static}} allows automatically prefixing the ARM exectuable with {{ic|qemu-arm-static}} or {{ic|qemu-aarch64-static}}.<br />
<br />
Make sure that the ARM executable support is active:<br />
<br />
{{hc|$ ls /proc/sys/fs/binfmt_misc|<br />
qemu-aarch64 qemu-arm qemu-cris qemu-microblaze qemu-mipsel qemu-ppc64 qemu-riscv64 qemu-sh4 qemu-sparc qemu-sparc64 status<br />
qemu-alpha qemu-armeb qemu-m68k qemu-mips qemu-ppc qemu-ppc64abi32 qemu-s390x qemu-sh4eb qemu-sparc32plus register<br />
}}<br />
<br />
Each executable must be listed.<br />
<br />
If it is not active, [[restart]] {{ic|systemd-binfmt.service}}.<br />
<br />
Mount the SD card to {{ic|/mnt/sdcard}} (the device name may be different).<br />
<br />
# mount --mkdir /dev/mmcblk0p2 /mnt/sdcard<br />
<br />
Mount boot partition if needed (again, use the suitable device name):<br />
<br />
# mount /dev/mmcblk0p1 /mnt/sdcard/boot<br />
<br />
Finally ''chroot'' into the SD card root as described in [[Change root#Using chroot]]:<br />
<br />
# chroot /mnt/sdcard /bin/bash<br />
<br />
Alternatively, you can use ''arch-chroot'' from {{Pkg|arch-install-scripts}}, as it will provide an easier way to get network support:<br />
<br />
# arch-chroot /mnt/sdcard /bin/bash<br />
<br />
You can also use [[systemd-nspawn]] to chroot into the ARM environment:<br />
<br />
# systemd-nspawn -D /mnt/sdcard -M myARMMachine --bind-ro=/etc/resolv.conf<br />
<br />
{{ic|1=--bind-ro=/etc/resolv.conf}} is optional and gives a working network DNS inside the chroot<br />
<br />
==== sudo in chroot ====<br />
<br />
If you install [[sudo]] in the chroot and receive the following error when trying to use it:<br />
<br />
sudo: effective uid is not 0, is /usr/bin/sudo on a file system with the 'nosuid' option set or an NFS file system without root privileges?<br />
<br />
then you may need to modify the binfmt flags, for example for {{ic|aarch64}}:<br />
<br />
# cp /usr/lib/binfmt.d/qemu-aarch64-static.conf /etc/binfmt.d/<br />
# vi /etc/binfmt.d/qemu-aarch64-static.conf<br />
<br />
and add a {{ic|C}} at the end of this file:<br />
<br />
:qemu-aarch64:M::\x7fELF\x02\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\xb7\x00:\xff\xff\xff\xff\xff\xff\xff\x00\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff\xff:/usr/bin/qemu-aarch64-static:FPC<br />
<br />
Then [[restart]] {{ic|systemd-binfmt.service}} and check that the changes have taken effect (note the {{ic|C}} on the {{ic|flags}} line):<br />
<br />
{{hc|# cat /proc/sys/fs/binfmt_misc/qemu-aarch64|<br />
enabled<br />
interpreter /usr/bin/qemu-aarch64-static<br />
flags: POCF<br />
offset 0<br />
magic 7f454c460201010000000000000000000200b700<br />
mask ffffffffffffff00fffffffffffffffffeffffff<br />
}}<br />
<br />
See the "flags" section of the [https://docs.kernel.org/admin-guide/binfmt-misc.html kernel binfmt documentation] for more information.<br />
<br />
=== Not grabbing mouse input ===<br />
<br />
{{Style|It is not explained what the option actually does. Is it causing or avoiding the side effect?}}<br />
<br />
Tablet mode has side effect of not grabbing mouse input in QEMU window:<br />
<br />
-usb -device usb-tablet<br />
<br />
It works with several {{ic|-vga}} backends one of which is virtio.<br />
<br />
== Troubleshooting ==<br />
<br />
{{Merge|QEMU/Troubleshooting|This section is long enough to be split into a dedicated subpage.}}<br />
<br />
=== Mouse cursor is jittery or erratic ===<br />
<br />
If the cursor jumps around the screen uncontrollably, entering this on the terminal before starting QEMU might help:<br />
<br />
$ export SDL_VIDEO_X11_DGAMOUSE=0<br />
<br />
If this helps, you can add this to your {{ic|~/.bashrc}} file.<br />
<br />
=== No visible Cursor ===<br />
<br />
Add {{ic|1=-display default,show-cursor=on}} to QEMU's options to see a mouse cursor.<br />
<br />
If that still does not work, make sure you have set your display device appropriately, for example: {{ic|-vga qxl}}.<br />
<br />
Another option to try is {{ic|-usb -device usb-tablet}} as mentioned in [[#Mouse integration]]. This overrides the default PS/2 mouse emulation and synchronizes pointer location between host and guest as an added bonus.<br />
<br />
=== Two different mouse cursors are visible ===<br />
<br />
Apply the tip [[#Mouse integration]].<br />
<br />
=== Keyboard issues when using VNC ===<br />
<br />
When using VNC, you might experience keyboard problems described (in gory details) [https://www.berrange.com/posts/2010/07/04/more-than-you-or-i-ever-wanted-to-know-about-virtual-keyboard-handling/ here]. The solution is ''not'' to use the {{ic|-k}} option on QEMU, and to use {{ic|gvncviewer}} from {{Pkg|gtk-vnc}}. See also [https://www.mail-archive.com/libvir-list@redhat.com/msg13340.html this] message posted on libvirt's mailing list.<br />
<br />
=== Keyboard seems broken or the arrow keys do not work ===<br />
<br />
Should you find that some of your keys do not work or "press" the wrong key (in particular, the arrow keys), you likely need to specify your keyboard layout as an option. The keyboard layouts can be found in {{ic|/usr/share/qemu/keymaps/}}.<br />
<br />
$ qemu-system-x86_64 -k ''keymap'' ''disk_image''<br />
<br />
=== Could not read keymap file ===<br />
<br />
qemu-system-x86_64: -display vnc=0.0.0.0:0: could not read keymap file: 'en'<br />
<br />
is caused by an invalid ''keymap'' passed to the {{ic|-k}} argument. For example, {{ic|en}} is invalid, but {{ic|en-us}} is valid - see {{ic|/usr/share/qemu/keymaps/}}.<br />
<br />
=== Guest display stretches on window resize ===<br />
<br />
To restore default window size, press {{ic|Ctrl+Alt+u}}.<br />
<br />
=== ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy ===<br />
<br />
If an error message like this is printed when starting QEMU with {{ic|-enable-kvm}} option:<br />
<br />
ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy<br />
failed to initialize KVM: Device or resource busy<br />
<br />
that means another [[hypervisor]] is currently running. It is not recommended or possible to run several hypervisors in parallel.<br />
<br />
=== libgfapi error message ===<br />
<br />
The error message displayed at startup:<br />
<br />
Failed to open module: libgfapi.so.0: cannot open shared object file: No such file or directory<br />
<br />
[[Install]] {{Pkg|glusterfs}} or ignore the error message as GlusterFS is a optional dependency.<br />
<br />
=== Kernel panic on LIVE-environments ===<br />
<br />
If you start a live-environment (or better: booting a system) you may encounter this:<br />
<br />
[ end Kernel panic - not syncing: VFS: Unable to mount root fs on unknown block(0,0)<br />
<br />
or some other boot hindering process (e.g. cannot unpack initramfs, cant start service foo).<br />
Try starting the virtual machine with the {{ic|-m VALUE}} switch and an appropriate amount of RAM, if the ram is to low you will probably encounter similar issues as above/without the memory-switch.<br />
<br />
=== Windows 7 guest suffers low-quality sound ===<br />
<br />
Using the {{ic|hda}} audio driver for Windows 7 guest may result in low-quality sound. Changing the audio driver to {{ic|ac97}} by passing the {{ic|-soundhw ac97}} arguments to QEMU and installing the AC97 driver from [https://www.realtek.com/en/component/zoo/category/pc-audio-codecs-ac-97-audio-codecs-software Realtek AC'97 Audio Codecs] in the guest may solve the problem. See [https://bugzilla.redhat.com/show_bug.cgi?id=1176761#c16 Red Hat Bugzilla – Bug 1176761] for more information.<br />
<br />
=== Could not access KVM kernel module: Permission denied ===<br />
<br />
If you encounter the following error:<br />
<br />
libvirtError: internal error: process exited while connecting to monitor: Could not access KVM kernel module: Permission denied failed to initialize KVM: Permission denied<br />
<br />
Systemd 234 assigns a dynamic ID for the {{ic|kvm}} group (see {{Bug|54943}}). To avoid this error, you need edit the file {{ic|/etc/libvirt/qemu.conf}} and change the line with {{ic|1=group = "78"}} to {{ic|1=group = "kvm"}}.<br />
<br />
=== "System Thread Exception Not Handled" when booting a Windows virtual machine ===<br />
<br />
Windows 8 or Windows 10 guests may raise a generic compatibility exception at boot, namely "System Thread Exception Not Handled", which tends to be caused by legacy drivers acting strangely on real machines. On KVM machines this issue can generally be solved by setting the CPU model to {{ic|core2duo}}.<br />
<br />
=== Certain Windows games/applications crashing/causing a bluescreen ===<br />
<br />
Occasionally, applications running in the virtual machine may crash unexpectedly, whereas they would run normally on a physical machine. If, while running {{ic|dmesg -wH}} as root, you encounter an error mentioning {{ic|MSR}}, the reason for those crashes is that KVM injects a [[wikipedia:General protection fault|General protection fault]] (GPF) when the guest tries to access unsupported [[wikipedia:Model-specific register|Model-specific registers]] (MSRs) - this often results in guest applications/OS crashing. A number of those issues can be solved by passing the {{ic|1=ignore_msrs=1}} option to the KVM module, which will ignore unimplemented MSRs.<br />
<br />
{{hc|/etc/modprobe.d/kvm.conf|2=<br />
...<br />
options kvm ignore_msrs=1<br />
...<br />
}}<br />
<br />
Cases where adding this option might help:<br />
<br />
* GeForce Experience complaining about an unsupported CPU being present.<br />
* StarCraft 2 and L.A. Noire reliably blue-screening Windows 10 with {{ic|KMODE_EXCEPTION_NOT_HANDLED}}. The blue screen information does not identify a driver file in these cases.<br />
<br />
{{Warning|While this is normally safe and some applications might not work without this, silently ignoring unknown MSR accesses could potentially break other software within the virtual machine or other virtual machine.}}<br />
<br />
=== Applications in the virtual machine experience long delays or take a long time to start ===<br />
<br />
{{Out of date|No longer true since kernel 5.6}}<br />
<br />
This may be caused by insufficient available entropy in the virtual machine. Consider allowing the guest to access the hosts's entropy pool by adding a [https://wiki.qemu.org/Features/VirtIORNG VirtIO RNG device] to the virtual machine, or by installing an entropy generating daemon such as [[Haveged]].<br />
<br />
Anecdotally, OpenSSH takes a while to start accepting connections under insufficient entropy, without the logs revealing why.<br />
<br />
=== High interrupt latency and microstuttering ===<br />
<br />
This problem manifests itself as small pauses (stutters) and is particularly noticeable in graphics-intensive applications, such as games.<br />
<br />
* One of the causes is CPU power saving features, which are controlled by [[CPU frequency scaling]]. Change this to {{ic|performance}} for all processor cores. <br />
* Another possible cause is PS/2 inputs. Switch from PS/2 to Virtio inputs, see [[PCI passthrough via OVMF#Passing keyboard/mouse via Evdev]].<br />
<br />
=== QXL video causes low resolution ===<br />
<br />
QEMU 4.1.0 introduced a regression where QXL video can fall back to low resolutions, when being displayed through spice. [https://bugs.launchpad.net/qemu/+bug/1843151] For example, when KMS starts, text resolution may become as low as 4x10 characters. When trying to increase GUI resolution, it may go to the lowest supported resolution.<br />
<br />
As a workaround, create your device in this form:<br />
<br />
-device qxl-vga,max_outputs=1...<br />
<br />
=== Virtual machine not booting when using a Secure Boot enabled OVMF ===<br />
<br />
{{ic|OVMF_CODE.secboot.4m.fd}} and {{ic|OVMF_CODE.secboot.fd}} files from {{Pkg|edk2-ovmf}} are built with [[Wikipedia:System Management Mode|SMM]] support. If S3 support is not disabled in the virtual machine, then the virtual machine might not boot at all.<br />
<br />
Add the {{ic|1=-global ICH9-LPC.disable_s3=1}} option to the ''qemu'' command.<br />
<br />
See {{Bug|59465}} and https://github.com/tianocore/edk2/blob/master/OvmfPkg/README for more details and the required options to use Secure Boot in QEMU.<br />
<br />
=== Virtual machine not booting into Arch ISO ===<br />
<br />
When trying to boot the virtual machine for the first time from an Arch ISO image, the boot process hangs. Adding {{ic|1=console=ttyS0}} to kernel boot options by pressing {{ic|e}} in the boot menu you will get more boot messages and the following error:<br />
<br />
:: Mounting '/dev/disk/by-label/ARCH_202204' to '/run/archiso/bootmnt'<br />
Waiting 30 seconds for device /dev/disk/by-label/ARCH_202204 ...<br />
ERROR: '/dev/disk/by-label/ARCH_202204' device did not show up after 30 seconds...<br />
Falling back to interactive prompt<br />
You can try to fix the problem manually, log out when you are finished<br />
sh: can't access tty; job control turned off<br />
<br />
The error message does not give a good clue as to what the real issue is. The problem is with the default 128MB of RAM that QEMU allocates to the virtual machine. Increasing the limit to 1024MB with {{ic|-m 1024}} solves the issue and lets the system boot. You can continue installing Arch Linux as usual after that. Once the installation is complete, the memory allocation for the virtual machine can be decreased. The need for 1024MB is due to RAM disk requirements and size of the installation media. See [https://lists.archlinux.org/archives/list/arch-releng@lists.archlinux.org/message/D5HSGOFTPGYI6IZUEB3ZNAX4D3F3ID37/ this message on the arch-releng mailing list] and [https://bbs.archlinux.org/viewtopic.php?id=204023 this forum thread].<br />
<br />
=== Guest CPU interrupts are not firing ===<br />
<br />
If you are writing your own operating system by following the [https://wiki.osdev.org/ OSDev wiki], or are simply getting stepping through the guest architecture assembly code using QEMU's {{ic|gdb}} interface using the {{ic|-s}} flag, it is useful to know that many emulators, QEMU included, usually implement some CPU interrupts leaving many hardware interrupts unimplemented. One way to know if your code is firing an interrupt, is by using:<br />
<br />
-d int<br />
<br />
to enable showing interrupts/exceptions on stdout.<br />
<br />
To see what other guest debugging features QEMU has to offer, see:<br />
<br />
qemu-system-x86_64 -d help<br />
<br />
or replace {{ic|x86_64}} for your chosen guest architecture.<br />
<br />
=== KDE with sddm does not start spice-vdagent at login automatically ===<br />
<br />
Remove or comment out {{ic|X-GNOME-Autostart-Phase{{=}}WindowManager}} from {{ic|/etc/xdg/autostart/spice-vdagent.desktop}}. [https://github.com/systemd/systemd/issues/18791]<br />
<br />
=== Error starting domain: Requested operation is not valid: network 'default' is not active ===<br />
<br />
If for any reason the default network is deactivated, you will not be able to start any guest virtual machines which are configured to use the network. Your first attempt can be simply trying to start the network with virsh.<br />
<br />
# virsh net-start default<br />
<br />
For additional troubleshooting steps, see [https://www.xmodulo.com/network-default-is-not-active.html].<br />
<br />
== See also ==<br />
<br />
* [https://qemu.org Official QEMU website]<br />
* [https://www.linux-kvm.org Official KVM website]<br />
* [https://qemu.weilnetz.de/doc/6.0/ QEMU Emulator User Documentation]<br />
* [[Wikibooks:QEMU|QEMU Wikibook]]<br />
* [http://alien.slackbook.org/dokuwiki/doku.php?id=slackware:qemu Hardware virtualization with QEMU] by AlienBOB (last updated in 2008)<br />
* [http://blog.falconindy.com/articles/build-a-virtual-army.html Building a Virtual Army] by Falconindy<br />
* [https://git.qemu.org/?p=qemu.git;a=tree;f=docs Lastest docs]<br />
* [https://qemu.weilnetz.de/ QEMU on Windows]<br />
* [[wikipedia:Qemu|Wikipedia]]<br />
* [[debian:QEMU|Debian Wiki - QEMU]]<br />
* [https://people.gnome.org/~markmc/qemu-networking.html QEMU Networking on gnome.org]{{Dead link|2022|09|22|status=404}}<br />
* [http://bsdwiki.reedmedia.net/wiki/networking_qemu_virtual_bsd_systems.html Networking QEMU Virtual BSD Systems]<br />
* [https://www.gnu.org/software/hurd/hurd/running/qemu.html QEMU on gnu.org]<br />
* [https://wiki.freebsd.org/qemu QEMU on FreeBSD as host]<br />
* [https://wiki.mikejung.biz/KVM_/_Xen KVM/QEMU Virtio Tuning and SSD VM Optimization Guide]{{Dead link|2022|09|22|status=404}}<br />
* [https://doc.opensuse.org/documentation/leap/virtualization/html/book-virt/part-virt-qemu.html Managing Virtual Machines with QEMU - openSUSE documentation]<br />
* [https://www.ibm.com/support/knowledgecenter/en/linuxonibm/liaat/liaatkvm.htm KVM on IBM Knowledge Center]</div>Malcontenthttps://wiki.archlinux.org/index.php?title=QEMU&diff=795980QEMU2024-01-04T00:57:32Z<p>Malcontent: VirtIO sound</p>
<hr />
<div>[[Category:Emulation]]<br />
[[Category:Hypervisors]]<br />
[[de:QEMU]]<br />
[[es:QEMU]]<br />
[[fr:QEMU]]<br />
[[ja:QEMU]]<br />
[[zh-hans:QEMU]]<br />
{{Related articles start}}<br />
{{Related|:Category:Hypervisors}}<br />
{{Related|Libvirt}}<br />
{{Related|QEMU/Guest graphics acceleration}}<br />
{{Related|PCI passthrough via OVMF}}<br />
{{Related articles end}}<br />
<br />
According to the [https://wiki.qemu.org/Main_Page QEMU about page], "QEMU is a generic and open source machine emulator and virtualizer."<br />
<br />
When used as a machine emulator, QEMU can run OSes and programs made for one machine (e.g. an ARM board) on a different machine (e.g. your x86 PC). By using dynamic translation, it achieves very good performance.<br />
<br />
QEMU can use other hypervisors like [[Xen]] or [[KVM]] to use CPU extensions ([[Wikipedia:Hardware-assisted virtualization|HVM]]) for virtualization. When used as a virtualizer, QEMU achieves near native performances by executing the guest code directly on the host CPU.<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|qemu-full}} package (or {{Pkg|qemu-base}} for the version without GUI) and below optional packages for your needs:<br />
<br />
* {{Pkg|qemu-block-gluster}} - [[Glusterfs]] block support<br />
* {{Pkg|qemu-block-iscsi}} - [[iSCSI]] block support<br />
* {{Pkg|samba}} - [[Samba|SMB/CIFS]] server support<br />
<br />
Alternatively, {{Pkg|qemu-user-static}} exists as a usermode and static variant.<br />
<br />
=== QEMU variants ===<br />
<br />
QEMU is offered in several variants suited for different use cases.<br />
<br />
As a first classification, QEMU is offered in full-system and usermode emulation modes:<br />
<br />
; Full-system emulation<br />
: In this mode, QEMU emulates a full system, including one or several processors and various peripherals. It is more accurate but slower, and does not require the emulated OS to be Linux.<br />
: QEMU commands for full-system emulation are named {{ic|qemu-system-''target_architecture''}}, e.g. {{ic|qemu-system-x86_64}} for emulating [[Wikipedia:x86_64|x86_64]] CPUs, {{ic|qemu-system-i386}} for Intel [[Wikipedia:i386|32-bit x86]] CPUs, {{ic|qemu-system-arm}} for [[Wikipedia:ARM architecture family#32-bit architecture|ARM (32 bits)]], {{ic|qemu-system-aarch64}} for [[Wikipedia:AArch64|ARM64]], etc.<br />
: If the target architecture matches the host CPU, this mode may still benefit from a significant speedup by using a hypervisor like [[#Enabling KVM|KVM]] or Xen.<br />
; [https://www.qemu.org/docs/master/user/main.html Usermode emulation]<br />
: In this mode, QEMU is able to invoke a Linux executable compiled for a (potentially) different architecture by leveraging the host system resources. There may be compatibility issues, e.g. some features may not be implemented, dynamically linked executables will not work out of the box (see [[#Chrooting into arm/arm64 environment from x86_64]] to address this) and only Linux is supported (although [https://wiki.winehq.org/Emulation Wine may be used] for running Windows executables).<br />
: QEMU commands for usermode emulation are named {{ic|qemu-''target_architecture''}}, e.g. {{ic|qemu-x86_64}} for emulating 64-bit CPUs.<br />
<br />
QEMU is offered in dynamically-linked and statically-linked variants:<br />
<br />
; Dynamically-linked (default): {{ic|qemu-*}} commands depend on the host OS libraries, so executables are smaller.<br />
; Statically-linked: {{ic|qemu-*}} commands can be copied to any Linux system with the same architecture.<br />
<br />
In the case of Arch Linux, full-system emulation is offered as:<br />
<br />
; Non-headless (default): This variant enables GUI features that require additional dependencies (like SDL or GTK).<br />
; Headless: This is a slimmer variant that does not require GUI (this is suitable e.g. for servers).<br />
<br />
Note that headless and non-headless versions install commands with the same name (e.g. {{ic|qemu-system-x86_64}}) and thus cannot be both installed at the same time.<br />
<br />
=== Details on packages available in Arch Linux ===<br />
<br />
* The {{Pkg|qemu-desktop}} package provides the {{ic|x86_64}} architecture emulators for full-system emulation ({{ic|qemu-system-x86_64}}). The {{Pkg|qemu-emulators-full}} package provides the {{ic|x86_64}} usermode variant ({{ic|qemu-x86_64}}) and also for the rest of supported architectures it includes both full-system and usermode variants (e.g. {{ic|qemu-system-arm}} and {{ic|qemu-arm}}).<br />
* The headless versions of these packages (only applicable to full-system emulation) are {{Pkg|qemu-base}} ({{ic|x86_64}}-only) and {{Pkg|qemu-emulators-full}} (rest of architectures).<br />
* Full-system emulation can be expanded with some QEMU modules present in separate packages: {{Pkg|qemu-block-gluster}}, {{Pkg|qemu-block-iscsi}} and {{Pkg|qemu-guest-agent}}.<br />
* {{Pkg|qemu-user-static}} provides a usermode and static variant for all target architectures supported by QEMU. The installed QEMU commands are named {{ic|qemu-''target_architecture''-static}}, for example, {{ic|qemu-x86_64-static}} for intel 64-bit CPUs.<br />
<br />
{{Note|At present, Arch does not offer a full-system mode and statically linked variant (neither officially nor via AUR), as this is usually not needed.}}<br />
<br />
=== Custom build ===<br />
<br />
{{Remove|Explaining how to use the [[Arch build system]] is out of scope here. There is no motivation for the customization in the first place.}}<br />
<br />
To obtain a customized version of QEMU, [[Git#Getting a Git repository|clone]] the package source of {{Pkg|qemu-common}} or {{AUR|qemu-git}}.<br />
<br />
The respective [[PKGBUILD]] file calls QEMU's [https://www.gnu.org/prep/standards/html_node/Configuration.html configure script] which accepts parameters obtainable by first manually running --help on it. <br />
To access this help beforehand, you may [[Makepkg#Usage|use makepkg]] to let it download and extract the QEMU source, canceling the build process as soon as the configure script begins.<br />
<br />
With the PKGBUILD file's configure script calls modified as desired, you may [[Makepkg#Usage|use makepkg]] (again) to let it build the packages, though it is inadvisable to let it install them as conflicting headless / static packages will be built as well and a typical user certainly won't need the additional system emulators for the other architectures.<br />
<br />
When the build process completes, it is advisable to instead copy your desired packages (see the [[#Removal|list for qemu-desktop in "Removal"]]{{Broken section link}}) to a different directory, [[Pacman#Additional commands|let pacman install them all]] and add them to the [[Pacman#Skip package from being upgraded|IgnorePkg]] list so you get to upgrade them manually.<br />
<br />
== Graphical front-ends for QEMU ==<br />
<br />
Unlike other virtualization programs such as [[VirtualBox]] and [[VMware]], QEMU does not provide a GUI to manage virtual machines (other than the window that appears when running a virtual machine), nor does it provide a way to create persistent virtual machines with saved settings. All parameters to run a virtual machine must be specified on the command line at every launch, unless you have created a custom script to start your virtual machine(s).<br />
<br />
[[Libvirt]] provides a convenient way to manage QEMU virtual machines. See [[Libvirt#Client|list of libvirt clients]] for available front-ends.<br />
<br />
== Creating new virtualized system ==<br />
<br />
=== Creating a hard disk image ===<br />
<br />
{{Accuracy|If I get the man page right the raw format only allocates the full size if the filesystem does not support "holes" or it is <br />
explicitly told to preallocate. See {{man|1|qemu-img|NOTES}}.}} <br />
<br />
{{Tip|See [[Wikibooks:QEMU/Images]] for more information on QEMU images.}}<br />
<br />
To run QEMU you will need a hard disk image, unless you are booting a live system from CD-ROM or the network (and not doing so to install an operating system to a hard disk image). A hard disk image is a file which stores the contents of the emulated hard disk.<br />
<br />
A hard disk image can be ''raw'', so that it is literally byte-by-byte the same as what the guest sees, and will always use the full capacity of the guest hard drive on the host. This method provides the least I/O overhead, but can waste a lot of space, as not-used space on the guest cannot be used on the host.<br />
<br />
Alternatively, the hard disk image can be in a format such as ''qcow2'' which only allocates space to the image file when the guest operating system actually writes to those sectors on its virtual hard disk. The image appears as the full size to the guest operating system, even though it may take up only a very small amount of space on the host system. This image format also supports QEMU snapshotting functionality (see [[#Creating and managing snapshots via the monitor console]] for details). However, using this format instead of ''raw'' will likely affect performance.<br />
<br />
QEMU provides the {{ic|qemu-img}} command to create hard disk images. For example to create a 4 GiB image in the ''raw'' format:<br />
<br />
$ qemu-img create -f raw ''image_file'' 4G<br />
<br />
You may use {{ic|-f qcow2}} to create a ''qcow2'' disk instead.<br />
<br />
{{Note|You can also simply create a ''raw'' image by creating a file of the needed size using {{ic|dd}} or {{ic|fallocate}}.}}<br />
<br />
{{Warning|If you store the hard disk images on a [[Btrfs]] file system, you should consider disabling [[Btrfs#Copy-on-Write (CoW)|Copy-on-Write]] for the directory before creating any images.}}<br />
<br />
==== Overlay storage images ====<br />
<br />
You can create a storage image once (the 'backing' image) and have QEMU keep mutations to this image in an overlay image. This allows you to revert to a previous state of this storage image. You could revert by creating a new overlay image at the time you wish to revert, based on the original backing image.<br />
<br />
To create an overlay image, issue a command like:<br />
<br />
$ qemu-img create -o backing_file=''img1.raw'',backing_fmt=''raw'' -f ''qcow2'' ''img1.cow''<br />
<br />
After that you can run your QEMU virtual machine as usual (see [[#Running virtualized system]]):<br />
<br />
$ qemu-system-x86_64 ''img1.cow''<br />
<br />
The backing image will then be left intact and mutations to this storage will be recorded in the overlay image file.<br />
<br />
When the path to the backing image changes, repair is required.<br />
<br />
{{Warning|The backing image's absolute filesystem path is stored in the (binary) overlay image file. Changing the backing image's path requires some effort.}}<br />
<br />
Make sure that the original backing image's path still leads to this image. If necessary, make a symbolic link at the original path to the new path. Then issue a command like:<br />
<br />
$ qemu-img rebase -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
At your discretion, you may alternatively perform an 'unsafe' rebase where the old path to the backing image is not checked:<br />
<br />
$ qemu-img rebase -u -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
==== Resizing an image ====<br />
<br />
{{Warning|Resizing an image containing an NTFS boot file system could make the operating system installed on it unbootable. It is recommended to create a backup first.}}<br />
<br />
The {{ic|qemu-img}} executable has the {{ic|resize}} option, which enables easy resizing of a hard drive image. It works for both ''raw'' and ''qcow2''. For example, to increase image space by 10 GiB, run:<br />
<br />
$ qemu-img resize ''disk_image'' +10G<br />
<br />
After enlarging the disk image, you must use file system and partitioning tools inside the virtual machine to actually begin using the new space. <br />
<br />
===== Shrinking an image =====<br />
<br />
When shrinking a disk image, you must first reduce the allocated file systems and partition sizes using the file system and partitioning tools inside the virtual machine and then shrink the disk image accordingly. For a Windows guest, this can be performed from the "create and format hard disk partitions" control panel.<br />
<br />
{{Warning|Proceeding to shrink the disk image without reducing the guest partition sizes will result in data loss.}}<br />
<br />
Then, to decrease image space by 10 GiB, run:<br />
<br />
$ qemu-img resize --shrink ''disk_image'' -10G<br />
<br />
==== Converting an image ====<br />
<br />
You can convert an image to other formats using {{ic|qemu-img convert}}. This example shows how to convert a ''raw'' image to ''qcow2'':<br />
<br />
$ qemu-img convert -f raw -O qcow2 ''input''.img ''output''.qcow2<br />
<br />
This will not remove the original input file.<br />
<br />
=== Preparing the installation media ===<br />
<br />
To install an operating system into your disk image, you need the installation medium (e.g. optical disc, USB-drive, or ISO image) for the operating system. The installation medium should not be mounted because QEMU accesses the media directly.<br />
<br />
{{Tip|If using an optical disc, it is a good idea to first dump the media to a file because this both improves performance and does not require you to have direct access to the devices (that is, you can run QEMU as a regular user without having to change access permissions on the media's device file). For example, if the CD-ROM device node is named {{ic|/dev/cdrom}}, you can dump it to a file with the command: {{bc|1=$ dd if=/dev/cdrom of=''cd_image.iso'' bs=4k}}}}<br />
<br />
=== Installing the operating system ===<br />
<br />
This is the first time you will need to start the emulator. To install the operating system on the disk image, you must attach both the disk image and the installation media to the virtual machine, and have it boot from the installation media.<br />
<br />
For example on i386 guests, to install from a bootable ISO file as CD-ROM and a raw disk image:<br />
<br />
$ qemu-system-x86_64 -cdrom ''iso_image'' -boot order=d -drive file=''disk_image'',format=raw<br />
<br />
See {{man|1|qemu}} for more information about loading other media types (such as floppy, disk images or physical drives) and [[#Running virtualized system]] for other useful options.<br />
<br />
After the operating system has finished installing, the QEMU image can be booted directly (see [[#Running virtualized system]]).<br />
<br />
{{Note|By default only 128 MiB of memory is assigned to the machine. The amount of memory can be adjusted with the {{ic|-m}} switch, for example {{ic|-m 512M}} or {{ic|-m 2G}}.}}<br />
<br />
{{Tip|<br />
* Instead of specifying {{ic|1=-boot order=x}}, some users may feel more comfortable using a boot menu: {{ic|1=-boot menu=on}}, at least during configuration and experimentation.<br />
* When running QEMU in headless mode, it starts a local VNC server on port 5900 per default. You can use [[TigerVNC]] to connect to the guest OS: {{ic|vncviewer :5900}}<br />
* If you need to replace floppies or CDs as part of the installation process, you can use the QEMU machine monitor (press {{ic|Ctrl+Alt+2}} in the virtual machine's window) to remove and attach storage devices to a virtual machine. Type {{ic|info block}} to see the block devices, and use the {{ic|change}} command to swap out a device. Press {{ic|Ctrl+Alt+1}} to go back to the virtual machine.<br />
}}<br />
<br />
== Running virtualized system ==<br />
<br />
{{ic|qemu-system-*}} binaries (for example {{ic|qemu-system-i386}} or {{ic|qemu-system-x86_64}}, depending on guest's architecture) are used to run the virtualized guest. The usage is:<br />
<br />
$ qemu-system-x86_64 ''options'' ''disk_image''<br />
<br />
Options are the same for all {{ic|qemu-system-*}} binaries, see {{man|1|qemu}} for documentation of all options.<br />
<br />
Usually, if an option has many possible values, you can use<br />
<br />
$ qemu-system-x86_64 ''option'' ''help''<br />
<br />
to list all possible values. If it supports properties, you can use<br />
<br />
$ qemu-system-x86_64 ''option'' ''value,help''<br />
<br />
to list all available properties.<br />
<br />
For example:<br />
$ qemu-system-x86_64 -machine help<br />
$ qemu-system-x86_64 -machine q35,help<br />
$ qemu-system-x86_64 -device help<br />
$ qemu-system-x86_64 -device qxl,help<br />
<br />
You can use these methods and the {{man|1|qemu}} documentation to understand the options used in follow sections.<br />
<br />
By default, QEMU will show the virtual machine's video output in a window. One thing to keep in mind: when you click inside the QEMU window, the mouse pointer is grabbed. To release it, press {{ic|Ctrl+Alt+g}}.<br />
<br />
{{Warning|QEMU should never be run as root. If you must launch it in a script as root, you should use the {{ic|-runas}} option to make QEMU drop root privileges.}}<br />
<br />
=== Enabling KVM ===<br />
<br />
KVM (''Kernel-based Virtual Machine'') full virtualization must be supported by your Linux kernel and your hardware, and necessary [[kernel modules]] must be loaded. See [[KVM]] for more information.<br />
<br />
To start QEMU in KVM mode, append {{ic|-accel kvm}} to the additional start options. To check if KVM is enabled for a running virtual machine, enter the [[#QEMU monitor]] and type {{ic|info kvm}}.<br />
<br />
{{Note|<br />
* The argument {{ic|1=accel=kvm}} of the {{ic|-machine}} option is equivalent to the {{ic|-enable-kvm}} or the {{ic|-accel kvm}} option.<br />
* CPU model {{ic|host}} requires KVM.<br />
* If you start your virtual machine with a GUI tool and experience very bad performance, you should check for proper KVM support, as QEMU may be falling back to software emulation.<br />
* KVM needs to be enabled in order to start Windows 7 or Windows 8 properly without a ''blue screen''.<br />
}}<br />
<br />
=== Enabling IOMMU (Intel VT-d/AMD-Vi) support ===<br />
<br />
First enable IOMMU, see [[PCI passthrough via OVMF#Setting up IOMMU]].<br />
<br />
Add {{ic|-device intel-iommu}} to create the IOMMU device:<br />
<br />
$ qemu-system-x86_64 '''-enable-kvm -machine q35 -device intel-iommu''' -cpu host ..<br />
<br />
{{Note|<br />
On Intel CPU based systems creating an IOMMU device in a QEMU guest with {{ic|-device intel-iommu}} will disable PCI passthrough with an error like: {{bc|Device at bus pcie.0 addr 09.0 requires iommu notifier which is currently not supported by intel-iommu emulation}} While adding the kernel parameter {{ic|1=intel_iommu=on}} is still needed for remapping IO (e.g. [[PCI passthrough via OVMF#Isolating the GPU|PCI passthrough with vfio-pci]]), {{ic|-device intel-iommu}} should not be set if PCI passthrough is required.<br />
}}<br />
<br />
=== Booting in UEFI mode ===<br />
<br />
The default firmware used by QEMU is [https://www.coreboot.org/SeaBIOS SeaBIOS], which is a Legacy BIOS implementation. QEMU uses {{ic|/usr/share/qemu/bios-256k.bin}} (provided by the {{Pkg|seabios}} package) as a default read-only (ROM) image. You can use the {{ic|-bios}} argument to select another firmware file. However, UEFI requires writable memory to work properly, so you need to emulate [https://wiki.qemu.org/Features/PC_System_Flash PC System Flash] instead.<br />
<br />
[https://github.com/tianocore/tianocore.github.io/wiki/OVMF OVMF] is a TianoCore project to enable UEFI support for Virtual Machines. It can be [[install]]ed with the {{Pkg|edk2-ovmf}} package.<br />
<br />
There are two ways to use OVMF as a firmware. The first is to copy {{ic|/usr/share/edk2/x64/OVMF.4m.fd}}, make it writable and use as a pflash drive:<br />
<br />
-drive if=pflash,format=raw,file=''/copy/of/OVMF.4m.fd''<br />
<br />
All changes to the UEFI settings will be saved directly to this file.<br />
<br />
Another and more preferable way is to split OVMF into two files. The first one will be read-only and store the firmware executable, and the second one will be used as a writable variable store. The advantage is that you can use the firmware file directly without copying, so it will be updated automatically by [[pacman]].<br />
<br />
Use {{ic|/usr/share/edk2/x64/OVMF_CODE.4m.fd}} as a first read-only pflash drive. Copy {{ic|/usr/share/edk2/x64/OVMF_VARS.4m.fd}}, make it writable and use as a second writable pflash drive:<br />
<br />
-drive if=pflash,format=raw,readonly=on,file=/usr/share/edk2/x64/OVMF_CODE.4m.fd \<br />
-drive if=pflash,format=raw,file=''/copy/of/OVMF_VARS.4m.fd''<br />
<br />
If secure boot is wanted, replace {{ic|/usr/share/edk2/x64/OVMF_CODE.4m.fd}} with {{ic|/usr/share/edk2/x64/OVMF_CODE.secboot.4m.fd}}.<br />
<br />
=== Trusted Platform Module emulation ===<br />
<br />
QEMU can emulate [[Trusted Platform Module]], which is required by some systems such as Windows 11 (which requires TPM 2.0).<br />
<br />
[[Install]] the {{Pkg|swtpm}} package, which provides a software TPM implementation. Create some directory for storing TPM data ({{ic|''/path/to/mytpm''}} will be used as an example). Run this command to start the emulator:<br />
<br />
$ swtpm socket --tpm2 --tpmstate dir=''/path/to/mytpm'' --ctrl type=unixio,path=''/path/to/mytpm/swtpm-sock''<br />
<br />
{{ic|''/path/to/mytpm/swtpm-sock''}} will be created by ''swtpm'': this is a UNIX socket to which QEMU will connect. You can put it in any directory.<br />
<br />
By default, ''swtpm'' starts a TPM version 1.2 emulator. The {{ic|--tpm2}} option enables TPM 2.0 emulation.<br />
<br />
Finally, add the following options to QEMU:<br />
<br />
-chardev socket,id=chrtpm,path=''/path/to/mytpm/swtpm-sock'' \<br />
-tpmdev emulator,id=tpm0,chardev=chrtpm \<br />
-device tpm-tis,tpmdev=tpm0<br />
<br />
and TPM will be available inside the virtual machine. After shutting down the virtual machine, ''swtpm'' will be automatically terminated.<br />
<br />
See [https://qemu-project.gitlab.io/qemu/specs/tpm.html the QEMU documentation] for more information. <br />
<br />
If guest OS still doesn't recognize the TPM device, try to adjust ''CPU Models and Topology'' options. It might cause problem.<br />
<br />
== Sharing data between host and guest ==<br />
<br />
=== Network ===<br />
<br />
Data can be shared between the host and guest OS using any network protocol that can transfer files, such as [[NFS]], [[SMB]], [[Wikipedia:Network block device|NBD]], HTTP, [[Very Secure FTP Daemon|FTP]], or [[SSH]], provided that you have set up the network appropriately and enabled the appropriate services.<br />
<br />
The default user-mode networking allows the guest to access the host OS at the IP address 10.0.2.2. Any servers that you are running on your host OS, such as a SSH server or SMB server, will be accessible at this IP address. So on the guests, you can mount directories exported on the host via [[SMB]] or [[NFS]], or you can access the host's HTTP server, etc.<br />
It will not be possible for the host OS to access servers running on the guest OS, but this can be done with other network configurations (see [[#Tap networking with QEMU]]).<br />
<br />
=== QEMU's port forwarding ===<br />
<br />
{{Note|QEMU's port forwarding is IPv4-only. IPv6 port forwarding is not implemented and the last patches were proposed in 2018.[https://lore.kernel.org/qemu-devel/1540512223-21199-1-git-send-email-max7255@yandex-team.ru/T/#u]}}<br />
<br />
QEMU can forward ports from the host to the guest to enable e.g. connecting from the host to an SSH server running on the guest.<br />
<br />
For example, to bind port 60022 on the host with port 22 (SSH) on the guest, start QEMU with a command like:<br />
<br />
$ qemu-system-x86_64 ''disk_image'' -nic user,hostfwd=tcp::60022-:22<br />
<br />
Make sure the sshd is running on the guest and connect with:<br />
<br />
$ ssh ''guest-user''@127.0.0.1 -p 60022<br />
<br />
You can use [[SSHFS]] to mount the guest's file system at the host for shared read and write access.<br />
<br />
To forward several ports, you just repeat the {{ic|hostfwd}} in the {{ic|-nic}} argument, e.g. for VNC's port:<br />
<br />
$ qemu-system-x86_64 ''disk_image'' -nic user,hostfwd=tcp::60022-:22,hostfwd=tcp::5900-:5900<br />
<br />
=== QEMU's built-in SMB server ===<br />
<br />
QEMU's documentation says it has a "built-in" SMB server, but actually it just starts up [[Samba]] on the host with an automatically generated {{ic|smb.conf}} file located in {{ic|/tmp/qemu-smb.''random_string''}} and makes it accessible to the guest at a different IP address (10.0.2.4 by default). This only works for user networking, and is useful when you do not want to start the normal [[Samba]] service on the host, which the guest can also access if you have set up shares on it.<br />
<br />
Only a single directory can be set as shared with the option {{ic|1=smb=}}, but adding more directories (even while the virtual machine is running) could be as easy as creating symbolic links in the shared directory if QEMU configured SMB to follow symbolic links. It does not do so, but the configuration of the running SMB server can be changed as described below.<br />
<br />
''Samba'' must be installed on the host. To enable this feature, start QEMU with a command like:<br />
<br />
$ qemu-system-x86_64 -nic user,id=nic0,smb=''shared_dir_path'' ''disk_image''<br />
<br />
where {{ic|''shared_dir_path''}} is a directory that you want to share between the guest and host.<br />
<br />
Then, in the guest, you will be able to access the shared directory on the host 10.0.2.4 with the share name "qemu". For example, in Windows Explorer you would go to {{ic|\\10.0.2.4\qemu}}.<br />
<br />
{{Note|<br />
* If you are using sharing options multiple times like {{ic|1=-net user,smb=''shared_dir_path1'' -net user,smb=''shared_dir_path2''}} or {{ic|1=-net user,smb=''shared_dir_path1'',smb=''shared_dir_path2''}} then it will share only the last defined one.<br />
* If you cannot access the shared folder and the guest system is Windows, check that the [http://ecross.mvps.org/howto/enable-netbios-over-tcp-ip-with-windows.htm NetBIOS protocol is enabled]{{Dead link|2023|05|06|status=domain name not resolved}} and that a firewall does not block [https://technet.microsoft.com/en-us/library/cc940063.aspx ports] used by the NetBIOS protocol.<br />
* If you cannot access the shared folder and the guest system is Windows 10 Enterprise or Education or Windows Server 2016, [https://support.microsoft.com/en-us/help/4046019 enable guest access].<br />
* If you use [[#Tap networking with QEMU]], use {{ic|1=-device virtio-net,netdev=vmnic -netdev user,id=vmnic,smb=''shared_dir_path''}} to get SMB.<br />
}}<br />
<br />
One way to share multiple directories and to add or remove them while the virtual machine is running, is to share an empty directory and create/remove symbolic links to the directories in the shared directory. For this to work, the configuration of the running SMB server can be changed with the following script, which also allows the execution of files on the guest that are not set executable on the host:<br />
<br />
#!/bin/sh<br />
eval $(ps h -C smbd -o pid,args | grep /tmp/qemu-smb | gawk '{print "pid="$1";conf="$6}')<br />
echo "[global]<br />
allow insecure wide links = yes<br />
[qemu]<br />
follow symlinks = yes<br />
wide links = yes<br />
acl allow execute always = yes" >> "$conf"<br />
# in case the change is not detected automatically:<br />
smbcontrol --configfile="$conf" "$pid" reload-config<br />
<br />
This can be applied to the running server started by qemu only after the guest has connected to the network drive the first time. An alternative to this method is to add additional shares to the configuration file like so:<br />
<br />
echo "[''myshare'']<br />
path=''another_path''<br />
read only=no<br />
guest ok=yes<br />
force user=''username''" >> $conf<br />
<br />
This share will be available on the guest as {{ic|\\10.0.2.4\''myshare''}}.<br />
<br />
=== Using filesystem passthrough and VirtFS ===<br />
<br />
See the [https://wiki.qemu.org/Documentation/9psetup QEMU documentation].<br />
<br />
=== Host file sharing with virtiofsd ===<br />
<br />
{{Style|See [[Help:Style/Formatting and punctuation]].}}<br />
<br />
virtiofsd is shipped with QEMU package. Documentation is available [https://qemu-stsquad.readthedocs.io/en/docs-next/tools/virtiofsd.html online]{{Dead link|2023|05|06|status=404}} or {{ic|/usr/share/doc/qemu/qemu/tools/virtiofsd.html}} on local file system with {{Pkg|qemu-docs}} installed.<br />
<br />
Add user that runs qemu to the 'kvm' [[user group]], because it needs to access the virtiofsd socket. You might have to logout for change to take effect.<br />
<br />
{{Accuracy|Running services as root is not secure. Also the process should be wrapped in a systemd service.}}<br />
<br />
Start as virtiofsd as root:<br />
<br />
# /usr/lib/virtiofsd --socket-path=/var/run/qemu-vm-001.sock --shared-dir /tmp/vm-001 --cache always<br />
<br />
where<br />
<br />
* {{ic|/var/run/qemu-vm-001.sock}} is a socket file,<br />
* {{ic|/tmp/vm-001}} is a shared directory between the host and the guest virtual machine.<br />
<br />
The created socket file has root only access permission. Give group kvm access to it with:<br />
<br />
# chgrp kvm qemu-vm-001.sock; chmod g+rxw qemu-vm-001.sock<br />
<br />
Add the following configuration options when starting the virtual machine:<br />
<br />
-object memory-backend-memfd,id=mem,size=4G,share=on \<br />
-numa node,memdev=mem \<br />
-chardev socket,id=char0,path=/var/run/qemu-vm-001.sock \<br />
-device vhost-user-fs-pci,chardev=char0,tag=myfs<br />
<br />
where<br />
<br />
{{Expansion|Explain the remaining options (or remove them if they are not necessary).}}<br />
<br />
* {{ic|1=size=4G}} shall match size specified with {{ic|-m 4G}} option,<br />
* {{ic|/var/run/qemu-vm-001.sock}} points to socket file started earlier,<br />
<br />
{{Style|The section should not be specific to Windows.}}<br />
<br />
Remember, that guest must be configured to enable sharing. For Windows there are [https://virtio-fs.gitlab.io/howto-windows.html instructions]. Once configured, Windows will have the {{ic|Z:}} drive mapped automatically with shared directory content.<br />
<br />
Your Windows 10 guest system is properly configured if it has:<br />
<br />
* VirtioFSSService windows service,<br />
* WinFsp.Launcher windows service,<br />
* VirtIO FS Device driver under "System devices" in Windows "Device Manager".<br />
<br />
If the above installed and {{ic|Z:}} drive is still not listed, try repairing "Virtio-win-guest-tools" in Windows ''Add/Remove programs''.<br />
<br />
=== Mounting a partition of the guest on the host ===<br />
<br />
It can be useful to mount a drive image under the host system, it can be a way to transfer files in and out of the guest. This should be done when the virtual machine is not running.<br />
<br />
The procedure to mount the drive on the host depends on the type of qemu image, ''raw'' or ''qcow2''. We detail thereafter the steps to mount a drive in the two formats in [[#Mounting a partition from a raw image]] and [[#Mounting a partition from a qcow2 image]]. For the full documentation see [[Wikibooks:QEMU/Images#Mounting an image on the host]].<br />
<br />
{{Warning|You must unmount the partitions before running the virtual machine again. Otherwise, data corruption is very likely to occur.}}<br />
<br />
==== Mounting a partition from a raw image ====<br />
<br />
It is possible to mount partitions that are inside a raw disk image file by setting them up as loopback devices.<br />
<br />
===== With manually specifying byte offset =====<br />
<br />
One way to mount a disk image partition is to mount the disk image at a certain offset using a command like the following:<br />
<br />
# mount -o loop,offset=32256 ''disk_image'' ''mountpoint''<br />
<br />
The {{ic|1=offset=32256}} option is actually passed to the {{ic|losetup}} program to set up a loopback device that starts at byte offset 32256 of the file and continues to the end. This loopback device is then mounted. You may also use the {{ic|sizelimit}} option to specify the exact size of the partition, but this is usually unnecessary.<br />
<br />
Depending on your disk image, the needed partition may not start at offset 32256. Run {{ic|fdisk -l ''disk_image''}} to see the partitions in the image. fdisk gives the start and end offsets in 512-byte sectors, so multiply by 512 to get the correct offset to pass to {{ic|mount}}.<br />
<br />
===== With loop module autodetecting partitions =====<br />
<br />
The Linux loop driver actually supports partitions in loopback devices, but it is disabled by default. To enable it, do the following:<br />
<br />
* Get rid of all your loopback devices (unmount all mounted images, etc.).<br />
* [[Kernel modules#Manual module handling|Unload]] the {{ic|loop}} kernel module, and load it with the {{ic|1=max_part=15}} parameter set. Additionally, the maximum number of loop devices can be controlled with the {{ic|max_loop}} parameter.<br />
<br />
{{Tip|You can put an entry in {{ic|/etc/modprobe.d}} to load the loop module with {{ic|1=max_part=15}} every time, or you can put {{ic|1=loop.max_part=15}} on the kernel command-line, depending on whether you have the {{ic|loop.ko}} module built into your kernel or not.}}<br />
<br />
Set up your image as a loopback device:<br />
<br />
# losetup -f -P ''disk_image''<br />
<br />
Then, if the device created was {{ic|/dev/loop0}}, additional devices {{ic|/dev/loop0p''X''}} will have been automatically created, where X is the number of the partition. These partition loopback devices can be mounted directly. For example:<br />
<br />
# mount /dev/loop0p1 ''mountpoint''<br />
<br />
To mount the disk image with ''udisksctl'', see [[Udisks#Mount loop devices]].<br />
<br />
===== With kpartx =====<br />
<br />
''kpartx'' from the {{Pkg|multipath-tools}} package can read a partition table on a device and create a new device for each partition. For example:<br />
<br />
# kpartx -a ''disk_image''<br />
<br />
This will setup the loopback device and create the necessary partition(s) device(s) in {{ic|/dev/mapper/}}.<br />
<br />
==== Mounting a partition from a qcow2 image ====<br />
<br />
We will use {{ic|qemu-nbd}}, which lets use the NBD (''network block device'') protocol to share the disk image.<br />
<br />
First, we need the ''nbd'' module loaded:<br />
<br />
# modprobe nbd max_part=16<br />
<br />
Then, we can share the disk and create the device entries:<br />
<br />
# qemu-nbd -c /dev/nbd0 ''/path/to/image.qcow2''<br />
<br />
Discover the partitions:<br />
<br />
# partprobe /dev/nbd0<br />
<br />
''fdisk'' can be used to get information regarding the different partitions in {{ic|''nbd0''}}:<br />
<br />
{{hc|# fdisk -l /dev/nbd0|2=<br />
Disk /dev/nbd0: 25.2 GiB, 27074281472 bytes, 52879456 sectors<br />
Units: sectors of 1 * 512 = 512 bytes<br />
Sector size (logical/physical): 512 bytes / 512 bytes<br />
I/O size (minimum/optimal): 512 bytes / 512 bytes<br />
Disklabel type: dos<br />
Disk identifier: 0xa6a4d542<br />
<br />
Device Boot Start End Sectors Size Id Type<br />
/dev/nbd0p1 * 2048 1026047 1024000 500M 7 HPFS/NTFS/exFAT<br />
/dev/nbd0p2 1026048 52877311 51851264 24.7G 7 HPFS/NTFS/exFAT}}<br />
<br />
Then mount any partition of the drive image, for example the partition 2:<br />
<br />
# mount /dev/nbd0'''p2''' ''mountpoint''<br />
<br />
After the usage, it is important to unmount the image and reverse previous steps, i.e. unmount the partition and disconnect the nbd device:<br />
<br />
# umount ''mountpoint''<br />
# qemu-nbd -d /dev/nbd0<br />
<br />
=== Using any real partition as the single primary partition of a hard disk image ===<br />
<br />
Sometimes, you may wish to use one of your system partitions from within QEMU. Using a raw partition for a virtual machine will improve performance, as the read and write operations do not go through the file system layer on the physical host. Such a partition also provides a way to share data between the host and guest.<br />
<br />
In Arch Linux, device files for raw partitions are, by default, owned by ''root'' and the ''disk'' group. If you would like to have a non-root user be able to read and write to a raw partition, you must either change the owner of the partition's device file to that user, add that user to the ''disk'' group, or use [[ACL]] for more fine-grained access control.<br />
<br />
{{Warning|<br />
* Although it is possible, it is not recommended to allow virtual machines to alter critical data on the host system, such as the root partition.<br />
* You must not mount a file system on a partition read-write on both the host and the guest at the same time. Otherwise, data corruption will result.<br />
}}<br />
<br />
After doing so, you can attach the partition to a QEMU virtual machine as a virtual disk.<br />
<br />
However, things are a little more complicated if you want to have the ''entire'' virtual machine contained in a partition. In that case, there would be no disk image file to actually boot the virtual machine since you cannot install a boot loader to a partition that is itself formatted as a file system and not as a partitioned device with an MBR. Such a virtual machine can be booted either by: [[#Specifying kernel and initrd manually]], [[#Simulating a virtual disk with MBR]], [[#Using the device-mapper]], [[#Using a linear RAID]] or [[#Using a Network Block Device]].<br />
<br />
==== Specifying kernel and initrd manually ====<br />
<br />
QEMU supports loading [[Kernels|Linux kernels]] and [[initramfs|init ramdisks]] directly, thereby circumventing boot loaders such as [[GRUB]]. It then can be launched with the physical partition containing the root file system as the virtual disk, which will not appear to be partitioned. This is done by issuing a command similar to the following:<br />
<br />
{{Note|In this example, it is the '''host's''' images that are being used, not the guest's. If you wish to use the guest's images, either mount {{ic|/dev/sda3}} read-only (to protect the file system from the host) and specify the {{ic|/full/path/to/images}} or use some kexec hackery in the guest to reload the guest's kernel (extends boot time). }}<br />
<br />
$ qemu-system-x86_64 -kernel /boot/vmlinuz-linux -initrd /boot/initramfs-linux.img -append root=/dev/sda /dev/sda3<br />
<br />
In the above example, the physical partition being used for the guest's root file system is {{ic|/dev/sda3}} on the host, but it shows up as {{ic|/dev/sda}} on the guest.<br />
<br />
You may, of course, specify any kernel and initrd that you want, and not just the ones that come with Arch Linux.<br />
<br />
When there are multiple [[kernel parameters]] to be passed to the {{ic|-append}} option, they need to be quoted using single or double quotes. For example:<br />
<br />
... -append 'root=/dev/sda1 console=ttyS0'<br />
<br />
==== Simulating a virtual disk with MBR ====<br />
<br />
A more complicated way to have a virtual machine use a physical partition, while keeping that partition formatted as a file system and not just having the guest partition the partition as if it were a disk, is to simulate an MBR for it so that it can boot using a boot loader such as GRUB.<br />
<br />
For the following, suppose you have a plain, unmounted {{ic|/dev/hda''N''}} partition with some file system on it you wish to make part of a QEMU disk image. The trick is to dynamically prepend a master boot record (MBR) to the real partition you wish to embed in a QEMU raw disk image. More generally, the partition can be any part of a larger simulated disk, in particular a block device that simulates the original physical disk but only exposes {{ic|/dev/hda''N''}} to the virtual machine.<br />
<br />
A virtual disk of this type can be represented by a VMDK file that contains references to (a copy of) the MBR and the partition, but QEMU does not support this VMDK format. For instance, a virtual disk [https://www.virtualbox.org/manual/ch09.html#rawdisk created by]<br />
<br />
$ VBoxManage internalcommands createrawvmdk -filename ''/path/to/file.vmdk'' -rawdisk /dev/hda<br />
<br />
will be rejected by QEMU with the error message<br />
<br />
Unsupported image type 'partitionedDevice'<br />
<br />
Note that {{ic|VBoxManage}} creates two files, {{ic|''file.vmdk''}} and {{ic|''file-pt.vmdk''}}, the latter being a copy of the MBR, to which the text file {{ic|file.vmdk}} points. Read operations outside the target partition or the MBR would give zeros, while written data would be discarded.<br />
<br />
===== Using the device-mapper =====<br />
<br />
A method that is similar to the use of a VMDK descriptor file uses the [https://docs.kernel.org/admin-guide/device-mapper/index.html device-mapper] to prepend a loop device attached to the MBR file to the target partition. In case we do not need our virtual disk to have the same size as the original, we first create a file to hold the MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=2048<br />
<br />
Here, a 1 MiB (2048 * 512 bytes) file is created in accordance with partition alignment policies used by modern disk partitioning tools. For compatibility with older partitioning software, 63 sectors instead of 2048 might be required. The MBR only needs a single 512 bytes block, the additional free space can be used for a BIOS boot partition and, in the case of a hybrid partitioning scheme, for a GUID Partition Table. Then, we attach a loop device to the MBR file:<br />
<br />
{{hc|# losetup --show -f ''/path/to/mbr''|/dev/loop0}}<br />
<br />
In this example, the resulting device is {{ic|/dev/loop0}}. The device mapper is now used to join the MBR and the partition:<br />
<br />
# echo "0 2048 linear /dev/loop0 0<br />
2048 `blockdev --getsz /dev/hda''N''` linear /dev/hda''N'' 0" | dmsetup create qemu<br />
<br />
The resulting {{ic|/dev/mapper/qemu}} is what we will use as a QEMU raw disk image. Additional steps are required to create a partition table (see the section that describes the use of a linear RAID for an example) and boot loader code on the virtual disk (which will be stored in {{ic|''/path/to/mbr''}}).<br />
<br />
The following setup is an example where the position of {{ic|/dev/hda''N''}} on the virtual disk is to be the same as on the physical disk and the rest of the disk is hidden, except for the MBR, which is provided as a copy:<br />
<br />
# dd if=/dev/hda count=1 of=''/path/to/mbr''<br />
# loop=`losetup --show -f ''/path/to/mbr''`<br />
# start=`blockdev --report /dev/hda''N'' | tail -1 | awk '{print $5}'`<br />
# size=`blockdev --getsz /dev/hda''N''`<br />
# disksize=`blockdev --getsz /dev/hda`<br />
# echo "0 1 linear $loop 0<br />
1 $((start-1)) zero<br />
$start $size linear /dev/hda''N'' 0<br />
$((start+size)) $((disksize-start-size)) zero" | dmsetup create qemu<br />
<br />
The table provided as standard input to {{ic|dmsetup}} has a similar format as the table in a VDMK descriptor file produced by {{ic|VBoxManage}} and can alternatively be loaded from a file with {{ic|dmsetup create qemu --table ''table_file''}}. To the virtual machine, only {{ic|/dev/hda''N''}} is accessible, while the rest of the hard disk reads as zeros and discards written data, except for the first sector. We can print the table for {{ic|/dev/mapper/qemu}} with {{ic|dmsetup table qemu}} (use {{ic|udevadm info -rq name /sys/dev/block/''major'':''minor''}} to translate {{ic|''major'':''minor''}} to the corresponding {{ic|/dev/''blockdevice''}} name). Use {{ic|dmsetup remove qemu}} and {{ic|losetup -d $loop}} to delete the created devices.<br />
<br />
A situation where this example would be useful is an existing Windows XP installation in a multi-boot configuration and maybe a hybrid partitioning scheme (on the physical hardware, Windows XP could be the only operating system that uses the MBR partition table, while more modern operating systems installed on the same computer could use the GUID Partition Table). Windows XP supports hardware profiles, so that that the same installation can be used with different hardware configurations alternatingly (in this case bare metal vs. virtual) with Windows needing to install drivers for newly detected hardware only once for every profile. Note that in this example the boot loader code in the copied MBR needs to be updated to directly load Windows XP from {{ic|/dev/hda''N''}} instead of trying to start the multi-boot capable boot loader (like GRUB) present in the original system. Alternatively, a copy of the boot partition containing the boot loader installation can be included in the virtual disk the same way as the MBR.<br />
<br />
===== Using a linear RAID =====<br />
<br />
{{Out of date|[[Wikipedia:Cylinder-head-sector|CHS]] has been obsolete for decades.}}<br />
<br />
You can also do this using software [[RAID]] in linear mode (you need the {{ic|linear.ko}} kernel driver) and a loopback device: <br />
<br />
First, you create some small file to hold the MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=32<br />
<br />
Here, a 16 KiB (32 * 512 bytes) file is created. It is important not to make it too small (even if the MBR only needs a single 512 bytes block), since the smaller it will be, the smaller the chunk size of the software RAID device will have to be, which could have an impact on performance. Then, you setup a loopback device to the MBR file:<br />
<br />
# losetup -f ''/path/to/mbr''<br />
<br />
Let us assume the resulting device is {{ic|/dev/loop0}}, because we would not already have been using other loopbacks. Next step is to create the "merged" MBR + {{ic|/dev/hda''N''}} disk image using software RAID:<br />
<br />
# modprobe linear<br />
# mdadm --build --verbose /dev/md0 --chunk=16 --level=linear --raid-devices=2 /dev/loop0 /dev/hda''N''<br />
<br />
The resulting {{ic|/dev/md0}} is what you will use as a QEMU raw disk image (do not forget to set the permissions so that the emulator can access it). The last (and somewhat tricky) step is to set the disk configuration (disk geometry and partitions table) so that the primary partition start point in the MBR matches the one of {{ic|/dev/hda''N''}} inside {{ic|/dev/md0}} (an offset of exactly 16 * 512 = 16384 bytes in this example). Do this using {{ic|fdisk}} on the host machine, not in the emulator: the default raw disc detection routine from QEMU often results in non-kibibyte-roundable offsets (such as 31.5 KiB, as in the previous section) that cannot be managed by the software RAID code. Hence, from the host:<br />
<br />
# fdisk /dev/md0<br />
<br />
Press {{ic|X}} to enter the expert menu. Set number of 's'ectors per track so that the size of one cylinder matches the size of your MBR file. For two heads and a sector size of 512, the number of sectors per track should be 16, so we get cylinders of size 2x16x512=16k.<br />
<br />
Now, press {{ic|R}} to return to the main menu.<br />
<br />
Press {{ic|P}} and check that the cylinder size is now 16k.<br />
<br />
Now, create a single primary partition corresponding to {{ic|/dev/hda''N''}}. It should start at cylinder 2 and end at the end of the disk (note that the number of cylinders now differs from what it was when you entered fdisk.<br />
<br />
Finally, 'w'rite the result to the file: you are done. You now have a partition you can mount directly from your host, as well as part of a QEMU disk image:<br />
<br />
$ qemu-system-x86_64 -hdc /dev/md0 ''[...]''<br />
<br />
You can, of course, safely set any boot loader on this disk image using QEMU, provided the original {{ic|/dev/hda''N''}} partition contains the necessary tools.<br />
<br />
===== Using a Network Block Device =====<br />
<br />
With [https://docs.kernel.org/admin-guide/blockdev/nbd.html Network Block Device], Linux can use a remote server as one of its block device. You may use {{ic|nbd-server}} (from the {{Pkg|nbd}} package) to create an MBR wrapper for QEMU.<br />
<br />
Assuming you have already set up your MBR wrapper file like above, rename it to {{ic|wrapper.img.0}}. Then create a symbolic link named {{ic|wrapper.img.1}} in the same directory, pointing to your partition. Then put the following script in the same directory:<br />
<br />
{{bc|1=<br />
#!/bin/sh<br />
dir="$(realpath "$(dirname "$0")")"<br />
cat >wrapper.conf <<EOF<br />
[generic]<br />
allowlist = true<br />
listenaddr = 127.713705<br />
port = 10809<br />
<br />
[wrap]<br />
exportname = $dir/wrapper.img<br />
multifile = true<br />
EOF<br />
<br />
nbd-server \<br />
-C wrapper.conf \<br />
-p wrapper.pid \<br />
"$@"<br />
}}<br />
<br />
The {{ic|.0}} and {{ic|.1}} suffixes are essential; the rest can be changed. After running the above script (which you may need to do as root to make sure nbd-server is able to access the partition), you can launch QEMU with:<br />
<br />
qemu-system-x86_64 -drive file=nbd:127.713705:10809:exportname=wrap ''[...]''<br />
<br />
=== Using an entire physical disk device inside the virtual machine ===<br />
<br />
{{Style|Duplicates [[#Using any real partition as the single primary partition of a hard disk image]], libvirt instructions do not belong to this page.}}<br />
<br />
You may have a second disk with a different OS (like Windows) on it and may want to gain the ability to also boot it inside a virtual machine.<br />
Since the disk access is raw, the disk will perform quite well inside the virtual machine.<br />
<br />
==== Windows virtual machine boot prerequisites ====<br />
<br />
Be sure to install the [https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/archive-virtio/ virtio drivers] inside the OS on that disk before trying to boot it in the virtual machine.<br />
For Win 7 use version [https://askubuntu.com/questions/1310440/using-virtio-win-drivers-with-win7-sp1-x64 0.1.173-4].<br />
Some singular drivers from newer virtio builds may be used on Win 7 but you will have to install them manually via device manager.<br />
For Win 10 you can use the latest virtio build.<br />
<br />
===== Set up the windows disk interface drivers =====<br />
<br />
You may get a {{ic|0x0000007B}} bluescreen when trying to boot the virtual machine. This means Windows can not access the drive during the early boot stage because the disk interface driver it would need for that is not loaded / is set to start manually.<br />
<br />
The solution is to [https://superuser.com/a/1032769 enable these drivers to start at boot].<br />
<br />
In {{ic|HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services}}, find the folders {{ic|aliide, amdide, atapi, cmdide, iastor (may not exist), iastorV, intelide, LSI_SAS, msahci, pciide and viaide}}.<br />
Inside each of those, set all their "start" values to 0 in order to enable them at boot.<br />
If your drive is a PCIe NVMe drive, also enable that driver (should it exist).<br />
<br />
==== Find the unique path of your disk ====<br />
<br />
Run {{ic|ls /dev/disk/by-id/}}: tere you pick out the ID of the drive you want to insert into the virtual machine, for example {{ic|ata-TS512GMTS930L_C199211383}}.<br />
Now add that ID to {{ic|/dev/disk/by-id/}} so you get {{ic|/dev/disk/by-id/ata-TS512GMTS930L_C199211383}}.<br />
That is the unique path to that disk.<br />
<br />
==== Add the disk in QEMU CLI ====<br />
<br />
In QEMU CLI that would probably be:<br />
<br />
{{ic|1=-drive file=/dev/disk/by-id/ata-TS512GMTS930L_C199211383,format=raw,media=disk}}<br />
<br />
Just modify {{ic|file{{=}}}} to be the unique path of your drive.<br />
<br />
==== Add the disk in libvirt ====<br />
<br />
In libvirt XML that translates to<br />
<br />
{{hc|$ virsh edit ''vmname''|<nowiki><br />
...<br />
<disk type="block" device="disk"><br />
<driver name="qemu" type="raw" cache="none" io="native"/><br />
<source dev="/dev/disk/by-id/ata-TS512GMTS930L_C199211383"/><br />
<target dev="sda" bus="sata"/><br />
<address type="drive" controller="0" bus="0" target="0" unit="0"/><br />
</disk><br />
...<br />
</nowiki>}}<br />
<br />
Just modify "source dev" to be the unique path of your drive.<br />
<br />
==== Add the disk in virt-manager ====<br />
<br />
When creating a virtual machine, select "import existing drive" and just paste that unique path.<br />
If you already have the virtual machine, add a device, storage, then select or create custom storage.<br />
Now paste the unique path.<br />
<br />
== Networking ==<br />
<br />
{{Style|Network topologies (sections [[#Host-only networking]], [[#Internal networking]] and info spread out across other sections) should not be described alongside the various virtual interfaces implementations, such as [[#User-mode networking]], [[#Tap networking with QEMU]], [[#Networking with VDE2]].}}<br />
<br />
The performance of virtual networking should be better with tap devices and bridges than with user-mode networking or vde because tap devices and bridges are implemented in-kernel.<br />
<br />
In addition, networking performance can be improved by assigning virtual machines a [https://wiki.libvirt.org/page/Virtio virtio] network device rather than the default emulation of an e1000 NIC. See [[#Installing virtio drivers]] for more information.<br />
<br />
=== Link-level address caveat ===<br />
<br />
By giving the {{ic|-net nic}} argument to QEMU, it will, by default, assign a virtual machine a network interface with the link-level address {{ic|52:54:00:12:34:56}}. However, when using bridged networking with multiple virtual machines, it is essential that each virtual machine has a unique link-level (MAC) address on the virtual machine side of the tap device. Otherwise, the bridge will not work correctly, because it will receive packets from multiple sources that have the same link-level address. This problem occurs even if the tap devices themselves have unique link-level addresses because the source link-level address is not rewritten as packets pass through the tap device.<br />
<br />
Make sure that each virtual machine has a unique link-level address, but it should always start with {{ic|52:54:}}. Use the following option, replace ''X'' with arbitrary hexadecimal digit:<br />
<br />
$ qemu-system-x86_64 -net nic,macaddr=52:54:''XX:XX:XX:XX'' -net vde ''disk_image''<br />
<br />
Generating unique link-level addresses can be done in several ways:<br />
<br />
* Manually specify unique link-level address for each NIC. The benefit is that the DHCP server will assign the same IP address each time the virtual machine is run, but it is unusable for large number of virtual machines.<br />
* Generate random link-level address each time the virtual machine is run. Practically zero probability of collisions, but the downside is that the DHCP server will assign a different IP address each time. You can use the following command in a script to generate random link-level address in a {{ic|macaddr}} variable:<br />
<br />
{{bc|1=<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
qemu-system-x86_64 -net nic,macaddr="$macaddr" -net vde ''disk_image''<br />
}}<br />
<br />
* Use the following script {{ic|qemu-mac-hasher.py}} to generate the link-level address from the virtual machine name using a hashing function. Given that the names of virtual machines are unique, this method combines the benefits of the aforementioned methods: it generates the same link-level address each time the script is run, yet it preserves the practically zero probability of collisions.<br />
<br />
{{hc|qemu-mac-hasher.py|2=<br />
#!/usr/bin/env python<br />
# usage: qemu-mac-hasher.py <VMName><br />
<br />
import sys<br />
import zlib<br />
<br />
crc = str(hex(zlib.crc32(sys.argv[1].encode("utf-8")))).replace("x", "")[-8:]<br />
print("52:54:%s%s:%s%s:%s%s:%s%s" % tuple(crc))<br />
}}<br />
<br />
In a script, you can use for example:<br />
<br />
vm_name="''VM Name''"<br />
qemu-system-x86_64 -name "$vm_name" -net nic,macaddr=$(qemu-mac-hasher.py "$vm_name") -net vde ''disk_image''<br />
<br />
=== User-mode networking ===<br />
<br />
By default, without any {{ic|-netdev}} arguments, QEMU will use user-mode networking with a built-in DHCP server. Your virtual machines will be assigned an IP address when they run their DHCP client, and they will be able to access the physical host's network through IP masquerading done by QEMU.<br />
<br />
{{Note|ICMPv6 will not work, as support for it is not implemented: {{ic|Slirp: external icmpv6 not supported yet}}. [[Ping]]ing an IPv6 address will not work.}}<br />
<br />
This default configuration allows your virtual machines to easily access the Internet, provided that the host is connected to it, but the virtual machines will not be directly visible on the external network, nor will virtual machines be able to talk to each other if you start up more than one concurrently.<br />
<br />
QEMU's user-mode networking can offer more capabilities such as built-in TFTP or SMB servers, redirecting host ports to the guest (for example to allow SSH connections to the guest) or attaching guests to VLANs so that they can talk to each other. See the QEMU documentation on the {{ic|-net user}} flag for more details.<br />
<br />
However, user-mode networking has limitations in both utility and performance. More advanced network configurations require the use of tap devices or other methods.<br />
<br />
{{Note|If the host system uses [[systemd-networkd]], make sure to symlink the {{ic|/etc/resolv.conf}} file as described in [[systemd-networkd#Required services and setup]], otherwise the DNS lookup in the guest system will not work.}}<br />
<br />
{{Tip|<br />
* To use the virtio driver with user-mode networking, the option is: {{ic|1=-nic user,model=virtio-net-pci}}.<br />
* You can isolate user-mode networking from the host and the outside world by adding {{ic|1=restrict=y}}, for example: {{ic|1=-net user,restrict=y}}<br />
}}<br />
<br />
=== Tap networking with QEMU ===<br />
<br />
[[wikipedia:TUN/TAP|Tap devices]] are a Linux kernel feature that allows you to create virtual network interfaces that appear as real network interfaces. Packets sent to a tap interface are delivered to a userspace program, such as QEMU, that has bound itself to the interface.<br />
<br />
QEMU can use tap networking for a virtual machine so that packets sent to the tap interface will be sent to the virtual machine and appear as coming from a network interface (usually an Ethernet interface) in the virtual machine. Conversely, everything that the virtual machine sends through its network interface will appear on the tap interface.<br />
<br />
Tap devices are supported by the Linux bridge drivers, so it is possible to bridge together tap devices with each other and possibly with other host interfaces such as {{ic|eth0}}. This is desirable if you want your virtual machines to be able to talk to each other, or if you want other machines on your LAN to be able to talk to the virtual machines.<br />
<br />
{{Warning|If you bridge together tap device and some host interface, such as {{ic|eth0}}, your virtual machines will appear directly on the external network, which will expose them to possible attack. Depending on what resources your virtual machines have access to, you may need to take all the [[Firewalls|precautions]] you normally would take in securing a computer to secure your virtual machines. If the risk is too great, virtual machines have little resources or you set up multiple virtual machines, a better solution might be to use [[#Host-only networking|host-only networking]] and set up NAT. In this case you only need one firewall on the host instead of multiple firewalls for each guest.}}<br />
<br />
As indicated in the user-mode networking section, tap devices offer higher networking performance than user-mode. If the guest OS supports virtio network driver, then the networking performance will be increased considerably as well. Supposing the use of the tap0 device, that the virtio driver is used on the guest, and that no scripts are used to help start/stop networking, next is part of the qemu command one should see:<br />
<br />
-device virtio-net,netdev=network0 -netdev tap,id=network0,ifname=tap0,script=no,downscript=no<br />
<br />
But if already using a tap device with virtio networking driver, one can even boost the networking performance by enabling vhost, like:<br />
<br />
-device virtio-net,netdev=network0 -netdev tap,id=network0,ifname=tap0,script=no,downscript=no,vhost=on<br />
<br />
See [https://web.archive.org/web/20160222161955/http://www.linux-kvm.com:80/content/how-maximize-virtio-net-performance-vhost-net] for more information.<br />
<br />
==== Host-only networking ====<br />
<br />
If the bridge is given an IP address and traffic destined for it is allowed, but no real interface (e.g. {{ic|eth0}}) is connected to the bridge, then the virtual machines will be able to talk to each other and the host system. However, they will not be able to talk to anything on the external network, provided that you do not set up IP masquerading on the physical host. This configuration is called ''host-only networking'' by other virtualization software such as [[VirtualBox]].<br />
<br />
{{Tip|<br />
* If you want to set up IP masquerading, e.g. NAT for virtual machines, see the [[Internet sharing#Enable NAT]] page.<br />
* See [[Network bridge]] for information on creating bridge.<br />
* You may want to have a DHCP server running on the bridge interface to service the virtual network. For example, to use the {{ic|172.20.0.1/16}} subnet with [[dnsmasq]] as the DHCP server:<br />
<br />
{{bc|1=<br />
# ip addr add 172.20.0.1/16 dev br0<br />
# ip link set br0 up<br />
# dnsmasq --interface=br0 --bind-interfaces --dhcp-range=172.20.0.2,172.20.255.254<br />
}}<br />
}}<br />
<br />
==== Internal networking ====<br />
<br />
If you do not give the bridge an IP address and add an [[iptables]] rule to drop all traffic to the bridge in the INPUT chain, then the virtual machines will be able to talk to each other, but not to the physical host or to the outside network. This configuration is called ''internal networking'' by other virtualization software such as [[VirtualBox]]. You will need to either assign static IP addresses to the virtual machines or run a DHCP server on one of them.<br />
<br />
By default iptables would drop packets in the bridge network. You may need to use such iptables rule to allow packets in a bridged network:<br />
<br />
# iptables -I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Bridged networking using qemu-bridge-helper ====<br />
<br />
This method does not require a start-up script and readily accommodates multiple taps and multiple bridges. It uses {{ic|/usr/lib/qemu/qemu-bridge-helper}} binary, which allows creating tap devices on an existing bridge.<br />
<br />
{{Tip|<br />
* See [[Network bridge]] for information on creating bridge.<br />
* See https://wiki.qemu.org/Features/HelperNetworking for more information on QEMU's network helper.<br />
}}<br />
<br />
First, create a configuration file containing the names of all bridges to be used by QEMU:<br />
<br />
{{hc|/etc/qemu/bridge.conf|<br />
allow ''br0''<br />
allow ''br1''<br />
...}}<br />
<br />
Make sure {{ic|/etc/qemu/}} has {{ic|755}} [[permissions]]. [https://gitlab.com/qemu-project/qemu/-/issues/515 QEMU issues] and [https://www.gns3.com/community/discussions/gns3-cannot-work-with-qemu GNS3 issues] may arise if this is not the case.<br />
<br />
Now start the virtual machine; the most basic usage to run QEMU with the default network helper and default bridge {{ic|br0}}:<br />
<br />
$ qemu-system-x86_64 -nic bridge ''[...]''<br />
<br />
Using the bridge {{ic|br1}} and the virtio driver:<br />
<br />
$ qemu-system-x86_64 -nic bridge,br=''br1'',model=virtio-net-pci ''[...]''<br />
<br />
==== Creating bridge manually ====<br />
<br />
{{Style|This section needs serious cleanup and may contain out-of-date information.}}<br />
<br />
{{Tip|Since QEMU 1.1, the [https://wiki.qemu.org/Features/HelperNetworking network bridge helper] can set tun/tap up for you without the need for additional scripting. See [[#Bridged networking using qemu-bridge-helper]].}}<br />
<br />
The following describes how to bridge a virtual machine to a host interface such as {{ic|eth0}}, which is probably the most common configuration. This configuration makes it appear that the virtual machine is located directly on the external network, on the same Ethernet segment as the physical host machine.<br />
<br />
We will replace the normal Ethernet adapter with a bridge adapter and bind the normal Ethernet adapter to it.<br />
<br />
* Install {{Pkg|bridge-utils}}, which provides {{ic|brctl}} to manipulate bridges.<br />
<br />
* Enable IPv4 forwarding:<br />
<br />
# sysctl -w net.ipv4.ip_forward=1<br />
<br />
To make the change permanent, change {{ic|1=net.ipv4.ip_forward = 0}} to {{ic|1=net.ipv4.ip_forward = 1}} in {{ic|/etc/sysctl.d/99-sysctl.conf}}.<br />
<br />
* Load the {{ic|tun}} module and configure it to be loaded on boot. See [[Kernel modules]] for details.<br />
<br />
* Optionally create the bridge. See [[Bridge with netctl]] for details. Remember to name your bridge as {{ic|br0}}, or change the scripts below to your bridge's name. In the {{ic|run-qemu}} script below, {{ic|br0}} is set up if not listed, as it is assumed that by default the host is not accessing network via the bridge.<br />
<br />
* Create the script that QEMU uses to bring up the tap adapter with {{ic|root:kvm}} 750 permissions:<br />
<br />
{{hc|/etc/qemu-ifup|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifup"<br />
echo "Bringing up $1 for bridged mode..."<br />
sudo /usr/bin/ip link set $1 up promisc on<br />
echo "Adding $1 to br0..."<br />
sudo /usr/bin/brctl addif br0 $1<br />
sleep 2<br />
</nowiki>}}<br />
<br />
* Create the script that QEMU uses to bring down the tap adapter in {{ic|/etc/qemu-ifdown}} with {{ic|root:kvm}} 750 permissions:<br />
{{hc|/etc/qemu-ifdown|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifdown"<br />
sudo /usr/bin/ip link set $1 down<br />
sudo /usr/bin/brctl delif br0 $1<br />
sudo /usr/bin/ip link delete dev $1<br />
</nowiki>}}<br />
<br />
* Use {{ic|visudo}} to add the following to your {{ic|sudoers}} file:<br />
<br />
{{bc|<nowiki><br />
Cmnd_Alias QEMU=/usr/bin/ip,/usr/bin/modprobe,/usr/bin/brctl<br />
%kvm ALL=NOPASSWD: QEMU<br />
</nowiki>}}<br />
<br />
* You launch QEMU using the following {{ic|run-qemu}} script:<br />
<br />
{{hc|run-qemu|<nowiki><br />
#!/bin/bash<br />
: '<br />
e.g. with img created via:<br />
qemu-img create -f qcow2 example.img 90G<br />
run-qemu -cdrom archlinux-x86_64.iso -boot order=d -drive file=example.img,format=qcow2 -m 4G -enable-kvm -cpu host -smp 4<br />
run-qemu -drive file=example.img,format=qcow2 -m 4G -enable-kvm -cpu host -smp 4<br />
'<br />
<br />
nicbr0() {<br />
sudo ip link set dev $1 promisc on up &> /dev/null<br />
sudo ip addr flush dev $1 scope host &>/dev/null<br />
sudo ip addr flush dev $1 scope site &>/dev/null<br />
sudo ip addr flush dev $1 scope global &>/dev/null<br />
sudo ip link set dev $1 master br0 &> /dev/null<br />
}<br />
_nicbr0() {<br />
sudo ip link set $1 promisc off down &> /dev/null<br />
sudo ip link set dev $1 nomaster &> /dev/null<br />
}<br />
<br />
HASBR0="$( ip link show | grep br0 )"<br />
if [ -z $HASBR0 ] ; then<br />
ROUTER="192.168.1.1"<br />
SUBNET="192.168.1."<br />
NIC=$(ip link show | grep en | grep 'state UP' | head -n 1 | cut -d":" -f 2 | xargs)<br />
IPADDR=$(ip addr show | grep -o "inet $SUBNET\([0-9]*\)" | cut -d ' ' -f2)<br />
sudo ip link add name br0 type bridge &> /dev/null<br />
sudo ip link set dev br0 up<br />
sudo ip addr add $IPADDR/24 brd + dev br0<br />
sudo ip route del default &> /dev/null<br />
sudo ip route add default via $ROUTER dev br0 onlink<br />
nicbr0 $NIC<br />
sudo iptables -I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
fi<br />
<br />
USERID=$(whoami)<br />
precreationg=$(ip tuntap list | cut -d: -f1 | sort)<br />
sudo ip tuntap add user $USERID mode tap<br />
postcreation=$(ip tuntap list | cut -d: -f1 | sort)<br />
TAP=$(comm -13 <(echo "$precreationg") <(echo "$postcreation"))<br />
nicbr0 $TAP<br />
<br />
printf -v MACADDR "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
qemu-system-x86_64 -net nic,macaddr=$MACADDR,model=virtio \<br />
-net tap,ifname=$TAP,script=no,downscript=no,vhost=on \<br />
$@<br />
<br />
_nicbr0 $TAP<br />
sudo ip link set dev $TAP down &> /dev/null<br />
sudo ip tuntap del $TAP mode tap<br />
<br />
if [ -z $HASBR0 ] ; then<br />
_nicbr0 $NIC<br />
sudo ip addr del dev br0 $IPADDR/24 &> /dev/null<br />
sudo ip link set dev br0 down<br />
sudo ip link delete br0 type bridge &> /dev/null<br />
sudo ip route del default &> /dev/null<br />
sudo ip link set dev $NIC up<br />
sudo ip route add default via $ROUTER dev $NIC onlink &> /dev/null<br />
fi<br />
</nowiki>}}<br />
<br />
Then to launch a virtual machine, do something like this<br />
<br />
$ run-qemu -hda ''myvm.img'' -m 512<br />
<br />
* It is recommended for performance and security reasons to disable the [http://ebtables.netfilter.org/documentation/bridge-nf.html firewall on the bridge]:<br />
<br />
{{hc|/etc/sysctl.d/10-disable-firewall-on-bridge.conf|<nowiki><br />
net.bridge.bridge-nf-call-ip6tables = 0<br />
net.bridge.bridge-nf-call-iptables = 0<br />
net.bridge.bridge-nf-call-arptables = 0<br />
</nowiki>}}<br />
<br />
In order to apply the parameters described above on boot, you will also need to load the br-netfilter module on boot. Otherwise, the parameters will not exist when sysctl will try to modify them.<br />
<br />
{{hc|/etc/modules-load.d/br_netfilter.conf|<nowiki><br />
br_netfilter<br />
</nowiki>}}<br />
<br />
Run {{ic|sysctl -p /etc/sysctl.d/10-disable-firewall-on-bridge.conf}} to apply the changes immediately.<br />
<br />
See the [https://wiki.libvirt.org/page/Networking#Creating_network_initscripts libvirt wiki] and [https://bugzilla.redhat.com/show_bug.cgi?id=512206 Fedora bug 512206]. If you get errors by sysctl during boot about non-existing files, make the {{ic|bridge}} module load at boot. See [[Kernel module#systemd]].<br />
<br />
Alternatively, you can configure [[iptables]] to allow all traffic to be forwarded across the bridge by adding a rule like this:<br />
<br />
-I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Network sharing between physical device and a Tap device through iptables ====<br />
<br />
{{Merge|Internet_sharing|Duplication, not specific to QEMU.}}<br />
<br />
Bridged networking works fine between a wired interface (Eg. eth0), and it is easy to setup. However if the host gets connected to the network through a wireless device, then bridging is not possible.<br />
<br />
See [[Network bridge#Wireless interface on a bridge]] as a reference.<br />
<br />
One way to overcome that is to setup a tap device with a static IP, making linux automatically handle the routing for it, and then forward traffic between the tap interface and the device connected to the network through iptables rules.<br />
<br />
See [[Internet sharing]] as a reference.<br />
<br />
There you can find what is needed to share the network between devices, included tap and tun ones. The following just hints further on some of the host configurations required. As indicated in the reference above, the client needs to be configured for a static IP, using the IP assigned to the tap interface as the gateway. The caveat is that the DNS servers on the client might need to be manually edited if they change when changing from one host device connected to the network to another.<br />
<br />
To allow IP forwarding on every boot, one need to add the following lines to sysctl configuration file inside {{ic|/etc/sysctl.d}}:<br />
<br />
net.ipv4.ip_forward = 1<br />
net.ipv6.conf.default.forwarding = 1<br />
net.ipv6.conf.all.forwarding = 1<br />
<br />
The iptables rules can look like:<br />
<br />
# Forwarding from/to outside<br />
iptables -A FORWARD -i ${INT} -o ${EXT_0} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_1} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_2} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_0} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_1} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_2} -o ${INT} -j ACCEPT<br />
# NAT/Masquerade (network address translation)<br />
iptables -t nat -A POSTROUTING -o ${EXT_0} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_1} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_2} -j MASQUERADE<br />
<br />
The prior supposes there are 3 devices connected to the network sharing traffic with one internal device, where for example:<br />
<br />
INT=tap0<br />
EXT_0=eth0<br />
EXT_1=wlan0<br />
EXT_2=tun0<br />
<br />
The prior shows a forwarding that would allow sharing wired and wireless connections with the tap device.<br />
<br />
The forwarding rules shown are stateless, and for pure forwarding. One could think of restricting specific traffic, putting a firewall in place to protect the guest and others. However those would decrease the networking performance, while a simple bridge does not include any of that.<br />
<br />
Bonus: Whether the connection is wired or wireless, if one gets connected through VPN to a remote site with a tun device, supposing the tun device opened for that connection is tun0, and the prior iptables rules are applied, then the remote connection gets also shared with the guest. This avoids the need for the guest to also open a VPN connection. Again, as the guest networking needs to be static, then if connecting the host remotely this way, one most probably will need to edit the DNS servers on the guest.<br />
<br />
=== Networking with VDE2 ===<br />
<br />
{{Style|This section needs serious cleanup and may contain out-of-date information.}}<br />
<br />
==== What is VDE? ====<br />
<br />
VDE stands for Virtual Distributed Ethernet. It started as an enhancement of [[User-mode Linux|uml]]_switch. It is a toolbox to manage virtual networks.<br />
<br />
The idea is to create virtual switches, which are basically sockets, and to "plug" both physical and virtual machines in them. The configuration we show here is quite simple; However, VDE is much more powerful than this, it can plug virtual switches together, run them on different hosts and monitor the traffic in the switches. You are invited to read [https://wiki.virtualsquare.org/ the documentation of the project].<br />
<br />
The advantage of this method is you do not have to add sudo privileges to your users. Regular users should not be allowed to run modprobe.<br />
<br />
==== Basics ====<br />
<br />
VDE support can be [[install]]ed via the {{Pkg|vde2}} package.<br />
<br />
In our config, we use tun/tap to create a virtual interface on my host. Load the {{ic|tun}} module (see [[Kernel modules]] for details):<br />
<br />
# modprobe tun<br />
<br />
Now create the virtual switch:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
<br />
This line creates the switch, creates {{ic|tap0}}, "plugs" it, and allows the users of the group {{ic|users}} to use it.<br />
<br />
The interface is plugged in but not configured yet. To configure it, run this command:<br />
<br />
# ip addr add 192.168.100.254/24 dev tap0<br />
<br />
Now, you just have to run KVM with these {{ic|-net}} options as a normal user:<br />
<br />
$ qemu-system-x86_64 -net nic -net vde -hda ''[...]''<br />
<br />
Configure networking for your guest as you would do in a physical network.<br />
<br />
{{Tip|You might want to set up NAT on tap device to access the internet from the virtual machine. See [[Internet sharing#Enable NAT]] for more information.}}<br />
<br />
==== Startup scripts ====<br />
<br />
Example of main script starting VDE:<br />
<br />
{{hc|/etc/systemd/scripts/qemu-network-env|<nowiki><br />
#!/bin/sh<br />
# QEMU/VDE network environment preparation script<br />
<br />
# The IP configuration for the tap device that will be used for<br />
# the virtual machine network:<br />
<br />
TAP_DEV=tap0<br />
TAP_IP=192.168.100.254<br />
TAP_MASK=24<br />
TAP_NETWORK=192.168.100.0<br />
<br />
# Host interface<br />
NIC=eth0<br />
<br />
case "$1" in<br />
start)<br />
echo -n "Starting VDE network for QEMU: "<br />
<br />
# If you want tun kernel module to be loaded by script uncomment here<br />
#modprobe tun 2>/dev/null<br />
## Wait for the module to be loaded<br />
#while ! lsmod | grep -q "^tun"; do echo "Waiting for tun device"; sleep 1; done<br />
<br />
# Start tap switch<br />
vde_switch -tap "$TAP_DEV" -daemon -mod 660 -group users<br />
<br />
# Bring tap interface up<br />
ip address add "$TAP_IP"/"$TAP_MASK" dev "$TAP_DEV"<br />
ip link set "$TAP_DEV" up<br />
<br />
# Start IP Forwarding<br />
echo "1" > /proc/sys/net/ipv4/ip_forward<br />
iptables -t nat -A POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
;;<br />
stop)<br />
echo -n "Stopping VDE network for QEMU: "<br />
# Delete the NAT rules<br />
iptables -t nat -D POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
<br />
# Bring tap interface down<br />
ip link set "$TAP_DEV" down<br />
<br />
# Kill VDE switch<br />
pgrep vde_switch | xargs kill -TERM<br />
;;<br />
restart|reload)<br />
$0 stop<br />
sleep 1<br />
$0 start<br />
;;<br />
*)<br />
echo "Usage: $0 {start|stop|restart|reload}"<br />
exit 1<br />
esac<br />
exit 0<br />
</nowiki>}}<br />
<br />
Example of systemd service using the above script:<br />
<br />
{{hc|/etc/systemd/system/qemu-network-env.service|<nowiki><br />
[Unit]<br />
Description=Manage VDE Switch<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/etc/systemd/scripts/qemu-network-env start<br />
ExecStop=/etc/systemd/scripts/qemu-network-env stop<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
Change permissions for {{ic|qemu-network-env}} to be [[executable]]. <br />
<br />
You can [[start]] {{ic|qemu-network-env.service}} as usual.<br />
<br />
==== Alternative method ====<br />
<br />
If the above method does not work or you do not want to mess with kernel configs, TUN, dnsmasq, and iptables you can do the following for the same result.<br />
<br />
# vde_switch -daemon -mod 660 -group users<br />
# slirpvde --dhcp --daemon<br />
<br />
Then, to start the virtual machine with a connection to the network of the host:<br />
<br />
$ qemu-system-x86_64 -net nic,macaddr=52:54:00:00:EE:03 -net vde ''disk_image''<br />
<br />
=== VDE2 Bridge ===<br />
<br />
Based on [https://selamatpagicikgu.wordpress.com/2011/06/08/quickhowto-qemu-networking-using-vde-tuntap-and-bridge/ quickhowto: qemu networking using vde, tun/tap, and bridge] graphic. Any virtual machine connected to vde is externally exposed. For example, each virtual machine can receive DHCP configuration directly from your ADSL router.<br />
<br />
==== Basics ====<br />
<br />
Remember that you need {{ic|tun}} module and {{Pkg|bridge-utils}} package.<br />
<br />
Create the vde2/tap device:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
# ip link set tap0 up<br />
<br />
Create bridge:<br />
<br />
# brctl addbr br0<br />
<br />
Add devices:<br />
<br />
# brctl addif br0 eth0<br />
# brctl addif br0 tap0<br />
<br />
And configure bridge interface:<br />
<br />
# dhcpcd br0<br />
<br />
==== Startup scripts ====<br />
<br />
All devices must be set up. And only the bridge needs an IP address. For physical devices on the bridge (e.g. {{ic|eth0}}), this can be done with [[netctl]] using a custom Ethernet profile with:<br />
<br />
{{hc|/etc/netctl/ethernet-noip|2=<br />
Description='A more versatile static Ethernet connection'<br />
Interface=eth0<br />
Connection=ethernet<br />
IP=no<br />
}}<br />
<br />
The following custom systemd service can be used to create and activate a VDE2 tap interface for users in the {{ic|users}} user group.<br />
<br />
{{hc|/etc/systemd/system/vde2@.service|2=<br />
[Unit]<br />
Description=Network Connectivity for %i<br />
Wants=network.target<br />
Before=network.target<br />
<br />
[Service]<br />
Type=oneshot<br />
RemainAfterExit=yes<br />
ExecStart=/usr/bin/vde_switch -tap %i -daemon -mod 660 -group users<br />
ExecStart=/usr/bin/ip link set dev %i up<br />
ExecStop=/usr/bin/ip addr flush dev %i<br />
ExecStop=/usr/bin/ip link set dev %i down<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
}}<br />
<br />
And finally, you can create the [[Bridge with netctl|bridge interface with netctl]].<br />
<br />
=== Shorthand configuration ===<br />
<br />
If you are using QEMU with various networking options a lot, you probably have created a lot of {{ic|-netdev}} and {{ic|-device}} argument pairs, which gets quite repetitive. You can instead use the {{ic|-nic}} argument to combine {{ic|-netdev}} and {{ic|-device}} together, so that, for example, these arguments:<br />
<br />
-netdev tap,id=network0,ifname=tap0,script=no,downscript=no,vhost=on -device virtio-net-pci,netdev=network0<br />
<br />
become:<br />
<br />
-nic tap,script=no,downscript=no,vhost=on,model=virtio-net-pci<br />
<br />
Notice the lack of network IDs, and that the device was created with {{ic|1=model=}}. The first half of the {{ic|-nic}} parameters are {{ic|-netdev}} parameters, whereas the second half (after {{ic|1=model=}}) are related with the device. The same parameters (for example, {{ic|1=smb=}}) are used. To completely disable the networking use {{ic|-nic none}}.<br />
<br />
See [https://qemu.weilnetz.de/doc/6.0/system/net.html QEMU networking documentation] for more information on parameters you can use.<br />
<br />
== Graphic card ==<br />
<br />
QEMU can emulate a standard graphic card text mode using {{ic|-display curses}} command line option. This allows to type text and see text output directly inside a text terminal. Alternatively, {{ic|-nographic}} serves a similar purpose.<br />
<br />
QEMU can emulate several types of VGA card. The card type is passed in the {{ic|-vga ''type''}} command line option and can be {{ic|std}}, {{ic|qxl}}, {{ic|vmware}}, {{ic|virtio}}, {{ic|cirrus}} or {{ic|none}}.<br />
<br />
=== std ===<br />
<br />
With {{ic|-vga std}} you can get a resolution of up to 2560 x 1600 pixels without requiring guest drivers. This is the default since QEMU 2.2.<br />
<br />
=== qxl ===<br />
<br />
QXL is a paravirtual graphics driver with 2D support. To use it, pass the {{ic|-vga qxl}} option and install drivers in the guest. You may want to use [[#SPICE]] for improved graphical performance when using QXL.<br />
<br />
On Linux guests, the {{ic|qxl}} and {{ic|bochs_drm}} kernel modules must be loaded in order to gain a decent performance.<br />
<br />
Default VGA memory size for QXL devices is 16M which is sufficient to drive resolutions approximately up to QHD (2560x1440). To enable higher resolutions, [[#Multi-monitor support|increase vga_memmb]].<br />
<br />
=== vmware ===<br />
<br />
Although it is a bit buggy, it performs better than std and cirrus. Install the VMware drivers {{Pkg|xf86-video-vmware}} and {{Pkg|xf86-input-vmmouse}} for Arch Linux guests.<br />
<br />
=== virtio ===<br />
<br />
{{ic|virtio-vga}} / {{ic|virtio-gpu}} is a paravirtual 3D graphics driver based on [https://virgil3d.github.io/ virgl]. It's mature, currently supporting only Linux guests with {{Pkg|mesa}} compiled with the option {{ic|1=gallium-drivers=virgl}}.<br />
<br />
To enable 3D acceleration on the guest system, select this vga with {{ic|-device virtio-vga-gl}} and enable the OpenGL context in the display device with {{ic|1=-display sdl,gl=on}} or {{ic|1=-display gtk,gl=on}} for the SDL and GTK display output respectively. Successful configuration can be confirmed looking at the kernel log in the guest:<br />
<br />
{{hc|# dmesg {{!}} grep drm |<br />
[drm] pci: virtio-vga detected<br />
[drm] virgl 3d acceleration enabled<br />
}}<br />
<br />
=== cirrus ===<br />
<br />
The cirrus graphical adapter was the default [https://wiki.qemu.org/ChangeLog/2.2#VGA before 2.2]. It [https://www.kraxel.org/blog/2014/10/qemu-using-cirrus-considered-harmful/ should not] be used on modern systems.<br />
<br />
=== none ===<br />
<br />
This is like a PC that has no VGA card at all. You would not even be able to access it with the {{ic|-vnc}} option. Also, this is different from the {{ic|-nographic}} option which lets QEMU emulate a VGA card, but disables the SDL display.<br />
<br />
== SPICE ==<br />
<br />
The [https://www.spice-space.org/ SPICE project] aims to provide a complete open source solution for remote access to virtual machines in a seamless way.<br />
<br />
=== Enabling SPICE support on the host ===<br />
<br />
The following is an example of booting with SPICE as the remote desktop protocol, including the support for copy and paste from host:<br />
<br />
$ qemu-system-x86_64 -vga qxl -device virtio-serial-pci -spice port=5930,disable-ticketing=on -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
The parameters have the following meaning:<br />
<br />
# {{ic|-device virtio-serial-pci}} adds a virtio-serial device<br />
# {{ic|1=-spice port=5930,disable-ticketing=on}} set TCP port {{ic|5930}} for spice channels listening and allow client to connect without authentication{{Tip|Using [[wikipedia:Unix_socket|Unix sockets]] instead of TCP ports does not involve using network stack on the host system. It does not imply that packets are encapsulated and decapsulated to use the network and the related protocol. The sockets are identified solely by the inodes on the hard drive. It is therefore considered better for performance. Use instead {{ic|1=-spice unix=on,addr=/tmp/vm_spice.socket,disable-ticketing=on}}.}}<br />
# {{ic|1=-device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0}} opens a port for spice vdagent in the virtio-serial device,<br />
# {{ic|1=-chardev spicevmc,id=spicechannel0,name=vdagent}} adds a spicevmc chardev for that port. It is important that the {{ic|1=chardev=}} option of the {{ic|virtserialport}} device matches the {{ic|1=id=}} option given to the {{ic|chardev}} option ({{ic|spicechannel0}} in this example). It is also important that the port name is {{ic|com.redhat.spice.0}}, because that is the namespace where vdagent is looking for in the guest. And finally, specify {{ic|1=name=vdagent}} so that spice knows what this channel is for.<br />
<br />
=== Connecting to the guest with a SPICE client ===<br />
<br />
A SPICE client is necessary to connect to the guest. In Arch, the following clients are available:<br />
<br />
* {{App|virt-viewer|SPICE client recommended by the protocol developers, a subset of the virt-manager project.|https://virt-manager.org/|{{Pkg|virt-viewer}}}}<br />
* {{App|spice-gtk|SPICE GTK client, a subset of the SPICE project. Embedded into other applications as a widget.|https://www.spice-space.org/|{{Pkg|spice-gtk}}}}<br />
<br />
For clients that run on smartphone or on other platforms, refer to the ''Other clients'' section in [https://www.spice-space.org/download.html spice-space download].<br />
<br />
==== Manually running a SPICE client ====<br />
<br />
One way of connecting to a guest listening on Unix socket {{ic|/tmp/vm_spice.socket}} is to manually run the SPICE client using {{ic|$ remote-viewer spice+unix:///tmp/vm_spice.socket}} or {{ic|1=$ spicy --uri="spice+unix:///tmp/vm_spice.socket"}}, depending on the desired client. Since QEMU in SPICE mode acts similarly to a remote desktop server, it may be more convenient to run QEMU in daemon mode with the {{ic|-daemonize}} parameter.<br />
<br />
{{Tip|<br />
To connect to the guest through SSH tunneling, the following type of command can be used: {{bc|$ ssh -fL 5999:localhost:5930 ''my.domain.org'' sleep 10; spicy -h 127.0.0.1 -p 5999}}<br />
This example connects ''spicy'' to the local port {{ic|5999}} which is forwarded through SSH to the guest's SPICE server located at the address ''my.domain.org'', port {{ic|5930}}.<br />
Note the {{ic|-f}} option that requests ssh to execute the command {{ic|sleep 10}} in the background. This way, the ssh session runs while the client is active and auto-closes once the client ends.<br />
}}<br />
<br />
==== Running a SPICE client with QEMU ====<br />
<br />
QEMU can automatically start a SPICE client with an appropriate socket, if the display is set to SPICE with the {{ic|-display spice-app}} parameter. This will use the system's default SPICE client as the viewer, determined by your [[XDG MIME Applications#mimeapps.list|mimeapps.list]] files.<br />
<br />
=== Enabling SPICE support on the guest ===<br />
<br />
For '''Arch Linux guests''', for improved support for multiple monitors or clipboard sharing, the following packages should be installed:<br />
* {{Pkg|spice-vdagent}}: Spice agent xorg client that enables copy and paste between client and X-session and more. (Refer to this [https://github.com/systemd/systemd/issues/18791 issue], until fixed, for workarounds to get this to work on non-GNOME desktops.)<br />
* {{Pkg|xf86-video-qxl}}: Xorg X11 qxl video driver<br />
* {{AUR|x-resize}}: Desktop environments other than GNOME do not react automatically when the SPICE client window is resized. This package uses a [[udev]] rule and [[xrandr]] to implement auto-resizing for all X11-based desktop environments and window managers.<br />
For guests under '''other operating systems''', refer to the ''Guest'' section in spice-space [https://www.spice-space.org/download.html download].<br />
<br />
=== Password authentication with SPICE ===<br />
<br />
If you want to enable password authentication with SPICE you need to remove {{ic|disable-ticketing}} from the {{ic|-spice}} argument and instead add {{ic|1=password=''yourpassword''}}. For example:<br />
<br />
$ qemu-system-x86_64 -vga qxl -spice port=5900,password=''yourpassword'' -device virtio-serial-pci -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
Your SPICE client should now ask for the password to be able to connect to the SPICE server.<br />
<br />
=== TLS encrypted communication with SPICE ===<br />
<br />
You can also configure TLS encryption for communicating with the SPICE server. First, you need to have a directory which contains the following files (the names must be exactly as indicated):<br />
<br />
* {{ic|ca-cert.pem}}: the CA master certificate.<br />
* {{ic|server-cert.pem}}: the server certificate signed with {{ic|ca-cert.pem}}.<br />
* {{ic|server-key.pem}}: the server private key.<br />
<br />
An example of generation of self-signed certificates with your own generated CA for your server is shown in the [https://www.spice-space.org/spice-user-manual.html#_generating_self_signed_certificates Spice User Manual].<br />
<br />
Afterwards, you can run QEMU with SPICE as explained above but using the following {{ic|-spice}} argument: {{ic|1=-spice tls-port=5901,password=''yourpassword'',x509-dir=''/path/to/pki_certs''}}, where {{ic|''/path/to/pki_certs''}} is the directory path that contains the three needed files shown earlier.<br />
<br />
It is now possible to connect to the server using {{Pkg|virt-viewer}}:<br />
<br />
$ remote-viewer spice://''hostname''?tls-port=5901 --spice-ca-file=''/path/to/ca-cert.pem'' --spice-host-subject="C=''XX'',L=''city'',O=''organization'',CN=''hostname''" --spice-secure-channels=all<br />
<br />
Keep in mind that the {{ic|--spice-host-subject}} parameter needs to be set according to your {{ic|server-cert.pem}} subject. You also need to copy {{ic|ca-cert.pem}} to every client to verify the server certificate.<br />
<br />
{{Tip|You can get the subject line of the server certificate in the correct format for {{ic|--spice-host-subject}} (with entries separated by commas) using the following command: {{bc|<nowiki>$ openssl x509 -noout -subject -in server-cert.pem | cut -d' ' -f2- | sed 's/\///' | sed 's/\//,/g'</nowiki>}}<br />
}}<br />
<br />
The equivalent {{Pkg|spice-gtk}} command is:<br />
<br />
$ spicy -h ''hostname'' -s 5901 --spice-ca-file=ca-cert.pem --spice-host-subject="C=''XX'',L=''city'',O=''organization'',CN=''hostname''" --spice-secure-channels=all<br />
<br />
== VNC ==<br />
<br />
One can add the {{ic|-vnc :''X''}} option to have QEMU redirect the VGA display to the VNC session. Substitute {{ic|''X''}} for the number of the display (0 will then listen on 5900, 1 on 5901...).<br />
<br />
$ qemu-system-x86_64 -vnc :0<br />
<br />
An example is also provided in the [[#Starting QEMU virtual machines on boot]] section.<br />
<br />
{{Warning|The default VNC server setup does not use any form of authentication. Any user can connect from any host.}}<br />
<br />
=== Basic password authentication ===<br />
<br />
An access password can be setup easily by using the {{ic|password}} option. The password must be indicated in the QEMU monitor and connection is only possible once the password is provided.<br />
<br />
$ qemu-system-x86_64 -vnc :0,password -monitor stdio<br />
<br />
In the QEMU monitor, password is set using the command {{ic|change vnc password}} and then indicating the password.<br />
<br />
The following command line directly runs vnc with a password:<br />
<br />
$ printf "change vnc password\n%s\n" MYPASSWORD | qemu-system-x86_64 -vnc :0,password -monitor stdio<br />
<br />
{{Note|The password is limited to 8 characters and can be guessed through brute force attack. More elaborated protection is strongly recommended for public network.}}<br />
<br />
== Audio ==<br />
<br />
=== Creating an audio backend ===<br />
<br />
The {{ic|-audiodev}} flag sets the audio backend driver on the host and its options.<br />
<br />
To list availabe audio backend drivers:<br />
<br />
$ qemu-system-x86_64 -audiodev help<br />
<br />
Their optional settings are detailed in the {{man|1|qemu}} man page.<br />
<br />
At the bare minimum, one need to choose an audio backend and set an id, for [[PulseAudio]] for example:<br />
<br />
-audiodev pa,id=snd0<br />
<br />
=== Using the audio backend ===<br />
<br />
==== Intel HD Audio ====<br />
<br />
For Intel HD Audio emulation, add both controller and codec devices. To list the available Intel HDA Audio devices:<br />
<br />
$ qemu-system-x86_64 -device help | grep hda<br />
<br />
Add the audio controller:<br />
<br />
-device ich9-intel-hda<br />
<br />
Also add the audio codec and map it to a host audio backend id:<br />
<br />
-device hda-output,audiodev=snd0<br />
<br />
==== Intel 82801AA AC97 ====<br />
<br />
For AC97 emulation just add the audio card device and map it to a host audio backend id<br />
<br />
-device AC97,audiodev=snd0<br />
<br />
{{Note|<br />
* If the audiodev backend is not provided, QEMU looks up for it and adds it automatically, this only works for a single audiodev. For example {{ic|-device intel-hda -device hda-duplex}} will emulate {{ic|intel-hda}} on the guest using the default audiodev backend.<br />
* Video graphic card emulated drivers for the guest machine may also cause a problem with the sound quality. Test one by one to make it work. You can list possible options with {{ic|<nowiki>qemu-system-x86_64 -h | grep vga</nowiki>}}.<br />
}}<br />
<br />
==== VirtIO-Sound ====<br />
<br />
VirtIO sound is also available since QEMU 8.2.0. Usage example is below:<br />
<br />
-device virtio-sound-pci,audiodev=my_audiodev \<br />
-audiodev alsa,id=my_audiodev<br />
<br />
More information can be found [https://qemu-project.gitlab.io/qemu/system/devices/virtio-snd.html here].<br />
<br />
== Installing virtio drivers ==<br />
<br />
QEMU offers guests the ability to use paravirtualized block and network devices using the [https://wiki.libvirt.org/page/Virtio virtio] drivers, which provide better performance and lower overhead.<br />
<br />
* A virtio block device requires the option {{ic|-drive}} for passing a disk image, with parameter {{ic|1=if=virtio}}:<br />
$ qemu-system-x86_64 -drive file=''disk_image'',if='''virtio'''<br />
<br />
* Almost the same goes for the network:<br />
$ qemu-system-x86_64 -nic user,model='''virtio-net-pci'''<br />
<br />
{{Note|This will only work if the guest machine has drivers for virtio devices. Linux does, and the required drivers are included in Arch Linux, but there is no guarantee that virtio devices will work with other operating systems.}}<br />
<br />
=== Preparing an Arch Linux guest ===<br />
<br />
To use virtio devices after an Arch Linux guest has been installed, the following modules must be loaded in the guest: {{ic|virtio}}, {{ic|virtio_pci}}, {{ic|virtio_blk}}, {{ic|virtio_net}}, and {{ic|virtio_ring}}. For 32-bit guests, the specific "virtio" module is not necessary.<br />
<br />
If you want to boot from a virtio disk, the initial ramdisk must contain the necessary modules. By default, this is handled by [[mkinitcpio]]'s {{ic|autodetect}} hook. Otherwise use the {{ic|MODULES}} array in {{ic|/etc/mkinitcpio.conf}} to include the necessary modules and rebuild the initial ramdisk.<br />
<br />
{{hc|/etc/mkinitcpio.conf|2=<br />
MODULES=(virtio virtio_blk virtio_pci virtio_net)}}<br />
<br />
Virtio disks are recognized with the prefix {{ic|'''v'''}} (e.g. {{ic|'''v'''da}}, {{ic|'''v'''db}}, etc.); therefore, changes must be made in at least {{ic|/etc/fstab}} and {{ic|/boot/grub/grub.cfg}} when booting from a virtio disk.<br />
<br />
{{Tip|When referencing disks by [[UUID]] in both {{ic|/etc/fstab}} and boot loader, nothing has to be done.}}<br />
<br />
Further information on paravirtualization with KVM can be found [https://www.linux-kvm.org/page/Boot_from_virtio_block_device here].<br />
<br />
You might also want to install {{Pkg|qemu-guest-agent}} to implement support for QMP commands that will enhance the hypervisor management capabilities.<br />
<br />
=== Preparing a Windows guest ===<br />
<br />
==== Virtio drivers for Windows ====<br />
<br />
Windows does not come with the virtio drivers. The latest and stable versions of the drivers are regularly built by Fedora, details on downloading the drivers are given on [https://github.com/virtio-win/virtio-win-pkg-scripts/blob/master/README.md virtio-win on GitHub]. In the following sections we will mostly use the stable ISO file provided here: [https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/stable-virtio/virtio-win.iso virtio-win.iso]. Alternatively, use {{AUR|virtio-win}}.<br />
<br />
==== Block device drivers ====<br />
<br />
===== New Install of Windows =====<br />
<br />
The drivers need to be loaded during installation, the procedure is to load the ISO image with the virtio drivers in a cdrom device along with the primary disk device and the Windows ISO install media:<br />
<br />
$ qemu-system-x86_64 ... \<br />
-drive file=''disk_image'',index=0,media=disk,if=virtio \<br />
-drive file=''windows.iso'',index=2,media=cdrom \<br />
-drive file=''virtio-win.iso'',index=3,media=cdrom \<br />
...<br />
<br />
During the installation, at some stage, the Windows installer will ask "Where do you want to install Windows?", it will give a warning that no disks are found. Follow the example instructions below (based on Windows Server 2012 R2 with Update).<br />
<br />
* Select the option ''Load Drivers''.<br />
* Uncheck the box for ''Hide drivers that are not compatible with this computer's hardware''.<br />
* Click the browse button and open the CDROM for the virtio iso, usually named "virtio-win-XX".<br />
* Now browse to {{ic|E:\viostor\[your-os]\amd64}}, select it, and confirm.<br />
<br />
You should now see your virtio disk(s) listed here, ready to be selected, formatted and installed to.<br />
<br />
===== Change existing Windows virtual machine to use virtio =====<br />
<br />
Modifying an existing Windows guest for booting from virtio disk requires that the virtio driver is loaded by the guest at boot time.<br />
We will therefore need to teach Windows to load the virtio driver at boot time before being able to boot a disk image in virtio mode.<br />
<br />
To achieve that, first create a new disk image that will be attached in virtio mode and trigger the search for the driver:<br />
<br />
$ qemu-img create -f qcow2 ''dummy.qcow2'' 1G<br />
<br />
Run the original Windows guest with the boot disk still in IDE mode, the fake disk in virtio mode and the driver ISO image.<br />
<br />
$ qemu-system-x86_64 -m 4G -drive file=''disk_image'',if=ide -drive file=''dummy.qcow2'',if=virtio -cdrom virtio-win.iso<br />
<br />
Windows will detect the fake disk and look for a suitable driver. If it fails, go to ''Device Manager'', locate the SCSI drive with an exclamation mark icon (should be open), click ''Update driver'' and select the virtual CD-ROM. Do not navigate to the driver folder within the CD-ROM, simply select the CD-ROM drive and Windows will find the appropriate driver automatically (tested for Windows 7 SP1).<br />
<br />
Request Windows to boot in safe mode next time it starts up. This can be done using the ''msconfig.exe'' tool in Windows. In safe mode all the drivers will be loaded at boot time including the new virtio driver. Once Windows knows that the virtio driver is required at boot it will memorize it for future boot.<br />
<br />
Once instructed to boot in safe mode, you can turn off the virtual machine and launch it again, now with the boot disk attached in virtio mode:<br />
<br />
$ qemu-system-x86_64 -m 4G -drive file=''disk_image'',if=virtio<br />
<br />
You should boot in safe mode with virtio driver loaded, you can now return to ''msconfig.exe'' disable safe mode boot and restart Windows.<br />
<br />
{{Note|If you encounter the blue screen of death using the {{ic|1=if=virtio}} parameter, it probably means the virtio disk driver is not installed or not loaded at boot time, reboot in safe mode and check your driver configuration.}}<br />
<br />
==== Network drivers ====<br />
<br />
Installing virtio network drivers is a bit easier, simply add the {{ic|-nic}} argument.<br />
<br />
$ qemu-system-x86_64 -m 4G -drive file=''windows_disk_image'',if=virtio -nic user,model=virtio-net-pci -cdrom virtio-win.iso<br />
<br />
Windows will detect the network adapter and try to find a driver for it. If it fails, go to the ''Device Manager'', locate the network adapter with an exclamation mark icon (should be open), click ''Update driver'' and select the virtual CD-ROM. Do not forget to select the checkbox which says to search for directories recursively.<br />
<br />
==== Balloon driver ====<br />
<br />
If you want to track you guest memory state (for example via {{ic|virsh}} command {{ic|dommemstat}}) or change guest's memory size in runtime (you still will not be able to change memory size, but can limit memory usage via inflating balloon driver) you will need to install guest balloon driver.<br />
<br />
For this you will need to go to ''Device Manager'', locate ''PCI standard RAM Controller'' in ''System devices'' (or unrecognized PCI controller from ''Other devices'') and choose ''Update driver''. In opened window you will need to choose ''Browse my computer...'' and select the CD-ROM (and do not forget the ''Include subdirectories'' checkbox). Reboot after installation. This will install the driver and you will be able to inflate the balloon (for example via hmp command {{ic|balloon ''memory_size''}}, which will cause balloon to take as much memory as possible in order to shrink the guest's available memory size to ''memory_size''). However, you still will not be able to track guest memory state. In order to do this you will need to install ''Balloon'' service properly. For that open command line as administrator, go to the CD-ROM, ''Balloon'' directory and deeper, depending on your system and architecture. Once you are in ''amd64'' (''x86'') directory, run {{ic|blnsrv.exe -i}} which will do the installation. After that {{ic|virsh}} command {{ic|dommemstat}} should be outputting all supported values.<br />
<br />
=== Preparing a FreeBSD guest ===<br />
<br />
Install the {{ic|emulators/virtio-kmod}} port if you are using FreeBSD 8.3 or later up until 10.0-CURRENT where they are included into the kernel. After installation, add the following to your {{ic|/boot/loader.conf}} file:<br />
<br />
{{bc|1=<br />
virtio_load="YES"<br />
virtio_pci_load="YES"<br />
virtio_blk_load="YES"<br />
if_vtnet_load="YES"<br />
virtio_balloon_load="YES"<br />
}}<br />
<br />
Then modify your {{ic|/etc/fstab}} by doing the following:<br />
<br />
# sed -ibak "s/ada/vtbd/g" /etc/fstab<br />
<br />
And verify that {{ic|/etc/fstab}} is consistent. If anything goes wrong, just boot into a rescue CD and copy {{ic|/etc/fstab.bak}} back to {{ic|/etc/fstab}}.<br />
<br />
== QEMU monitor ==<br />
<br />
While QEMU is running, a monitor console is provided in order to provide several ways to interact with the virtual machine running. The QEMU monitor offers interesting capabilities such as obtaining information about the current virtual machine, hotplugging devices, creating snapshots of the current state of the virtual machine, etc. To see the list of all commands, run {{ic|help}} or {{ic|?}} in the QEMU monitor console or review the relevant section of the [https://www.qemu.org/docs/master/system/monitor.html official QEMU documentation].<br />
<br />
=== Accessing the monitor console ===<br />
<br />
==== Graphical view ====<br />
<br />
When using the {{ic|std}} default graphics option, one can access the QEMU monitor by pressing {{ic|Ctrl+Alt+2}} or by clicking ''View > compatmonitor0'' in the QEMU window. To return to the virtual machine graphical view either press {{ic|Ctrl+Alt+1}} or click ''View > VGA''.<br />
<br />
However, the standard method of accessing the monitor is not always convenient and does not work in all graphic outputs QEMU supports.<br />
<br />
==== Telnet ====<br />
<br />
To enable [[telnet]], run QEMU with the {{ic|-monitor telnet:127.0.0.1:''port'',server,nowait}} parameter. When the virtual machine is started you will be able to access the monitor via telnet:<br />
<br />
$ telnet 127.0.0.1 ''port''<br />
<br />
{{Note|If {{ic|127.0.0.1}} is specified as the IP to listen it will be only possible to connect to the monitor from the same host QEMU is running on. If connecting from remote hosts is desired, QEMU must be told to listen {{ic|0.0.0.0}} as follows: {{ic|-monitor telnet:0.0.0.0:''port'',server,nowait}}. Keep in mind that it is recommended to have a [[firewall]] configured in this case or make sure your local network is completely trustworthy since this connection is completely unauthenticated and unencrypted.}}<br />
<br />
==== UNIX socket ====<br />
<br />
Run QEMU with the {{ic|-monitor unix:''socketfile'',server,nowait}} parameter. Then you can connect with either {{Pkg|socat}}, {{Pkg|nmap}} or {{Pkg|openbsd-netcat}}.<br />
<br />
For example, if QEMU is run via:<br />
<br />
$ qemu-system-x86_64 -monitor unix:/tmp/monitor.sock,server,nowait ''[...]''<br />
<br />
It is possible to connect to the monitor with:<br />
<br />
$ socat - UNIX-CONNECT:/tmp/monitor.sock<br />
<br />
Or with:<br />
<br />
$ nc -U /tmp/monitor.sock<br />
<br />
Alternatively with {{Pkg|nmap}}:<br />
<br />
$ ncat -U /tmp/monitor.sock<br />
<br />
==== TCP ====<br />
<br />
You can expose the monitor over TCP with the argument {{ic|-monitor tcp:127.0.0.1:''port'',server,nowait}}. Then connect with netcat, either {{Pkg|openbsd-netcat}} or {{Pkg|gnu-netcat}} by running:<br />
<br />
$ nc 127.0.0.1 ''port''<br />
<br />
{{Note|In order to be able to connect to the tcp socket from other devices other than the same host QEMU is being run on you need to listen to {{ic|0.0.0.0}} like explained in the telnet case. The same security warnings apply in this case as well.}}<br />
<br />
==== Standard I/O ====<br />
<br />
It is possible to access the monitor automatically from the same terminal QEMU is being run by running it with the argument {{ic|-monitor stdio}}.<br />
<br />
=== Sending keyboard presses to the virtual machine using the monitor console ===<br />
<br />
Some combinations of keys may be difficult to perform on virtual machines due to the host intercepting them instead in some configurations (a notable example is the {{ic|Ctrl+Alt+F*}} key combinations, which change the active tty). To avoid this problem, the problematic combination of keys may be sent via the monitor console instead. Switch to the monitor and use the {{ic|sendkey}} command to forward the necessary keypresses to the virtual machine. For example:<br />
<br />
(qemu) sendkey ctrl-alt-f2<br />
<br />
=== Creating and managing snapshots via the monitor console ===<br />
<br />
{{Note|This feature will '''only''' work when the virtual machine disk image is in ''qcow2'' format. It will not work with ''raw'' images.}}<br />
<br />
It is sometimes desirable to save the current state of a virtual machine and having the possibility of reverting the state of the virtual machine to that of a previously saved snapshot at any time. The QEMU monitor console provides the user with the necessary utilities to create snapshots, manage them, and revert the machine state to a saved snapshot.<br />
<br />
* Use {{ic|savevm ''name''}} in order to create a snapshot with the tag ''name''.<br />
* Use {{ic|loadvm ''name''}} to revert the virtual machine to the state of the snapshot ''name''.<br />
* Use {{ic|delvm ''name''}} to delete the snapshot tagged as ''name''.<br />
* Use {{ic|info snapshots}} to see a list of saved snapshots. Snapshots are identified by both an auto-incremented ID number and a text tag (set by the user on snapshot creation).<br />
<br />
=== Running the virtual machine in immutable mode ===<br />
<br />
It is possible to run a virtual machine in a frozen state so that all changes will be discarded when the virtual machine is powered off just by running QEMU with the {{ic|-snapshot}} parameter. When the disk image is written by the guest, changes will be saved in a temporary file in {{ic|/tmp}} and will be discarded when QEMU halts.<br />
<br />
However, if a machine is running in frozen mode it is still possible to save the changes to the disk image if it is afterwards desired by using the monitor console and running the following command:<br />
<br />
(qemu) commit all<br />
<br />
If snapshots are created when running in frozen mode they will be discarded as soon as QEMU is exited unless changes are explicitly commited to disk, as well.<br />
<br />
=== Pause and power options via the monitor console ===<br />
<br />
Some operations of a physical machine can be emulated by QEMU using some monitor commands:<br />
<br />
* {{ic|system_powerdown}} will send an ACPI shutdown request to the virtual machine. This effect is similar to the power button in a physical machine.<br />
* {{ic|system_reset}} will reset the virtual machine similarly to a reset button in a physical machine. This operation can cause data loss and file system corruption since the virtual machine is not cleanly restarted.<br />
* {{ic|stop}} will pause the virtual machine.<br />
* {{ic|cont}} will resume a virtual machine previously paused.<br />
<br />
=== Taking screenshots of the virtual machine ===<br />
<br />
Screenshots of the virtual machine graphic display can be obtained in the PPM format by running the following command in the monitor console:<br />
<br />
(qemu) screendump ''file.ppm''<br />
<br />
== QEMU machine protocol ==<br />
<br />
The QEMU machine protocol (QMP) is a JSON-based protocol which allows applications to control a QEMU instance. Similarly to the [[#QEMU monitor]] it offers ways to interact with a running machine and the JSON protocol allows to do it programmatically. The description of all the QMP commands can be found in [https://raw.githubusercontent.com/coreos/qemu/master/qmp-commands.hx qmp-commands].<br />
<br />
=== Start QMP ===<br />
<br />
The usual way to control the guest using the QMP protocol, is to open a TCP socket when launching the machine using the {{ic|-qmp}} option. Here it is using for example the TCP port 4444:<br />
<br />
$ qemu-system-x86_64 ''[...]'' -qmp tcp:localhost:4444,server,nowait<br />
<br />
Then one way to communicate with the QMP agent is to use [[netcat]]:<br />
<br />
{{hc|nc localhost 4444|{"QMP": {"version": {"qemu": {"micro": 0, "minor": 1, "major": 3}, "package": ""}, "capabilities": []} } }}<br />
<br />
At this stage, the only command that can be recognized is {{ic|qmp_capabilities}}, so that QMP enters into command mode. Type:<br />
<br />
{"execute": "qmp_capabilities"}<br />
<br />
Now, QMP is ready to receive commands, to retrieve the list of recognized commands, use:<br />
<br />
{"execute": "query-commands"}<br />
<br />
=== Live merging of child image into parent image ===<br />
<br />
It is possible to merge a running snapshot into its parent by issuing a {{ic|block-commit}} command. In its simplest form the following line will commit the child into its parent:<br />
<br />
{"execute": "block-commit", "arguments": {"device": "''devicename''"}}<br />
<br />
Upon reception of this command, the handler looks for the base image and converts it from read only to read write mode and then runs the commit job.<br />
<br />
Once the ''block-commit'' operation has completed, the event {{ic|BLOCK_JOB_READY}} will be emitted, signalling that the synchronization has finished. The job can then be gracefully completed by issuing the command {{ic|block-job-complete}}:<br />
<br />
{"execute": "block-job-complete", "arguments": {"device": "''devicename''"}}<br />
<br />
Until such a command is issued, the ''commit'' operation remains active.<br />
After successful completion, the base image remains in read write mode and becomes the new active layer. On the other hand, the child image becomes invalid and it is the responsibility of the user to clean it up.<br />
<br />
{{Tip|The list of device and their names can be retrieved by executing the command {{ic|query-block}} and parsing the results. The device name is in the {{ic|device}} field, for example {{ic|ide0-hd0}} for the hard disk in this example: {{hc|{"execute": "query-block"}|{"return": [{"io-status": "ok", "device": "'''ide0-hd0'''", "locked": false, "removable": false, "inserted": {"iops_rd": 0, "detect_zeroes": "off", "image": {"backing-image": {"virtual-size": 27074281472, "filename": "parent.qcow2", ... } }} }}<br />
<br />
=== Live creation of a new snapshot ===<br />
<br />
To create a new snapshot out of a running image, run the command:<br />
<br />
{"execute": "blockdev-snapshot-sync", "arguments": {"device": "''devicename''","snapshot-file": "''new_snapshot_name''.qcow2"}}<br />
<br />
This creates an overlay file named {{ic|''new_snapshot_name''.qcow2}} which then becomes the new active layer.<br />
<br />
== Tips and tricks ==<br />
<br />
=== Improve virtual machine performance ===<br />
<br />
There are a number of techniques that you can use to improve the performance of the virtual machine. For example:<br />
<br />
* Apply [[#Enabling KVM]] for full virtualization.<br />
* Use the {{ic|-cpu host}} option to make QEMU emulate the host's exact CPU rather than a more generic CPU.<br />
* Especially for Windows guests, enable [https://blog.wikichoon.com/2014/07/enabling-hyper-v-enlightenments-with-kvm.html Hyper-V enlightenments]: {{ic|1=-cpu host,hv_relaxed,hv_spinlocks=0x1fff,hv_vapic,hv_time}}. See the [https://www.qemu.org/docs/master/system/i386/hyperv.html QEMU documentation] for more information and flags.<br />
* multiple cores can be assigned to the guest using the {{ic|-smp cores{{=}}x,threads{{=}}y,sockets{{=}}1,maxcpus{{=}}z}} option. The threads parameter is used to assign [https://www.tomshardware.com/reviews/simultaneous-multithreading-definition,5762.html SMT cores]. Leaving a physical core for QEMU, the hypervisor and the host system to operate unimpeded is highly beneficial.<br />
* Make sure you have assigned the virtual machine enough memory. By default, QEMU only assigns 128 MiB of memory to each virtual machine. Use the {{ic|-m}} option to assign more memory. For example, {{ic|-m 1024}} runs a virtual machine with 1024 MiB of memory.<br />
* If supported by drivers in the guest operating system, use virtio for network and/or block devices, see [[#Installing virtio drivers]].<br />
* Use TAP devices instead of user-mode networking, see [[#Tap networking with QEMU]].<br />
* If the guest OS is doing heavy writing to its disk, you may benefit from certain mount options on the host's file system. For example, you can mount an [[Ext4|ext4 file system]] with the option {{ic|1=barrier=0}}. You should read the documentation for any options that you change because sometimes performance-enhancing options for file systems come at the cost of data integrity.<br />
* If you have a raw disk or partition, you may want to disable the cache: {{bc|1=$ qemu-system-x86_64 -drive file=/dev/''disk'',if=virtio,'''cache=none'''}}<br />
* Use the native Linux AIO: {{bc|1=$ qemu-system-x86_64 -drive file=''disk_image'',if=virtio''',aio=native,cache.direct=on'''}}<br />
* If you are running multiple virtual machines concurrently that all have the same operating system installed, you can save memory by enabling [[wikipedia:Kernel_SamePage_Merging_(KSM)|kernel same-page merging]]. See [[#Enabling KSM]].<br />
* In some cases, memory can be reclaimed from running virtual machines by running a memory ballooning driver in the guest operating system and launching QEMU using {{ic|-device virtio-balloon}}.<br />
* It is possible to use a emulation layer for an ICH-9 AHCI controller (although it may be unstable). The AHCI emulation supports [[Wikipedia:Native_Command_Queuing|NCQ]], so multiple read or write requests can be outstanding at the same time: {{bc|1=$ qemu-system-x86_64 -drive id=disk,file=''disk_image'',if=none -device ich9-ahci,id=ahci -device ide-drive,drive=disk,bus=ahci.0}}<br />
<br />
See https://www.linux-kvm.org/page/Tuning_KVM for more information.<br />
<br />
=== Starting QEMU virtual machines on boot ===<br />
<br />
==== With libvirt ====<br />
<br />
If a virtual machine is set up with [[libvirt]], it can be configured with {{ic|virsh autostart}} or through the ''virt-manager'' GUI to start at host boot by going to the Boot Options for the virtual machine and selecting "Start virtual machine on host boot up".<br />
<br />
==== With systemd service ====<br />
<br />
To run QEMU virtual machines on boot, you can use following systemd unit and config.<br />
<br />
{{hc|/etc/systemd/system/qemu@.service|2=<br />
[Unit]<br />
Description=QEMU virtual machine<br />
<br />
[Service]<br />
Environment="haltcmd=kill -INT $MAINPID"<br />
EnvironmentFile=/etc/conf.d/qemu.d/%i<br />
ExecStart=/usr/bin/qemu-system-x86_64 -name %i -enable-kvm -m 512 -nographic $args<br />
ExecStop=/usr/bin/bash -c ${haltcmd}<br />
ExecStop=/usr/bin/bash -c 'while nc localhost 7100; do sleep 1; done'<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
}}<br />
<br />
{{Note|This service will wait for the console port to be released, which means that the virtual machine has been shutdown, to graciously end.}}<br />
<br />
Then create per-VM configuration files, named {{ic|/etc/conf.d/qemu.d/''vm_name''}}, with the variables {{ic|args}} and {{ic|haltcmd}} set. Example configs:<br />
<br />
{{hc|/etc/conf.d/qemu.d/one|2=<br />
args="-hda /dev/vg0/vm1 -serial telnet:localhost:7000,server,nowait,nodelay \<br />
-monitor telnet:localhost:7100,server,nowait,nodelay -vnc :0"<br />
<br />
haltcmd="echo 'system_powerdown' {{!}} nc localhost 7100" # or netcat/ncat}}<br />
<br />
{{hc|/etc/conf.d/qemu.d/two|2=<br />
args="-hda /srv/kvm/vm2 -serial telnet:localhost:7001,server,nowait,nodelay -vnc :1"<br />
<br />
haltcmd="ssh powermanager@vm2 sudo poweroff"}}<br />
<br />
The description of the variables is the following:<br />
<br />
* {{ic|args}} - QEMU command line arguments to be used.<br />
* {{ic|haltcmd}} - Command to shut down a virtual machine safely. In the first example, the QEMU monitor is exposed via telnet using {{ic|-monitor telnet:..}} and the virtual machines are powered off via ACPI by sending {{ic|system_powerdown}} to monitor with the {{ic|nc}} command. In the other example, SSH is used.<br />
<br />
To set which virtual machines will start on boot-up, [[enable]] the {{ic|qemu@''vm_name''.service}} systemd unit.<br />
<br />
=== Mouse integration ===<br />
<br />
To prevent the mouse from being grabbed when clicking on the guest operating system's window, add the options {{ic|-usb -device usb-tablet}}. This means QEMU is able to report the mouse position without having to grab the mouse. This also overrides PS/2 mouse emulation when activated. For example:<br />
<br />
$ qemu-system-x86_64 -hda ''disk_image'' -m 512 -usb -device usb-tablet<br />
<br />
If that does not work, try using {{ic|-vga qxl}} parameter, also look at the instructions [[#Mouse cursor is jittery or erratic]].<br />
<br />
=== Pass-through host USB device ===<br />
<br />
It is possible to access the physical device connected to a USB port of the host from the guest. The first step is to identify where the device is connected, this can be found running the {{ic|lsusb}} command. For example:<br />
<br />
{{hc|$ lsusb|<br />
...<br />
Bus '''003''' Device '''007''': ID '''0781''':'''5406''' SanDisk Corp. Cruzer Micro U3<br />
}}<br />
<br />
The outputs in bold above will be useful to identify respectively the ''host_bus'' and ''host_addr'' or the ''vendor_id'' and ''product_id''.<br />
<br />
In qemu, the idea is to emulate an EHCI (USB 2) or XHCI (USB 1.1 USB 2 USB 3) controller with the option {{ic|1=-device usb-ehci,id=ehci}} or {{ic|1=-device qemu-xhci,id=xhci}} respectively and then attach the physical device to it with the option {{ic|1=-device usb-host,..}}. We will consider that ''controller_id'' is either {{ic|ehci}} or {{ic|xhci}} for the rest of this section.<br />
<br />
Then, there are two ways to connect to the USB of the host with qemu:<br />
<br />
# Identify the device and connect to it on any bus and address it is attached to on the host, the generic syntax is: {{bc|1=-device usb-host,bus=''controller_id''.0,vendorid=0x''vendor_id'',productid=0x''product_id''}}Applied to the device used in the example above, it becomes:{{bc|1=-device usb-ehci,id=ehci -device usb-host,bus=ehci.0,vendorid=0x'''0781''',productid=0x'''5406'''}}One can also add the {{ic|1=...,port=''port_number''}} setting to the previous option to specify in which physical port of the virtual controller the device should be attached, useful in the case one wants to add multiple USB devices to the virtual machine. Another option is to use the new {{ic|hostdevice}} property of {{ic|usb-host}} which is available since QEMU 5.1.0, the syntax is: {{bc|1=-device qemu-xhci,id=xhci -device usb-host,hostdevice=/dev/bus/usb/003/007}}<br />
# Attach whatever is connected to a given USB bus and address, the syntax is:{{bc|1=-device usb-host,bus=''controller_id''.0,hostbus=''host_bus'',host_addr=''host_addr''}}Applied to the bus and the address in the example above, it becomes:{{bc|1=-device usb-ehci,id=ehci -device usb-host,bus=ehci.0,hostbus='''3''',hostaddr='''7'''}}<br />
See [https://www.qemu.org/docs/master/system/devices/usb.html QEMU/USB emulation] for more information.<br />
{{Note|If you encounter permission errors when running QEMU, see [[udev#About udev rules]] for information on how to set permissions of the device.}}<br />
<br />
=== USB redirection with SPICE ===<br />
<br />
When using [[#SPICE]] it is possible to redirect USB devices from the client to the virtual machine without needing to specify them in the QEMU command. It is possible to configure the number of USB slots available for redirected devices (the number of slots will determine the maximum number of devices which can be redirected simultaneously). The main advantages of using SPICE for redirection compared to the previously-mentioned {{ic|-usbdevice}} method is the possibility of hot-swapping USB devices after the virtual machine has started, without needing to halt it in order to remove USB devices from the redirection or adding new ones. This method of USB redirection also allows us to redirect USB devices over the network, from the client to the server. In summary, it is the most flexible method of using USB devices in a QEMU virtual machine.<br />
<br />
We need to add one EHCI/UHCI controller per available USB redirection slot desired as well as one SPICE redirection channel per slot. For example, adding the following arguments to the QEMU command you use for starting the virtual machine in SPICE mode will start the virtual machine with three available USB slots for redirection:<br />
<br />
{{bc|1=<br />
-device ich9-usb-ehci1,id=usb \<br />
-device ich9-usb-uhci1,masterbus=usb.0,firstport=0,multifunction=on \<br />
-device ich9-usb-uhci2,masterbus=usb.0,firstport=2 \<br />
-device ich9-usb-uhci3,masterbus=usb.0,firstport=4 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev1 -device usb-redir,chardev=usbredirchardev1,id=usbredirdev1 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev2 -device usb-redir,chardev=usbredirchardev2,id=usbredirdev2 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev3 -device usb-redir,chardev=usbredirchardev3,id=usbredirdev3<br />
}}<br />
<br />
See [https://www.spice-space.org/usbredir.html SPICE/usbredir] for more information.<br />
<br />
Both {{ic|spicy}} from {{Pkg|spice-gtk}} (''Input > Select USB Devices for redirection'') and {{ic|remote-viewer}} from {{Pkg|virt-viewer}} (''File > USB device selection'') support this feature. Please make sure that you have installed the necessary SPICE Guest Tools on the virtual machine for this functionality to work as expected (see the [[#SPICE]] section for more information).<br />
<br />
{{Warning|Keep in mind that when a USB device is redirected from the client, it will not be usable from the client operating system itself until the redirection is stopped. It is specially important to never redirect the input devices (namely mouse and keyboard), since it will be then difficult to access the SPICE client menus to revert the situation, because the client will not respond to the input devices after being redirected to the virtual machine.}}<br />
<br />
==== Automatic USB forwarding with udev ====<br />
<br />
Normally, forwarded devices must be available at the boot time of the virtual machine to be forwarded. If that device is disconnected, it will not be forwarded anymore.<br />
<br />
You can use [[udev rule]]s to automatically attach a device when it comes online. Create a {{ic|hostdev}} entry somewhere on disk. [[chown]] it to root to prevent other users modifying it.<br />
<br />
{{hc|/usr/local/hostdev-mydevice.xml|2=<br />
<hostdev mode='subsystem' type='usb'><br />
<source><br />
<vendor id='0x03f0'/><br />
<product id='0x4217'/><br />
</source><br />
</hostdev><br />
}}<br />
<br />
Then create a ''udev'' rule which will attach/detach the device:<br />
<br />
{{hc|/usr/lib/udev/rules.d/90-libvirt-mydevice|2=<br />
ACTION=="add", \<br />
SUBSYSTEM=="usb", \<br />
ENV{ID_VENDOR_ID}=="03f0", \<br />
ENV{ID_MODEL_ID}=="4217", \<br />
RUN+="/usr/bin/virsh attach-device GUESTNAME /usr/local/hostdev-mydevice.xml"<br />
ACTION=="remove", \<br />
SUBSYSTEM=="usb", \<br />
ENV{ID_VENDOR_ID}=="03f0", \<br />
ENV{ID_MODEL_ID}=="4217", \<br />
RUN+="/usr/bin/virsh detach-device GUESTNAME /usr/local/hostdev-mydevice.xml"<br />
}}<br />
<br />
[https://rolandtapken.de/blog/2011-04/how-auto-hotplug-usb-devices-libvirt-vms-update-1 Source and further reading].<br />
<br />
=== Enabling KSM ===<br />
<br />
Kernel Samepage Merging (KSM) is a feature of the Linux kernel that allows for an application to register with the kernel to have its pages merged with other processes that also register to have their pages merged. The KSM mechanism allows for guest virtual machines to share pages with each other. In an environment where many of the guest operating systems are similar, this can result in significant memory savings.<br />
<br />
{{Note|Although KSM may reduce memory usage, it may increase CPU usage. Also note some security issues may occur, see [[Wikipedia:Kernel same-page merging]].}}<br />
<br />
To enable KSM:<br />
<br />
# echo 1 > /sys/kernel/mm/ksm/run<br />
<br />
To make it permanent, use [[systemd#systemd-tmpfiles - temporary files|systemd's temporary files]]:<br />
<br />
{{hc|/etc/tmpfiles.d/ksm.conf|<br />
w /sys/kernel/mm/ksm/run - - - - 1<br />
}}<br />
<br />
If KSM is running, and there are pages to be merged (i.e. at least two similar virtual machines are running), then {{ic|/sys/kernel/mm/ksm/pages_shared}} should be non-zero. See https://docs.kernel.org/admin-guide/mm/ksm.html for more information.<br />
<br />
{{Tip|An easy way to see how well KSM is performing is to simply print the contents of all the files in that directory:<br />
<br />
$ grep -r . /sys/kernel/mm/ksm/<br />
<br />
}}<br />
<br />
=== Multi-monitor support ===<br />
<br />
The Linux QXL driver supports four heads (virtual screens) by default. This can be changed via the {{ic|1=qxl.heads=N}} kernel parameter.<br />
<br />
The default VGA memory size for QXL devices is 16M (VRAM size is 64M). This is not sufficient if you would like to enable two 1920x1200 monitors since that requires 2 × 1920 × 4 (color depth) × 1200 = 17.6 MiB VGA memory. This can be changed by replacing {{ic|-vga qxl}} by {{ic|<nowiki>-vga none -device qxl-vga,vgamem_mb=32</nowiki>}}. If you ever increase vgamem_mb beyond 64M, then you also have to increase the {{ic|vram_size_mb}} option.<br />
<br />
=== Custom display resolution ===<br />
<br />
A custom display resolution can be set with {{ic|1=-device VGA,edid=on,xres=1280,yres=720}} (see [[wikipedia:Extended_Display_Identification_Data|EDID]] and [[wikipedia:Display_resolution|display resolution]]).<br />
<br />
=== Copy and paste ===<br />
<br />
==== SPICE ====<br />
<br />
One way to share the clipboard between the host and the guest is to enable the SPICE remote desktop protocol and access the client with a SPICE client.<br />
One needs to follow the steps described in [[#SPICE]]. A guest run this way will support copy paste with the host.<br />
<br />
==== qemu-vdagent ====<br />
<br />
QEMU provides its own implementation of the spice vdagent chardev called {{ic|qemu-vdagent}}. It interfaces with the spice-vdagent guest service and allows the guest and host share a clipboard.<br />
<br />
To access this shared clipboard with QEMU's GTK display, you will need to [[#Custom build|compile QEMU from source]] with the {{ic|--enable-gtk-clipboard}} configure parameter. It is sufficient to replace the installed {{ic|qemu-ui-gtk}} package.<br />
<br />
{{Note|<br />
* Feature request {{Bug|79716}} submitted to enable the functionality in the official package.<br />
* The shared clipboard in qemu-ui-gtk has been pushed back to experimental as it can [https://gitlab.com/qemu-project/qemu/-/issues/1150 freeze guests under certain circumstances]. A fix has been proposed to solve the issue upstream.<br />
}}<br />
<br />
Add the following QEMU command line arguments:<br />
<br />
-device virtio-serial,packed=on,ioeventfd=on<br />
-device virtserialport,name=com.redhat.spice.0,chardev=vdagent0<br />
-chardev qemu-vdagent,id=vdagent0,name=vdagent,clipboard=on,mouse=off<br />
<br />
These arguments are also valid if converted to [[Libvirt#QEMU command line arguments|libvirt form]].<br />
<br />
{{Note|While the spicevmc chardev will start the spice-vdagent service of the guest automatically, the qemu-vdagent chardev may not.}}<br />
<br />
On linux guests, you may [[start]] the {{ic|spice-vdagent.service}} [[user unit]] manually. On Windows guests, set the spice-agent startup type to automatic.<br />
<br />
=== Windows-specific notes ===<br />
<br />
QEMU can run any version of Windows from Windows 95 through Windows 11.<br />
<br />
It is possible to run [[Windows PE]] in QEMU.<br />
<br />
==== Fast startup ====<br />
<br />
{{Note|An administrator account is required to change power settings.}}<br />
<br />
For Windows 8 (or later) guests it is better to disable "Turn on fast startup (recommended)" from the Power Options of the Control Panel as explained in the following [https://www.tenforums.com/tutorials/4189-turn-off-fast-startup-windows-10-a.html forum page], as it causes the guest to hang during every other boot.<br />
<br />
Fast Startup may also need to be disabled for changes to the {{ic|-smp}} option to be properly applied.<br />
<br />
==== Remote Desktop Protocol ====<br />
<br />
If you use a MS Windows guest, you might want to use RDP to connect to your guest virtual machine. If you are using a VLAN or are not in the same network as the guest, use:<br />
<br />
$ qemu-system-x86_64 -nographic -nic user,hostfwd=tcp::5555-:3389<br />
<br />
Then connect with either {{Pkg|rdesktop}} or {{Pkg|freerdp}} to the guest. For example:<br />
<br />
$ xfreerdp -g 2048x1152 localhost:5555 -z -x lan<br />
<br />
=== Clone Linux system installed on physical equipment ===<br />
<br />
Linux system installed on physical equipment can be cloned for running on a QEMU virtual machine. See [https://coffeebirthday.wordpress.com/2018/09/14/clone-linux-system-for-qemu-virtual-machine/ Clone Linux system from hardware for QEMU virtual machine]<br />
<br />
=== Chrooting into arm/arm64 environment from x86_64 ===<br />
<br />
Sometimes it is easier to work directly on a disk image instead of the real ARM based device. This can be achieved by mounting an SD card/storage containing the ''root'' partition and chrooting into it.<br />
<br />
Another use case for an ARM chroot is building ARM packages on an x86_64 machine. Here, the chroot environment can be created from an image tarball from [https://archlinuxarm.org Arch Linux ARM] - see [https://nerdstuff.org/posts/2020/2020-003_simplest_way_to_create_an_arm_chroot/] for a detailed description of this approach.<br />
<br />
Either way, from the chroot it should be possible to run ''pacman'' and install more packages, compile large libraries etc. Since the executables are for the ARM architecture, the translation to x86 needs to be performed by [[QEMU]].<br />
<br />
Install {{Pkg|qemu-user-static}} on the x86_64 machine/host, and {{Pkg|qemu-user-static-binfmt}} to register the qemu binaries to binfmt service.<br />
<br />
''qemu-user-static'' is used to allow the execution of compiled programs from other architectures. This is similar to what is provided by {{Pkg|qemu-emulators-full}}, but the "static" variant is required for chroot. Examples:<br />
<br />
qemu-arm-static path_to_sdcard/usr/bin/ls<br />
qemu-aarch64-static path_to_sdcard/usr/bin/ls<br />
<br />
These two lines execute the {{ic|ls}} command compiled for 32-bit ARM and 64-bit ARM respectively. Note that this will not work without chrooting, because it will look for libraries not present in the host system.<br />
<br />
{{Pkg|qemu-user-static}} allows automatically prefixing the ARM exectuable with {{ic|qemu-arm-static}} or {{ic|qemu-aarch64-static}}.<br />
<br />
Make sure that the ARM executable support is active:<br />
<br />
{{hc|$ ls /proc/sys/fs/binfmt_misc|<br />
qemu-aarch64 qemu-arm qemu-cris qemu-microblaze qemu-mipsel qemu-ppc64 qemu-riscv64 qemu-sh4 qemu-sparc qemu-sparc64 status<br />
qemu-alpha qemu-armeb qemu-m68k qemu-mips qemu-ppc qemu-ppc64abi32 qemu-s390x qemu-sh4eb qemu-sparc32plus register<br />
}}<br />
<br />
Each executable must be listed.<br />
<br />
If it is not active, [[restart]] {{ic|systemd-binfmt.service}}.<br />
<br />
Mount the SD card to {{ic|/mnt/sdcard}} (the device name may be different).<br />
<br />
# mount --mkdir /dev/mmcblk0p2 /mnt/sdcard<br />
<br />
Mount boot partition if needed (again, use the suitable device name):<br />
<br />
# mount /dev/mmcblk0p1 /mnt/sdcard/boot<br />
<br />
Finally ''chroot'' into the SD card root as described in [[Change root#Using chroot]]:<br />
<br />
# chroot /mnt/sdcard /bin/bash<br />
<br />
Alternatively, you can use ''arch-chroot'' from {{Pkg|arch-install-scripts}}, as it will provide an easier way to get network support:<br />
<br />
# arch-chroot /mnt/sdcard /bin/bash<br />
<br />
You can also use [[systemd-nspawn]] to chroot into the ARM environment:<br />
<br />
# systemd-nspawn -D /mnt/sdcard -M myARMMachine --bind-ro=/etc/resolv.conf<br />
<br />
{{ic|1=--bind-ro=/etc/resolv.conf}} is optional and gives a working network DNS inside the chroot<br />
<br />
==== sudo in chroot ====<br />
<br />
If you install [[sudo]] in the chroot and receive the following error when trying to use it:<br />
<br />
sudo: effective uid is not 0, is /usr/bin/sudo on a file system with the 'nosuid' option set or an NFS file system without root privileges?<br />
<br />
then you may need to modify the binfmt flags, for example for {{ic|aarch64}}:<br />
<br />
# cp /usr/lib/binfmt.d/qemu-aarch64-static.conf /etc/binfmt.d/<br />
# vi /etc/binfmt.d/qemu-aarch64-static.conf<br />
<br />
and add a {{ic|C}} at the end of this file:<br />
<br />
:qemu-aarch64:M::\x7fELF\x02\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\xb7\x00:\xff\xff\xff\xff\xff\xff\xff\x00\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff\xff:/usr/bin/qemu-aarch64-static:FPC<br />
<br />
Then [[restart]] {{ic|systemd-binfmt.service}} and check that the changes have taken effect (note the {{ic|C}} on the {{ic|flags}} line):<br />
<br />
{{hc|# cat /proc/sys/fs/binfmt_misc/qemu-aarch64|<br />
enabled<br />
interpreter /usr/bin/qemu-aarch64-static<br />
flags: POCF<br />
offset 0<br />
magic 7f454c460201010000000000000000000200b700<br />
mask ffffffffffffff00fffffffffffffffffeffffff<br />
}}<br />
<br />
See the "flags" section of the [https://docs.kernel.org/admin-guide/binfmt-misc.html kernel binfmt documentation] for more information.<br />
<br />
=== Not grabbing mouse input ===<br />
<br />
{{Style|It is not explained what the option actually does. Is it causing or avoiding the side effect?}}<br />
<br />
Tablet mode has side effect of not grabbing mouse input in QEMU window:<br />
<br />
-usb -device usb-tablet<br />
<br />
It works with several {{ic|-vga}} backends one of which is virtio.<br />
<br />
== Troubleshooting ==<br />
<br />
{{Merge|QEMU/Troubleshooting|This section is long enough to be split into a dedicated subpage.}}<br />
<br />
=== Mouse cursor is jittery or erratic ===<br />
<br />
If the cursor jumps around the screen uncontrollably, entering this on the terminal before starting QEMU might help:<br />
<br />
$ export SDL_VIDEO_X11_DGAMOUSE=0<br />
<br />
If this helps, you can add this to your {{ic|~/.bashrc}} file.<br />
<br />
=== No visible Cursor ===<br />
<br />
Add {{ic|1=-display default,show-cursor=on}} to QEMU's options to see a mouse cursor.<br />
<br />
If that still does not work, make sure you have set your display device appropriately, for example: {{ic|-vga qxl}}.<br />
<br />
Another option to try is {{ic|-usb -device usb-tablet}} as mentioned in [[#Mouse integration]]. This overrides the default PS/2 mouse emulation and synchronizes pointer location between host and guest as an added bonus.<br />
<br />
=== Two different mouse cursors are visible ===<br />
<br />
Apply the tip [[#Mouse integration]].<br />
<br />
=== Keyboard issues when using VNC ===<br />
<br />
When using VNC, you might experience keyboard problems described (in gory details) [https://www.berrange.com/posts/2010/07/04/more-than-you-or-i-ever-wanted-to-know-about-virtual-keyboard-handling/ here]. The solution is ''not'' to use the {{ic|-k}} option on QEMU, and to use {{ic|gvncviewer}} from {{Pkg|gtk-vnc}}. See also [https://www.mail-archive.com/libvir-list@redhat.com/msg13340.html this] message posted on libvirt's mailing list.<br />
<br />
=== Keyboard seems broken or the arrow keys do not work ===<br />
<br />
Should you find that some of your keys do not work or "press" the wrong key (in particular, the arrow keys), you likely need to specify your keyboard layout as an option. The keyboard layouts can be found in {{ic|/usr/share/qemu/keymaps/}}.<br />
<br />
$ qemu-system-x86_64 -k ''keymap'' ''disk_image''<br />
<br />
=== Could not read keymap file ===<br />
<br />
qemu-system-x86_64: -display vnc=0.0.0.0:0: could not read keymap file: 'en'<br />
<br />
is caused by an invalid ''keymap'' passed to the {{ic|-k}} argument. For example, {{ic|en}} is invalid, but {{ic|en-us}} is valid - see {{ic|/usr/share/qemu/keymaps/}}.<br />
<br />
=== Guest display stretches on window resize ===<br />
<br />
To restore default window size, press {{ic|Ctrl+Alt+u}}.<br />
<br />
=== ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy ===<br />
<br />
If an error message like this is printed when starting QEMU with {{ic|-enable-kvm}} option:<br />
<br />
ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy<br />
failed to initialize KVM: Device or resource busy<br />
<br />
that means another [[hypervisor]] is currently running. It is not recommended or possible to run several hypervisors in parallel.<br />
<br />
=== libgfapi error message ===<br />
<br />
The error message displayed at startup:<br />
<br />
Failed to open module: libgfapi.so.0: cannot open shared object file: No such file or directory<br />
<br />
[[Install]] {{Pkg|glusterfs}} or ignore the error message as GlusterFS is a optional dependency.<br />
<br />
=== Kernel panic on LIVE-environments ===<br />
<br />
If you start a live-environment (or better: booting a system) you may encounter this:<br />
<br />
[ end Kernel panic - not syncing: VFS: Unable to mount root fs on unknown block(0,0)<br />
<br />
or some other boot hindering process (e.g. cannot unpack initramfs, cant start service foo).<br />
Try starting the virtual machine with the {{ic|-m VALUE}} switch and an appropriate amount of RAM, if the ram is to low you will probably encounter similar issues as above/without the memory-switch.<br />
<br />
=== Windows 7 guest suffers low-quality sound ===<br />
<br />
Using the {{ic|hda}} audio driver for Windows 7 guest may result in low-quality sound. Changing the audio driver to {{ic|ac97}} by passing the {{ic|-soundhw ac97}} arguments to QEMU and installing the AC97 driver from [https://www.realtek.com/en/component/zoo/category/pc-audio-codecs-ac-97-audio-codecs-software Realtek AC'97 Audio Codecs] in the guest may solve the problem. See [https://bugzilla.redhat.com/show_bug.cgi?id=1176761#c16 Red Hat Bugzilla – Bug 1176761] for more information.<br />
<br />
=== Could not access KVM kernel module: Permission denied ===<br />
<br />
If you encounter the following error:<br />
<br />
libvirtError: internal error: process exited while connecting to monitor: Could not access KVM kernel module: Permission denied failed to initialize KVM: Permission denied<br />
<br />
Systemd 234 assigns a dynamic ID for the {{ic|kvm}} group (see {{Bug|54943}}). To avoid this error, you need edit the file {{ic|/etc/libvirt/qemu.conf}} and change the line with {{ic|1=group = "78"}} to {{ic|1=group = "kvm"}}.<br />
<br />
=== "System Thread Exception Not Handled" when booting a Windows virtual machine ===<br />
<br />
Windows 8 or Windows 10 guests may raise a generic compatibility exception at boot, namely "System Thread Exception Not Handled", which tends to be caused by legacy drivers acting strangely on real machines. On KVM machines this issue can generally be solved by setting the CPU model to {{ic|core2duo}}.<br />
<br />
=== Certain Windows games/applications crashing/causing a bluescreen ===<br />
<br />
Occasionally, applications running in the virtual machine may crash unexpectedly, whereas they would run normally on a physical machine. If, while running {{ic|dmesg -wH}} as root, you encounter an error mentioning {{ic|MSR}}, the reason for those crashes is that KVM injects a [[wikipedia:General protection fault|General protection fault]] (GPF) when the guest tries to access unsupported [[wikipedia:Model-specific register|Model-specific registers]] (MSRs) - this often results in guest applications/OS crashing. A number of those issues can be solved by passing the {{ic|1=ignore_msrs=1}} option to the KVM module, which will ignore unimplemented MSRs.<br />
<br />
{{hc|/etc/modprobe.d/kvm.conf|2=<br />
...<br />
options kvm ignore_msrs=1<br />
...<br />
}}<br />
<br />
Cases where adding this option might help:<br />
<br />
* GeForce Experience complaining about an unsupported CPU being present.<br />
* StarCraft 2 and L.A. Noire reliably blue-screening Windows 10 with {{ic|KMODE_EXCEPTION_NOT_HANDLED}}. The blue screen information does not identify a driver file in these cases.<br />
<br />
{{Warning|While this is normally safe and some applications might not work without this, silently ignoring unknown MSR accesses could potentially break other software within the virtual machine or other virtual machine.}}<br />
<br />
=== Applications in the virtual machine experience long delays or take a long time to start ===<br />
<br />
{{Out of date|No longer true since kernel 5.6}}<br />
<br />
This may be caused by insufficient available entropy in the virtual machine. Consider allowing the guest to access the hosts's entropy pool by adding a [https://wiki.qemu.org/Features/VirtIORNG VirtIO RNG device] to the virtual machine, or by installing an entropy generating daemon such as [[Haveged]].<br />
<br />
Anecdotally, OpenSSH takes a while to start accepting connections under insufficient entropy, without the logs revealing why.<br />
<br />
=== High interrupt latency and microstuttering ===<br />
<br />
This problem manifests itself as small pauses (stutters) and is particularly noticeable in graphics-intensive applications, such as games.<br />
<br />
* One of the causes is CPU power saving features, which are controlled by [[CPU frequency scaling]]. Change this to {{ic|performance}} for all processor cores. <br />
* Another possible cause is PS/2 inputs. Switch from PS/2 to Virtio inputs, see [[PCI passthrough via OVMF#Passing keyboard/mouse via Evdev]].<br />
<br />
=== QXL video causes low resolution ===<br />
<br />
QEMU 4.1.0 introduced a regression where QXL video can fall back to low resolutions, when being displayed through spice. [https://bugs.launchpad.net/qemu/+bug/1843151] For example, when KMS starts, text resolution may become as low as 4x10 characters. When trying to increase GUI resolution, it may go to the lowest supported resolution.<br />
<br />
As a workaround, create your device in this form:<br />
<br />
-device qxl-vga,max_outputs=1...<br />
<br />
=== Virtual machine not booting when using a Secure Boot enabled OVMF ===<br />
<br />
{{ic|OVMF_CODE.secboot.4m.fd}} and {{ic|OVMF_CODE.secboot.fd}} files from {{Pkg|edk2-ovmf}} are built with [[Wikipedia:System Management Mode|SMM]] support. If S3 support is not disabled in the virtual machine, then the virtual machine might not boot at all.<br />
<br />
Add the {{ic|1=-global ICH9-LPC.disable_s3=1}} option to the ''qemu'' command.<br />
<br />
See {{Bug|59465}} and https://github.com/tianocore/edk2/blob/master/OvmfPkg/README for more details and the required options to use Secure Boot in QEMU.<br />
<br />
=== Virtual machine not booting into Arch ISO ===<br />
<br />
When trying to boot the virtual machine for the first time from an Arch ISO image, the boot process hangs. Adding {{ic|1=console=ttyS0}} to kernel boot options by pressing {{ic|e}} in the boot menu you will get more boot messages and the following error:<br />
<br />
:: Mounting '/dev/disk/by-label/ARCH_202204' to '/run/archiso/bootmnt'<br />
Waiting 30 seconds for device /dev/disk/by-label/ARCH_202204 ...<br />
ERROR: '/dev/disk/by-label/ARCH_202204' device did not show up after 30 seconds...<br />
Falling back to interactive prompt<br />
You can try to fix the problem manually, log out when you are finished<br />
sh: can't access tty; job control turned off<br />
<br />
The error message does not give a good clue as to what the real issue is. The problem is with the default 128MB of RAM that QEMU allocates to the virtual machine. Increasing the limit to 1024MB with {{ic|-m 1024}} solves the issue and lets the system boot. You can continue installing Arch Linux as usual after that. Once the installation is complete, the memory allocation for the virtual machine can be decreased. The need for 1024MB is due to RAM disk requirements and size of the installation media. See [https://lists.archlinux.org/archives/list/arch-releng@lists.archlinux.org/message/D5HSGOFTPGYI6IZUEB3ZNAX4D3F3ID37/ this message on the arch-releng mailing list] and [https://bbs.archlinux.org/viewtopic.php?id=204023 this forum thread].<br />
<br />
=== Guest CPU interrupts are not firing ===<br />
<br />
If you are writing your own operating system by following the [https://wiki.osdev.org/ OSDev wiki], or are simply getting stepping through the guest architecture assembly code using QEMU's {{ic|gdb}} interface using the {{ic|-s}} flag, it is useful to know that many emulators, QEMU included, usually implement some CPU interrupts leaving many hardware interrupts unimplemented. One way to know if your code is firing an interrupt, is by using:<br />
<br />
-d int<br />
<br />
to enable showing interrupts/exceptions on stdout.<br />
<br />
To see what other guest debugging features QEMU has to offer, see:<br />
<br />
qemu-system-x86_64 -d help<br />
<br />
or replace {{ic|x86_64}} for your chosen guest architecture.<br />
<br />
=== KDE with sddm does not start spice-vdagent at login automatically ===<br />
<br />
Remove or comment out {{ic|X-GNOME-Autostart-Phase{{=}}WindowManager}} from {{ic|/etc/xdg/autostart/spice-vdagent.desktop}}. [https://github.com/systemd/systemd/issues/18791]<br />
<br />
=== Error starting domain: Requested operation is not valid: network 'default' is not active ===<br />
<br />
If for any reason the default network is deactivated, you will not be able to start any guest virtual machines which are configured to use the network. Your first attempt can be simply trying to start the network with virsh.<br />
<br />
# virsh net-start default<br />
<br />
For additional troubleshooting steps, see [https://www.xmodulo.com/network-default-is-not-active.html].<br />
<br />
== See also ==<br />
<br />
* [https://qemu.org Official QEMU website]<br />
* [https://www.linux-kvm.org Official KVM website]<br />
* [https://qemu.weilnetz.de/doc/6.0/ QEMU Emulator User Documentation]<br />
* [[Wikibooks:QEMU|QEMU Wikibook]]<br />
* [http://alien.slackbook.org/dokuwiki/doku.php?id=slackware:qemu Hardware virtualization with QEMU] by AlienBOB (last updated in 2008)<br />
* [http://blog.falconindy.com/articles/build-a-virtual-army.html Building a Virtual Army] by Falconindy<br />
* [https://git.qemu.org/?p=qemu.git;a=tree;f=docs Lastest docs]<br />
* [https://qemu.weilnetz.de/ QEMU on Windows]<br />
* [[wikipedia:Qemu|Wikipedia]]<br />
* [[debian:QEMU|Debian Wiki - QEMU]]<br />
* [https://people.gnome.org/~markmc/qemu-networking.html QEMU Networking on gnome.org]{{Dead link|2022|09|22|status=404}}<br />
* [http://bsdwiki.reedmedia.net/wiki/networking_qemu_virtual_bsd_systems.html Networking QEMU Virtual BSD Systems]<br />
* [https://www.gnu.org/software/hurd/hurd/running/qemu.html QEMU on gnu.org]<br />
* [https://wiki.freebsd.org/qemu QEMU on FreeBSD as host]<br />
* [https://wiki.mikejung.biz/KVM_/_Xen KVM/QEMU Virtio Tuning and SSD VM Optimization Guide]{{Dead link|2022|09|22|status=404}}<br />
* [https://doc.opensuse.org/documentation/leap/virtualization/html/book-virt/part-virt-qemu.html Managing Virtual Machines with QEMU - openSUSE documentation]<br />
* [https://www.ibm.com/support/knowledgecenter/en/linuxonibm/liaat/liaatkvm.htm KVM on IBM Knowledge Center]</div>Malcontenthttps://wiki.archlinux.org/index.php?title=QEMU&diff=795979QEMU2024-01-04T00:53:16Z<p>Malcontent: Remove bogus performance claim (It's not measured)</p>
<hr />
<div>[[Category:Emulation]]<br />
[[Category:Hypervisors]]<br />
[[de:QEMU]]<br />
[[es:QEMU]]<br />
[[fr:QEMU]]<br />
[[ja:QEMU]]<br />
[[zh-hans:QEMU]]<br />
{{Related articles start}}<br />
{{Related|:Category:Hypervisors}}<br />
{{Related|Libvirt}}<br />
{{Related|QEMU/Guest graphics acceleration}}<br />
{{Related|PCI passthrough via OVMF}}<br />
{{Related articles end}}<br />
<br />
According to the [https://wiki.qemu.org/Main_Page QEMU about page], "QEMU is a generic and open source machine emulator and virtualizer."<br />
<br />
When used as a machine emulator, QEMU can run OSes and programs made for one machine (e.g. an ARM board) on a different machine (e.g. your x86 PC). By using dynamic translation, it achieves very good performance.<br />
<br />
QEMU can use other hypervisors like [[Xen]] or [[KVM]] to use CPU extensions ([[Wikipedia:Hardware-assisted virtualization|HVM]]) for virtualization. When used as a virtualizer, QEMU achieves near native performances by executing the guest code directly on the host CPU.<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|qemu-full}} package (or {{Pkg|qemu-base}} for the version without GUI) and below optional packages for your needs:<br />
<br />
* {{Pkg|qemu-block-gluster}} - [[Glusterfs]] block support<br />
* {{Pkg|qemu-block-iscsi}} - [[iSCSI]] block support<br />
* {{Pkg|samba}} - [[Samba|SMB/CIFS]] server support<br />
<br />
Alternatively, {{Pkg|qemu-user-static}} exists as a usermode and static variant.<br />
<br />
=== QEMU variants ===<br />
<br />
QEMU is offered in several variants suited for different use cases.<br />
<br />
As a first classification, QEMU is offered in full-system and usermode emulation modes:<br />
<br />
; Full-system emulation<br />
: In this mode, QEMU emulates a full system, including one or several processors and various peripherals. It is more accurate but slower, and does not require the emulated OS to be Linux.<br />
: QEMU commands for full-system emulation are named {{ic|qemu-system-''target_architecture''}}, e.g. {{ic|qemu-system-x86_64}} for emulating [[Wikipedia:x86_64|x86_64]] CPUs, {{ic|qemu-system-i386}} for Intel [[Wikipedia:i386|32-bit x86]] CPUs, {{ic|qemu-system-arm}} for [[Wikipedia:ARM architecture family#32-bit architecture|ARM (32 bits)]], {{ic|qemu-system-aarch64}} for [[Wikipedia:AArch64|ARM64]], etc.<br />
: If the target architecture matches the host CPU, this mode may still benefit from a significant speedup by using a hypervisor like [[#Enabling KVM|KVM]] or Xen.<br />
; [https://www.qemu.org/docs/master/user/main.html Usermode emulation]<br />
: In this mode, QEMU is able to invoke a Linux executable compiled for a (potentially) different architecture by leveraging the host system resources. There may be compatibility issues, e.g. some features may not be implemented, dynamically linked executables will not work out of the box (see [[#Chrooting into arm/arm64 environment from x86_64]] to address this) and only Linux is supported (although [https://wiki.winehq.org/Emulation Wine may be used] for running Windows executables).<br />
: QEMU commands for usermode emulation are named {{ic|qemu-''target_architecture''}}, e.g. {{ic|qemu-x86_64}} for emulating 64-bit CPUs.<br />
<br />
QEMU is offered in dynamically-linked and statically-linked variants:<br />
<br />
; Dynamically-linked (default): {{ic|qemu-*}} commands depend on the host OS libraries, so executables are smaller.<br />
; Statically-linked: {{ic|qemu-*}} commands can be copied to any Linux system with the same architecture.<br />
<br />
In the case of Arch Linux, full-system emulation is offered as:<br />
<br />
; Non-headless (default): This variant enables GUI features that require additional dependencies (like SDL or GTK).<br />
; Headless: This is a slimmer variant that does not require GUI (this is suitable e.g. for servers).<br />
<br />
Note that headless and non-headless versions install commands with the same name (e.g. {{ic|qemu-system-x86_64}}) and thus cannot be both installed at the same time.<br />
<br />
=== Details on packages available in Arch Linux ===<br />
<br />
* The {{Pkg|qemu-desktop}} package provides the {{ic|x86_64}} architecture emulators for full-system emulation ({{ic|qemu-system-x86_64}}). The {{Pkg|qemu-emulators-full}} package provides the {{ic|x86_64}} usermode variant ({{ic|qemu-x86_64}}) and also for the rest of supported architectures it includes both full-system and usermode variants (e.g. {{ic|qemu-system-arm}} and {{ic|qemu-arm}}).<br />
* The headless versions of these packages (only applicable to full-system emulation) are {{Pkg|qemu-base}} ({{ic|x86_64}}-only) and {{Pkg|qemu-emulators-full}} (rest of architectures).<br />
* Full-system emulation can be expanded with some QEMU modules present in separate packages: {{Pkg|qemu-block-gluster}}, {{Pkg|qemu-block-iscsi}} and {{Pkg|qemu-guest-agent}}.<br />
* {{Pkg|qemu-user-static}} provides a usermode and static variant for all target architectures supported by QEMU. The installed QEMU commands are named {{ic|qemu-''target_architecture''-static}}, for example, {{ic|qemu-x86_64-static}} for intel 64-bit CPUs.<br />
<br />
{{Note|At present, Arch does not offer a full-system mode and statically linked variant (neither officially nor via AUR), as this is usually not needed.}}<br />
<br />
=== Custom build ===<br />
<br />
{{Remove|Explaining how to use the [[Arch build system]] is out of scope here. There is no motivation for the customization in the first place.}}<br />
<br />
To obtain a customized version of QEMU, [[Git#Getting a Git repository|clone]] the package source of {{Pkg|qemu-common}} or {{AUR|qemu-git}}.<br />
<br />
The respective [[PKGBUILD]] file calls QEMU's [https://www.gnu.org/prep/standards/html_node/Configuration.html configure script] which accepts parameters obtainable by first manually running --help on it. <br />
To access this help beforehand, you may [[Makepkg#Usage|use makepkg]] to let it download and extract the QEMU source, canceling the build process as soon as the configure script begins.<br />
<br />
With the PKGBUILD file's configure script calls modified as desired, you may [[Makepkg#Usage|use makepkg]] (again) to let it build the packages, though it is inadvisable to let it install them as conflicting headless / static packages will be built as well and a typical user certainly won't need the additional system emulators for the other architectures.<br />
<br />
When the build process completes, it is advisable to instead copy your desired packages (see the [[#Removal|list for qemu-desktop in "Removal"]]{{Broken section link}}) to a different directory, [[Pacman#Additional commands|let pacman install them all]] and add them to the [[Pacman#Skip package from being upgraded|IgnorePkg]] list so you get to upgrade them manually.<br />
<br />
== Graphical front-ends for QEMU ==<br />
<br />
Unlike other virtualization programs such as [[VirtualBox]] and [[VMware]], QEMU does not provide a GUI to manage virtual machines (other than the window that appears when running a virtual machine), nor does it provide a way to create persistent virtual machines with saved settings. All parameters to run a virtual machine must be specified on the command line at every launch, unless you have created a custom script to start your virtual machine(s).<br />
<br />
[[Libvirt]] provides a convenient way to manage QEMU virtual machines. See [[Libvirt#Client|list of libvirt clients]] for available front-ends.<br />
<br />
== Creating new virtualized system ==<br />
<br />
=== Creating a hard disk image ===<br />
<br />
{{Accuracy|If I get the man page right the raw format only allocates the full size if the filesystem does not support "holes" or it is <br />
explicitly told to preallocate. See {{man|1|qemu-img|NOTES}}.}} <br />
<br />
{{Tip|See [[Wikibooks:QEMU/Images]] for more information on QEMU images.}}<br />
<br />
To run QEMU you will need a hard disk image, unless you are booting a live system from CD-ROM or the network (and not doing so to install an operating system to a hard disk image). A hard disk image is a file which stores the contents of the emulated hard disk.<br />
<br />
A hard disk image can be ''raw'', so that it is literally byte-by-byte the same as what the guest sees, and will always use the full capacity of the guest hard drive on the host. This method provides the least I/O overhead, but can waste a lot of space, as not-used space on the guest cannot be used on the host.<br />
<br />
Alternatively, the hard disk image can be in a format such as ''qcow2'' which only allocates space to the image file when the guest operating system actually writes to those sectors on its virtual hard disk. The image appears as the full size to the guest operating system, even though it may take up only a very small amount of space on the host system. This image format also supports QEMU snapshotting functionality (see [[#Creating and managing snapshots via the monitor console]] for details). However, using this format instead of ''raw'' will likely affect performance.<br />
<br />
QEMU provides the {{ic|qemu-img}} command to create hard disk images. For example to create a 4 GiB image in the ''raw'' format:<br />
<br />
$ qemu-img create -f raw ''image_file'' 4G<br />
<br />
You may use {{ic|-f qcow2}} to create a ''qcow2'' disk instead.<br />
<br />
{{Note|You can also simply create a ''raw'' image by creating a file of the needed size using {{ic|dd}} or {{ic|fallocate}}.}}<br />
<br />
{{Warning|If you store the hard disk images on a [[Btrfs]] file system, you should consider disabling [[Btrfs#Copy-on-Write (CoW)|Copy-on-Write]] for the directory before creating any images.}}<br />
<br />
==== Overlay storage images ====<br />
<br />
You can create a storage image once (the 'backing' image) and have QEMU keep mutations to this image in an overlay image. This allows you to revert to a previous state of this storage image. You could revert by creating a new overlay image at the time you wish to revert, based on the original backing image.<br />
<br />
To create an overlay image, issue a command like:<br />
<br />
$ qemu-img create -o backing_file=''img1.raw'',backing_fmt=''raw'' -f ''qcow2'' ''img1.cow''<br />
<br />
After that you can run your QEMU virtual machine as usual (see [[#Running virtualized system]]):<br />
<br />
$ qemu-system-x86_64 ''img1.cow''<br />
<br />
The backing image will then be left intact and mutations to this storage will be recorded in the overlay image file.<br />
<br />
When the path to the backing image changes, repair is required.<br />
<br />
{{Warning|The backing image's absolute filesystem path is stored in the (binary) overlay image file. Changing the backing image's path requires some effort.}}<br />
<br />
Make sure that the original backing image's path still leads to this image. If necessary, make a symbolic link at the original path to the new path. Then issue a command like:<br />
<br />
$ qemu-img rebase -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
At your discretion, you may alternatively perform an 'unsafe' rebase where the old path to the backing image is not checked:<br />
<br />
$ qemu-img rebase -u -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
==== Resizing an image ====<br />
<br />
{{Warning|Resizing an image containing an NTFS boot file system could make the operating system installed on it unbootable. It is recommended to create a backup first.}}<br />
<br />
The {{ic|qemu-img}} executable has the {{ic|resize}} option, which enables easy resizing of a hard drive image. It works for both ''raw'' and ''qcow2''. For example, to increase image space by 10 GiB, run:<br />
<br />
$ qemu-img resize ''disk_image'' +10G<br />
<br />
After enlarging the disk image, you must use file system and partitioning tools inside the virtual machine to actually begin using the new space. <br />
<br />
===== Shrinking an image =====<br />
<br />
When shrinking a disk image, you must first reduce the allocated file systems and partition sizes using the file system and partitioning tools inside the virtual machine and then shrink the disk image accordingly. For a Windows guest, this can be performed from the "create and format hard disk partitions" control panel.<br />
<br />
{{Warning|Proceeding to shrink the disk image without reducing the guest partition sizes will result in data loss.}}<br />
<br />
Then, to decrease image space by 10 GiB, run:<br />
<br />
$ qemu-img resize --shrink ''disk_image'' -10G<br />
<br />
==== Converting an image ====<br />
<br />
You can convert an image to other formats using {{ic|qemu-img convert}}. This example shows how to convert a ''raw'' image to ''qcow2'':<br />
<br />
$ qemu-img convert -f raw -O qcow2 ''input''.img ''output''.qcow2<br />
<br />
This will not remove the original input file.<br />
<br />
=== Preparing the installation media ===<br />
<br />
To install an operating system into your disk image, you need the installation medium (e.g. optical disc, USB-drive, or ISO image) for the operating system. The installation medium should not be mounted because QEMU accesses the media directly.<br />
<br />
{{Tip|If using an optical disc, it is a good idea to first dump the media to a file because this both improves performance and does not require you to have direct access to the devices (that is, you can run QEMU as a regular user without having to change access permissions on the media's device file). For example, if the CD-ROM device node is named {{ic|/dev/cdrom}}, you can dump it to a file with the command: {{bc|1=$ dd if=/dev/cdrom of=''cd_image.iso'' bs=4k}}}}<br />
<br />
=== Installing the operating system ===<br />
<br />
This is the first time you will need to start the emulator. To install the operating system on the disk image, you must attach both the disk image and the installation media to the virtual machine, and have it boot from the installation media.<br />
<br />
For example on i386 guests, to install from a bootable ISO file as CD-ROM and a raw disk image:<br />
<br />
$ qemu-system-x86_64 -cdrom ''iso_image'' -boot order=d -drive file=''disk_image'',format=raw<br />
<br />
See {{man|1|qemu}} for more information about loading other media types (such as floppy, disk images or physical drives) and [[#Running virtualized system]] for other useful options.<br />
<br />
After the operating system has finished installing, the QEMU image can be booted directly (see [[#Running virtualized system]]).<br />
<br />
{{Note|By default only 128 MiB of memory is assigned to the machine. The amount of memory can be adjusted with the {{ic|-m}} switch, for example {{ic|-m 512M}} or {{ic|-m 2G}}.}}<br />
<br />
{{Tip|<br />
* Instead of specifying {{ic|1=-boot order=x}}, some users may feel more comfortable using a boot menu: {{ic|1=-boot menu=on}}, at least during configuration and experimentation.<br />
* When running QEMU in headless mode, it starts a local VNC server on port 5900 per default. You can use [[TigerVNC]] to connect to the guest OS: {{ic|vncviewer :5900}}<br />
* If you need to replace floppies or CDs as part of the installation process, you can use the QEMU machine monitor (press {{ic|Ctrl+Alt+2}} in the virtual machine's window) to remove and attach storage devices to a virtual machine. Type {{ic|info block}} to see the block devices, and use the {{ic|change}} command to swap out a device. Press {{ic|Ctrl+Alt+1}} to go back to the virtual machine.<br />
}}<br />
<br />
== Running virtualized system ==<br />
<br />
{{ic|qemu-system-*}} binaries (for example {{ic|qemu-system-i386}} or {{ic|qemu-system-x86_64}}, depending on guest's architecture) are used to run the virtualized guest. The usage is:<br />
<br />
$ qemu-system-x86_64 ''options'' ''disk_image''<br />
<br />
Options are the same for all {{ic|qemu-system-*}} binaries, see {{man|1|qemu}} for documentation of all options.<br />
<br />
Usually, if an option has many possible values, you can use<br />
<br />
$ qemu-system-x86_64 ''option'' ''help''<br />
<br />
to list all possible values. If it supports properties, you can use<br />
<br />
$ qemu-system-x86_64 ''option'' ''value,help''<br />
<br />
to list all available properties.<br />
<br />
For example:<br />
$ qemu-system-x86_64 -machine help<br />
$ qemu-system-x86_64 -machine q35,help<br />
$ qemu-system-x86_64 -device help<br />
$ qemu-system-x86_64 -device qxl,help<br />
<br />
You can use these methods and the {{man|1|qemu}} documentation to understand the options used in follow sections.<br />
<br />
By default, QEMU will show the virtual machine's video output in a window. One thing to keep in mind: when you click inside the QEMU window, the mouse pointer is grabbed. To release it, press {{ic|Ctrl+Alt+g}}.<br />
<br />
{{Warning|QEMU should never be run as root. If you must launch it in a script as root, you should use the {{ic|-runas}} option to make QEMU drop root privileges.}}<br />
<br />
=== Enabling KVM ===<br />
<br />
KVM (''Kernel-based Virtual Machine'') full virtualization must be supported by your Linux kernel and your hardware, and necessary [[kernel modules]] must be loaded. See [[KVM]] for more information.<br />
<br />
To start QEMU in KVM mode, append {{ic|-accel kvm}} to the additional start options. To check if KVM is enabled for a running virtual machine, enter the [[#QEMU monitor]] and type {{ic|info kvm}}.<br />
<br />
{{Note|<br />
* The argument {{ic|1=accel=kvm}} of the {{ic|-machine}} option is equivalent to the {{ic|-enable-kvm}} or the {{ic|-accel kvm}} option.<br />
* CPU model {{ic|host}} requires KVM.<br />
* If you start your virtual machine with a GUI tool and experience very bad performance, you should check for proper KVM support, as QEMU may be falling back to software emulation.<br />
* KVM needs to be enabled in order to start Windows 7 or Windows 8 properly without a ''blue screen''.<br />
}}<br />
<br />
=== Enabling IOMMU (Intel VT-d/AMD-Vi) support ===<br />
<br />
First enable IOMMU, see [[PCI passthrough via OVMF#Setting up IOMMU]].<br />
<br />
Add {{ic|-device intel-iommu}} to create the IOMMU device:<br />
<br />
$ qemu-system-x86_64 '''-enable-kvm -machine q35 -device intel-iommu''' -cpu host ..<br />
<br />
{{Note|<br />
On Intel CPU based systems creating an IOMMU device in a QEMU guest with {{ic|-device intel-iommu}} will disable PCI passthrough with an error like: {{bc|Device at bus pcie.0 addr 09.0 requires iommu notifier which is currently not supported by intel-iommu emulation}} While adding the kernel parameter {{ic|1=intel_iommu=on}} is still needed for remapping IO (e.g. [[PCI passthrough via OVMF#Isolating the GPU|PCI passthrough with vfio-pci]]), {{ic|-device intel-iommu}} should not be set if PCI passthrough is required.<br />
}}<br />
<br />
=== Booting in UEFI mode ===<br />
<br />
The default firmware used by QEMU is [https://www.coreboot.org/SeaBIOS SeaBIOS], which is a Legacy BIOS implementation. QEMU uses {{ic|/usr/share/qemu/bios-256k.bin}} (provided by the {{Pkg|seabios}} package) as a default read-only (ROM) image. You can use the {{ic|-bios}} argument to select another firmware file. However, UEFI requires writable memory to work properly, so you need to emulate [https://wiki.qemu.org/Features/PC_System_Flash PC System Flash] instead.<br />
<br />
[https://github.com/tianocore/tianocore.github.io/wiki/OVMF OVMF] is a TianoCore project to enable UEFI support for Virtual Machines. It can be [[install]]ed with the {{Pkg|edk2-ovmf}} package.<br />
<br />
There are two ways to use OVMF as a firmware. The first is to copy {{ic|/usr/share/edk2/x64/OVMF.4m.fd}}, make it writable and use as a pflash drive:<br />
<br />
-drive if=pflash,format=raw,file=''/copy/of/OVMF.4m.fd''<br />
<br />
All changes to the UEFI settings will be saved directly to this file.<br />
<br />
Another and more preferable way is to split OVMF into two files. The first one will be read-only and store the firmware executable, and the second one will be used as a writable variable store. The advantage is that you can use the firmware file directly without copying, so it will be updated automatically by [[pacman]].<br />
<br />
Use {{ic|/usr/share/edk2/x64/OVMF_CODE.4m.fd}} as a first read-only pflash drive. Copy {{ic|/usr/share/edk2/x64/OVMF_VARS.4m.fd}}, make it writable and use as a second writable pflash drive:<br />
<br />
-drive if=pflash,format=raw,readonly=on,file=/usr/share/edk2/x64/OVMF_CODE.4m.fd \<br />
-drive if=pflash,format=raw,file=''/copy/of/OVMF_VARS.4m.fd''<br />
<br />
If secure boot is wanted, replace {{ic|/usr/share/edk2/x64/OVMF_CODE.4m.fd}} with {{ic|/usr/share/edk2/x64/OVMF_CODE.secboot.4m.fd}}.<br />
<br />
=== Trusted Platform Module emulation ===<br />
<br />
QEMU can emulate [[Trusted Platform Module]], which is required by some systems such as Windows 11 (which requires TPM 2.0).<br />
<br />
[[Install]] the {{Pkg|swtpm}} package, which provides a software TPM implementation. Create some directory for storing TPM data ({{ic|''/path/to/mytpm''}} will be used as an example). Run this command to start the emulator:<br />
<br />
$ swtpm socket --tpm2 --tpmstate dir=''/path/to/mytpm'' --ctrl type=unixio,path=''/path/to/mytpm/swtpm-sock''<br />
<br />
{{ic|''/path/to/mytpm/swtpm-sock''}} will be created by ''swtpm'': this is a UNIX socket to which QEMU will connect. You can put it in any directory.<br />
<br />
By default, ''swtpm'' starts a TPM version 1.2 emulator. The {{ic|--tpm2}} option enables TPM 2.0 emulation.<br />
<br />
Finally, add the following options to QEMU:<br />
<br />
-chardev socket,id=chrtpm,path=''/path/to/mytpm/swtpm-sock'' \<br />
-tpmdev emulator,id=tpm0,chardev=chrtpm \<br />
-device tpm-tis,tpmdev=tpm0<br />
<br />
and TPM will be available inside the virtual machine. After shutting down the virtual machine, ''swtpm'' will be automatically terminated.<br />
<br />
See [https://qemu-project.gitlab.io/qemu/specs/tpm.html the QEMU documentation] for more information. <br />
<br />
If guest OS still doesn't recognize the TPM device, try to adjust ''CPU Models and Topology'' options. It might cause problem.<br />
<br />
== Sharing data between host and guest ==<br />
<br />
=== Network ===<br />
<br />
Data can be shared between the host and guest OS using any network protocol that can transfer files, such as [[NFS]], [[SMB]], [[Wikipedia:Network block device|NBD]], HTTP, [[Very Secure FTP Daemon|FTP]], or [[SSH]], provided that you have set up the network appropriately and enabled the appropriate services.<br />
<br />
The default user-mode networking allows the guest to access the host OS at the IP address 10.0.2.2. Any servers that you are running on your host OS, such as a SSH server or SMB server, will be accessible at this IP address. So on the guests, you can mount directories exported on the host via [[SMB]] or [[NFS]], or you can access the host's HTTP server, etc.<br />
It will not be possible for the host OS to access servers running on the guest OS, but this can be done with other network configurations (see [[#Tap networking with QEMU]]).<br />
<br />
=== QEMU's port forwarding ===<br />
<br />
{{Note|QEMU's port forwarding is IPv4-only. IPv6 port forwarding is not implemented and the last patches were proposed in 2018.[https://lore.kernel.org/qemu-devel/1540512223-21199-1-git-send-email-max7255@yandex-team.ru/T/#u]}}<br />
<br />
QEMU can forward ports from the host to the guest to enable e.g. connecting from the host to an SSH server running on the guest.<br />
<br />
For example, to bind port 60022 on the host with port 22 (SSH) on the guest, start QEMU with a command like:<br />
<br />
$ qemu-system-x86_64 ''disk_image'' -nic user,hostfwd=tcp::60022-:22<br />
<br />
Make sure the sshd is running on the guest and connect with:<br />
<br />
$ ssh ''guest-user''@127.0.0.1 -p 60022<br />
<br />
You can use [[SSHFS]] to mount the guest's file system at the host for shared read and write access.<br />
<br />
To forward several ports, you just repeat the {{ic|hostfwd}} in the {{ic|-nic}} argument, e.g. for VNC's port:<br />
<br />
$ qemu-system-x86_64 ''disk_image'' -nic user,hostfwd=tcp::60022-:22,hostfwd=tcp::5900-:5900<br />
<br />
=== QEMU's built-in SMB server ===<br />
<br />
QEMU's documentation says it has a "built-in" SMB server, but actually it just starts up [[Samba]] on the host with an automatically generated {{ic|smb.conf}} file located in {{ic|/tmp/qemu-smb.''random_string''}} and makes it accessible to the guest at a different IP address (10.0.2.4 by default). This only works for user networking, and is useful when you do not want to start the normal [[Samba]] service on the host, which the guest can also access if you have set up shares on it.<br />
<br />
Only a single directory can be set as shared with the option {{ic|1=smb=}}, but adding more directories (even while the virtual machine is running) could be as easy as creating symbolic links in the shared directory if QEMU configured SMB to follow symbolic links. It does not do so, but the configuration of the running SMB server can be changed as described below.<br />
<br />
''Samba'' must be installed on the host. To enable this feature, start QEMU with a command like:<br />
<br />
$ qemu-system-x86_64 -nic user,id=nic0,smb=''shared_dir_path'' ''disk_image''<br />
<br />
where {{ic|''shared_dir_path''}} is a directory that you want to share between the guest and host.<br />
<br />
Then, in the guest, you will be able to access the shared directory on the host 10.0.2.4 with the share name "qemu". For example, in Windows Explorer you would go to {{ic|\\10.0.2.4\qemu}}.<br />
<br />
{{Note|<br />
* If you are using sharing options multiple times like {{ic|1=-net user,smb=''shared_dir_path1'' -net user,smb=''shared_dir_path2''}} or {{ic|1=-net user,smb=''shared_dir_path1'',smb=''shared_dir_path2''}} then it will share only the last defined one.<br />
* If you cannot access the shared folder and the guest system is Windows, check that the [http://ecross.mvps.org/howto/enable-netbios-over-tcp-ip-with-windows.htm NetBIOS protocol is enabled]{{Dead link|2023|05|06|status=domain name not resolved}} and that a firewall does not block [https://technet.microsoft.com/en-us/library/cc940063.aspx ports] used by the NetBIOS protocol.<br />
* If you cannot access the shared folder and the guest system is Windows 10 Enterprise or Education or Windows Server 2016, [https://support.microsoft.com/en-us/help/4046019 enable guest access].<br />
* If you use [[#Tap networking with QEMU]], use {{ic|1=-device virtio-net,netdev=vmnic -netdev user,id=vmnic,smb=''shared_dir_path''}} to get SMB.<br />
}}<br />
<br />
One way to share multiple directories and to add or remove them while the virtual machine is running, is to share an empty directory and create/remove symbolic links to the directories in the shared directory. For this to work, the configuration of the running SMB server can be changed with the following script, which also allows the execution of files on the guest that are not set executable on the host:<br />
<br />
#!/bin/sh<br />
eval $(ps h -C smbd -o pid,args | grep /tmp/qemu-smb | gawk '{print "pid="$1";conf="$6}')<br />
echo "[global]<br />
allow insecure wide links = yes<br />
[qemu]<br />
follow symlinks = yes<br />
wide links = yes<br />
acl allow execute always = yes" >> "$conf"<br />
# in case the change is not detected automatically:<br />
smbcontrol --configfile="$conf" "$pid" reload-config<br />
<br />
This can be applied to the running server started by qemu only after the guest has connected to the network drive the first time. An alternative to this method is to add additional shares to the configuration file like so:<br />
<br />
echo "[''myshare'']<br />
path=''another_path''<br />
read only=no<br />
guest ok=yes<br />
force user=''username''" >> $conf<br />
<br />
This share will be available on the guest as {{ic|\\10.0.2.4\''myshare''}}.<br />
<br />
=== Using filesystem passthrough and VirtFS ===<br />
<br />
See the [https://wiki.qemu.org/Documentation/9psetup QEMU documentation].<br />
<br />
=== Host file sharing with virtiofsd ===<br />
<br />
{{Style|See [[Help:Style/Formatting and punctuation]].}}<br />
<br />
virtiofsd is shipped with QEMU package. Documentation is available [https://qemu-stsquad.readthedocs.io/en/docs-next/tools/virtiofsd.html online]{{Dead link|2023|05|06|status=404}} or {{ic|/usr/share/doc/qemu/qemu/tools/virtiofsd.html}} on local file system with {{Pkg|qemu-docs}} installed.<br />
<br />
Add user that runs qemu to the 'kvm' [[user group]], because it needs to access the virtiofsd socket. You might have to logout for change to take effect.<br />
<br />
{{Accuracy|Running services as root is not secure. Also the process should be wrapped in a systemd service.}}<br />
<br />
Start as virtiofsd as root:<br />
<br />
# /usr/lib/virtiofsd --socket-path=/var/run/qemu-vm-001.sock --shared-dir /tmp/vm-001 --cache always<br />
<br />
where<br />
<br />
* {{ic|/var/run/qemu-vm-001.sock}} is a socket file,<br />
* {{ic|/tmp/vm-001}} is a shared directory between the host and the guest virtual machine.<br />
<br />
The created socket file has root only access permission. Give group kvm access to it with:<br />
<br />
# chgrp kvm qemu-vm-001.sock; chmod g+rxw qemu-vm-001.sock<br />
<br />
Add the following configuration options when starting the virtual machine:<br />
<br />
-object memory-backend-memfd,id=mem,size=4G,share=on \<br />
-numa node,memdev=mem \<br />
-chardev socket,id=char0,path=/var/run/qemu-vm-001.sock \<br />
-device vhost-user-fs-pci,chardev=char0,tag=myfs<br />
<br />
where<br />
<br />
{{Expansion|Explain the remaining options (or remove them if they are not necessary).}}<br />
<br />
* {{ic|1=size=4G}} shall match size specified with {{ic|-m 4G}} option,<br />
* {{ic|/var/run/qemu-vm-001.sock}} points to socket file started earlier,<br />
<br />
{{Style|The section should not be specific to Windows.}}<br />
<br />
Remember, that guest must be configured to enable sharing. For Windows there are [https://virtio-fs.gitlab.io/howto-windows.html instructions]. Once configured, Windows will have the {{ic|Z:}} drive mapped automatically with shared directory content.<br />
<br />
Your Windows 10 guest system is properly configured if it has:<br />
<br />
* VirtioFSSService windows service,<br />
* WinFsp.Launcher windows service,<br />
* VirtIO FS Device driver under "System devices" in Windows "Device Manager".<br />
<br />
If the above installed and {{ic|Z:}} drive is still not listed, try repairing "Virtio-win-guest-tools" in Windows ''Add/Remove programs''.<br />
<br />
=== Mounting a partition of the guest on the host ===<br />
<br />
It can be useful to mount a drive image under the host system, it can be a way to transfer files in and out of the guest. This should be done when the virtual machine is not running.<br />
<br />
The procedure to mount the drive on the host depends on the type of qemu image, ''raw'' or ''qcow2''. We detail thereafter the steps to mount a drive in the two formats in [[#Mounting a partition from a raw image]] and [[#Mounting a partition from a qcow2 image]]. For the full documentation see [[Wikibooks:QEMU/Images#Mounting an image on the host]].<br />
<br />
{{Warning|You must unmount the partitions before running the virtual machine again. Otherwise, data corruption is very likely to occur.}}<br />
<br />
==== Mounting a partition from a raw image ====<br />
<br />
It is possible to mount partitions that are inside a raw disk image file by setting them up as loopback devices.<br />
<br />
===== With manually specifying byte offset =====<br />
<br />
One way to mount a disk image partition is to mount the disk image at a certain offset using a command like the following:<br />
<br />
# mount -o loop,offset=32256 ''disk_image'' ''mountpoint''<br />
<br />
The {{ic|1=offset=32256}} option is actually passed to the {{ic|losetup}} program to set up a loopback device that starts at byte offset 32256 of the file and continues to the end. This loopback device is then mounted. You may also use the {{ic|sizelimit}} option to specify the exact size of the partition, but this is usually unnecessary.<br />
<br />
Depending on your disk image, the needed partition may not start at offset 32256. Run {{ic|fdisk -l ''disk_image''}} to see the partitions in the image. fdisk gives the start and end offsets in 512-byte sectors, so multiply by 512 to get the correct offset to pass to {{ic|mount}}.<br />
<br />
===== With loop module autodetecting partitions =====<br />
<br />
The Linux loop driver actually supports partitions in loopback devices, but it is disabled by default. To enable it, do the following:<br />
<br />
* Get rid of all your loopback devices (unmount all mounted images, etc.).<br />
* [[Kernel modules#Manual module handling|Unload]] the {{ic|loop}} kernel module, and load it with the {{ic|1=max_part=15}} parameter set. Additionally, the maximum number of loop devices can be controlled with the {{ic|max_loop}} parameter.<br />
<br />
{{Tip|You can put an entry in {{ic|/etc/modprobe.d}} to load the loop module with {{ic|1=max_part=15}} every time, or you can put {{ic|1=loop.max_part=15}} on the kernel command-line, depending on whether you have the {{ic|loop.ko}} module built into your kernel or not.}}<br />
<br />
Set up your image as a loopback device:<br />
<br />
# losetup -f -P ''disk_image''<br />
<br />
Then, if the device created was {{ic|/dev/loop0}}, additional devices {{ic|/dev/loop0p''X''}} will have been automatically created, where X is the number of the partition. These partition loopback devices can be mounted directly. For example:<br />
<br />
# mount /dev/loop0p1 ''mountpoint''<br />
<br />
To mount the disk image with ''udisksctl'', see [[Udisks#Mount loop devices]].<br />
<br />
===== With kpartx =====<br />
<br />
''kpartx'' from the {{Pkg|multipath-tools}} package can read a partition table on a device and create a new device for each partition. For example:<br />
<br />
# kpartx -a ''disk_image''<br />
<br />
This will setup the loopback device and create the necessary partition(s) device(s) in {{ic|/dev/mapper/}}.<br />
<br />
==== Mounting a partition from a qcow2 image ====<br />
<br />
We will use {{ic|qemu-nbd}}, which lets use the NBD (''network block device'') protocol to share the disk image.<br />
<br />
First, we need the ''nbd'' module loaded:<br />
<br />
# modprobe nbd max_part=16<br />
<br />
Then, we can share the disk and create the device entries:<br />
<br />
# qemu-nbd -c /dev/nbd0 ''/path/to/image.qcow2''<br />
<br />
Discover the partitions:<br />
<br />
# partprobe /dev/nbd0<br />
<br />
''fdisk'' can be used to get information regarding the different partitions in {{ic|''nbd0''}}:<br />
<br />
{{hc|# fdisk -l /dev/nbd0|2=<br />
Disk /dev/nbd0: 25.2 GiB, 27074281472 bytes, 52879456 sectors<br />
Units: sectors of 1 * 512 = 512 bytes<br />
Sector size (logical/physical): 512 bytes / 512 bytes<br />
I/O size (minimum/optimal): 512 bytes / 512 bytes<br />
Disklabel type: dos<br />
Disk identifier: 0xa6a4d542<br />
<br />
Device Boot Start End Sectors Size Id Type<br />
/dev/nbd0p1 * 2048 1026047 1024000 500M 7 HPFS/NTFS/exFAT<br />
/dev/nbd0p2 1026048 52877311 51851264 24.7G 7 HPFS/NTFS/exFAT}}<br />
<br />
Then mount any partition of the drive image, for example the partition 2:<br />
<br />
# mount /dev/nbd0'''p2''' ''mountpoint''<br />
<br />
After the usage, it is important to unmount the image and reverse previous steps, i.e. unmount the partition and disconnect the nbd device:<br />
<br />
# umount ''mountpoint''<br />
# qemu-nbd -d /dev/nbd0<br />
<br />
=== Using any real partition as the single primary partition of a hard disk image ===<br />
<br />
Sometimes, you may wish to use one of your system partitions from within QEMU. Using a raw partition for a virtual machine will improve performance, as the read and write operations do not go through the file system layer on the physical host. Such a partition also provides a way to share data between the host and guest.<br />
<br />
In Arch Linux, device files for raw partitions are, by default, owned by ''root'' and the ''disk'' group. If you would like to have a non-root user be able to read and write to a raw partition, you must either change the owner of the partition's device file to that user, add that user to the ''disk'' group, or use [[ACL]] for more fine-grained access control.<br />
<br />
{{Warning|<br />
* Although it is possible, it is not recommended to allow virtual machines to alter critical data on the host system, such as the root partition.<br />
* You must not mount a file system on a partition read-write on both the host and the guest at the same time. Otherwise, data corruption will result.<br />
}}<br />
<br />
After doing so, you can attach the partition to a QEMU virtual machine as a virtual disk.<br />
<br />
However, things are a little more complicated if you want to have the ''entire'' virtual machine contained in a partition. In that case, there would be no disk image file to actually boot the virtual machine since you cannot install a boot loader to a partition that is itself formatted as a file system and not as a partitioned device with an MBR. Such a virtual machine can be booted either by: [[#Specifying kernel and initrd manually]], [[#Simulating a virtual disk with MBR]], [[#Using the device-mapper]], [[#Using a linear RAID]] or [[#Using a Network Block Device]].<br />
<br />
==== Specifying kernel and initrd manually ====<br />
<br />
QEMU supports loading [[Kernels|Linux kernels]] and [[initramfs|init ramdisks]] directly, thereby circumventing boot loaders such as [[GRUB]]. It then can be launched with the physical partition containing the root file system as the virtual disk, which will not appear to be partitioned. This is done by issuing a command similar to the following:<br />
<br />
{{Note|In this example, it is the '''host's''' images that are being used, not the guest's. If you wish to use the guest's images, either mount {{ic|/dev/sda3}} read-only (to protect the file system from the host) and specify the {{ic|/full/path/to/images}} or use some kexec hackery in the guest to reload the guest's kernel (extends boot time). }}<br />
<br />
$ qemu-system-x86_64 -kernel /boot/vmlinuz-linux -initrd /boot/initramfs-linux.img -append root=/dev/sda /dev/sda3<br />
<br />
In the above example, the physical partition being used for the guest's root file system is {{ic|/dev/sda3}} on the host, but it shows up as {{ic|/dev/sda}} on the guest.<br />
<br />
You may, of course, specify any kernel and initrd that you want, and not just the ones that come with Arch Linux.<br />
<br />
When there are multiple [[kernel parameters]] to be passed to the {{ic|-append}} option, they need to be quoted using single or double quotes. For example:<br />
<br />
... -append 'root=/dev/sda1 console=ttyS0'<br />
<br />
==== Simulating a virtual disk with MBR ====<br />
<br />
A more complicated way to have a virtual machine use a physical partition, while keeping that partition formatted as a file system and not just having the guest partition the partition as if it were a disk, is to simulate an MBR for it so that it can boot using a boot loader such as GRUB.<br />
<br />
For the following, suppose you have a plain, unmounted {{ic|/dev/hda''N''}} partition with some file system on it you wish to make part of a QEMU disk image. The trick is to dynamically prepend a master boot record (MBR) to the real partition you wish to embed in a QEMU raw disk image. More generally, the partition can be any part of a larger simulated disk, in particular a block device that simulates the original physical disk but only exposes {{ic|/dev/hda''N''}} to the virtual machine.<br />
<br />
A virtual disk of this type can be represented by a VMDK file that contains references to (a copy of) the MBR and the partition, but QEMU does not support this VMDK format. For instance, a virtual disk [https://www.virtualbox.org/manual/ch09.html#rawdisk created by]<br />
<br />
$ VBoxManage internalcommands createrawvmdk -filename ''/path/to/file.vmdk'' -rawdisk /dev/hda<br />
<br />
will be rejected by QEMU with the error message<br />
<br />
Unsupported image type 'partitionedDevice'<br />
<br />
Note that {{ic|VBoxManage}} creates two files, {{ic|''file.vmdk''}} and {{ic|''file-pt.vmdk''}}, the latter being a copy of the MBR, to which the text file {{ic|file.vmdk}} points. Read operations outside the target partition or the MBR would give zeros, while written data would be discarded.<br />
<br />
===== Using the device-mapper =====<br />
<br />
A method that is similar to the use of a VMDK descriptor file uses the [https://docs.kernel.org/admin-guide/device-mapper/index.html device-mapper] to prepend a loop device attached to the MBR file to the target partition. In case we do not need our virtual disk to have the same size as the original, we first create a file to hold the MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=2048<br />
<br />
Here, a 1 MiB (2048 * 512 bytes) file is created in accordance with partition alignment policies used by modern disk partitioning tools. For compatibility with older partitioning software, 63 sectors instead of 2048 might be required. The MBR only needs a single 512 bytes block, the additional free space can be used for a BIOS boot partition and, in the case of a hybrid partitioning scheme, for a GUID Partition Table. Then, we attach a loop device to the MBR file:<br />
<br />
{{hc|# losetup --show -f ''/path/to/mbr''|/dev/loop0}}<br />
<br />
In this example, the resulting device is {{ic|/dev/loop0}}. The device mapper is now used to join the MBR and the partition:<br />
<br />
# echo "0 2048 linear /dev/loop0 0<br />
2048 `blockdev --getsz /dev/hda''N''` linear /dev/hda''N'' 0" | dmsetup create qemu<br />
<br />
The resulting {{ic|/dev/mapper/qemu}} is what we will use as a QEMU raw disk image. Additional steps are required to create a partition table (see the section that describes the use of a linear RAID for an example) and boot loader code on the virtual disk (which will be stored in {{ic|''/path/to/mbr''}}).<br />
<br />
The following setup is an example where the position of {{ic|/dev/hda''N''}} on the virtual disk is to be the same as on the physical disk and the rest of the disk is hidden, except for the MBR, which is provided as a copy:<br />
<br />
# dd if=/dev/hda count=1 of=''/path/to/mbr''<br />
# loop=`losetup --show -f ''/path/to/mbr''`<br />
# start=`blockdev --report /dev/hda''N'' | tail -1 | awk '{print $5}'`<br />
# size=`blockdev --getsz /dev/hda''N''`<br />
# disksize=`blockdev --getsz /dev/hda`<br />
# echo "0 1 linear $loop 0<br />
1 $((start-1)) zero<br />
$start $size linear /dev/hda''N'' 0<br />
$((start+size)) $((disksize-start-size)) zero" | dmsetup create qemu<br />
<br />
The table provided as standard input to {{ic|dmsetup}} has a similar format as the table in a VDMK descriptor file produced by {{ic|VBoxManage}} and can alternatively be loaded from a file with {{ic|dmsetup create qemu --table ''table_file''}}. To the virtual machine, only {{ic|/dev/hda''N''}} is accessible, while the rest of the hard disk reads as zeros and discards written data, except for the first sector. We can print the table for {{ic|/dev/mapper/qemu}} with {{ic|dmsetup table qemu}} (use {{ic|udevadm info -rq name /sys/dev/block/''major'':''minor''}} to translate {{ic|''major'':''minor''}} to the corresponding {{ic|/dev/''blockdevice''}} name). Use {{ic|dmsetup remove qemu}} and {{ic|losetup -d $loop}} to delete the created devices.<br />
<br />
A situation where this example would be useful is an existing Windows XP installation in a multi-boot configuration and maybe a hybrid partitioning scheme (on the physical hardware, Windows XP could be the only operating system that uses the MBR partition table, while more modern operating systems installed on the same computer could use the GUID Partition Table). Windows XP supports hardware profiles, so that that the same installation can be used with different hardware configurations alternatingly (in this case bare metal vs. virtual) with Windows needing to install drivers for newly detected hardware only once for every profile. Note that in this example the boot loader code in the copied MBR needs to be updated to directly load Windows XP from {{ic|/dev/hda''N''}} instead of trying to start the multi-boot capable boot loader (like GRUB) present in the original system. Alternatively, a copy of the boot partition containing the boot loader installation can be included in the virtual disk the same way as the MBR.<br />
<br />
===== Using a linear RAID =====<br />
<br />
{{Out of date|[[Wikipedia:Cylinder-head-sector|CHS]] has been obsolete for decades.}}<br />
<br />
You can also do this using software [[RAID]] in linear mode (you need the {{ic|linear.ko}} kernel driver) and a loopback device: <br />
<br />
First, you create some small file to hold the MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=32<br />
<br />
Here, a 16 KiB (32 * 512 bytes) file is created. It is important not to make it too small (even if the MBR only needs a single 512 bytes block), since the smaller it will be, the smaller the chunk size of the software RAID device will have to be, which could have an impact on performance. Then, you setup a loopback device to the MBR file:<br />
<br />
# losetup -f ''/path/to/mbr''<br />
<br />
Let us assume the resulting device is {{ic|/dev/loop0}}, because we would not already have been using other loopbacks. Next step is to create the "merged" MBR + {{ic|/dev/hda''N''}} disk image using software RAID:<br />
<br />
# modprobe linear<br />
# mdadm --build --verbose /dev/md0 --chunk=16 --level=linear --raid-devices=2 /dev/loop0 /dev/hda''N''<br />
<br />
The resulting {{ic|/dev/md0}} is what you will use as a QEMU raw disk image (do not forget to set the permissions so that the emulator can access it). The last (and somewhat tricky) step is to set the disk configuration (disk geometry and partitions table) so that the primary partition start point in the MBR matches the one of {{ic|/dev/hda''N''}} inside {{ic|/dev/md0}} (an offset of exactly 16 * 512 = 16384 bytes in this example). Do this using {{ic|fdisk}} on the host machine, not in the emulator: the default raw disc detection routine from QEMU often results in non-kibibyte-roundable offsets (such as 31.5 KiB, as in the previous section) that cannot be managed by the software RAID code. Hence, from the host:<br />
<br />
# fdisk /dev/md0<br />
<br />
Press {{ic|X}} to enter the expert menu. Set number of 's'ectors per track so that the size of one cylinder matches the size of your MBR file. For two heads and a sector size of 512, the number of sectors per track should be 16, so we get cylinders of size 2x16x512=16k.<br />
<br />
Now, press {{ic|R}} to return to the main menu.<br />
<br />
Press {{ic|P}} and check that the cylinder size is now 16k.<br />
<br />
Now, create a single primary partition corresponding to {{ic|/dev/hda''N''}}. It should start at cylinder 2 and end at the end of the disk (note that the number of cylinders now differs from what it was when you entered fdisk.<br />
<br />
Finally, 'w'rite the result to the file: you are done. You now have a partition you can mount directly from your host, as well as part of a QEMU disk image:<br />
<br />
$ qemu-system-x86_64 -hdc /dev/md0 ''[...]''<br />
<br />
You can, of course, safely set any boot loader on this disk image using QEMU, provided the original {{ic|/dev/hda''N''}} partition contains the necessary tools.<br />
<br />
===== Using a Network Block Device =====<br />
<br />
With [https://docs.kernel.org/admin-guide/blockdev/nbd.html Network Block Device], Linux can use a remote server as one of its block device. You may use {{ic|nbd-server}} (from the {{Pkg|nbd}} package) to create an MBR wrapper for QEMU.<br />
<br />
Assuming you have already set up your MBR wrapper file like above, rename it to {{ic|wrapper.img.0}}. Then create a symbolic link named {{ic|wrapper.img.1}} in the same directory, pointing to your partition. Then put the following script in the same directory:<br />
<br />
{{bc|1=<br />
#!/bin/sh<br />
dir="$(realpath "$(dirname "$0")")"<br />
cat >wrapper.conf <<EOF<br />
[generic]<br />
allowlist = true<br />
listenaddr = 127.713705<br />
port = 10809<br />
<br />
[wrap]<br />
exportname = $dir/wrapper.img<br />
multifile = true<br />
EOF<br />
<br />
nbd-server \<br />
-C wrapper.conf \<br />
-p wrapper.pid \<br />
"$@"<br />
}}<br />
<br />
The {{ic|.0}} and {{ic|.1}} suffixes are essential; the rest can be changed. After running the above script (which you may need to do as root to make sure nbd-server is able to access the partition), you can launch QEMU with:<br />
<br />
qemu-system-x86_64 -drive file=nbd:127.713705:10809:exportname=wrap ''[...]''<br />
<br />
=== Using an entire physical disk device inside the virtual machine ===<br />
<br />
{{Style|Duplicates [[#Using any real partition as the single primary partition of a hard disk image]], libvirt instructions do not belong to this page.}}<br />
<br />
You may have a second disk with a different OS (like Windows) on it and may want to gain the ability to also boot it inside a virtual machine.<br />
Since the disk access is raw, the disk will perform quite well inside the virtual machine.<br />
<br />
==== Windows virtual machine boot prerequisites ====<br />
<br />
Be sure to install the [https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/archive-virtio/ virtio drivers] inside the OS on that disk before trying to boot it in the virtual machine.<br />
For Win 7 use version [https://askubuntu.com/questions/1310440/using-virtio-win-drivers-with-win7-sp1-x64 0.1.173-4].<br />
Some singular drivers from newer virtio builds may be used on Win 7 but you will have to install them manually via device manager.<br />
For Win 10 you can use the latest virtio build.<br />
<br />
===== Set up the windows disk interface drivers =====<br />
<br />
You may get a {{ic|0x0000007B}} bluescreen when trying to boot the virtual machine. This means Windows can not access the drive during the early boot stage because the disk interface driver it would need for that is not loaded / is set to start manually.<br />
<br />
The solution is to [https://superuser.com/a/1032769 enable these drivers to start at boot].<br />
<br />
In {{ic|HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services}}, find the folders {{ic|aliide, amdide, atapi, cmdide, iastor (may not exist), iastorV, intelide, LSI_SAS, msahci, pciide and viaide}}.<br />
Inside each of those, set all their "start" values to 0 in order to enable them at boot.<br />
If your drive is a PCIe NVMe drive, also enable that driver (should it exist).<br />
<br />
==== Find the unique path of your disk ====<br />
<br />
Run {{ic|ls /dev/disk/by-id/}}: tere you pick out the ID of the drive you want to insert into the virtual machine, for example {{ic|ata-TS512GMTS930L_C199211383}}.<br />
Now add that ID to {{ic|/dev/disk/by-id/}} so you get {{ic|/dev/disk/by-id/ata-TS512GMTS930L_C199211383}}.<br />
That is the unique path to that disk.<br />
<br />
==== Add the disk in QEMU CLI ====<br />
<br />
In QEMU CLI that would probably be:<br />
<br />
{{ic|1=-drive file=/dev/disk/by-id/ata-TS512GMTS930L_C199211383,format=raw,media=disk}}<br />
<br />
Just modify {{ic|file{{=}}}} to be the unique path of your drive.<br />
<br />
==== Add the disk in libvirt ====<br />
<br />
In libvirt XML that translates to<br />
<br />
{{hc|$ virsh edit ''vmname''|<nowiki><br />
...<br />
<disk type="block" device="disk"><br />
<driver name="qemu" type="raw" cache="none" io="native"/><br />
<source dev="/dev/disk/by-id/ata-TS512GMTS930L_C199211383"/><br />
<target dev="sda" bus="sata"/><br />
<address type="drive" controller="0" bus="0" target="0" unit="0"/><br />
</disk><br />
...<br />
</nowiki>}}<br />
<br />
Just modify "source dev" to be the unique path of your drive.<br />
<br />
==== Add the disk in virt-manager ====<br />
<br />
When creating a virtual machine, select "import existing drive" and just paste that unique path.<br />
If you already have the virtual machine, add a device, storage, then select or create custom storage.<br />
Now paste the unique path.<br />
<br />
== Networking ==<br />
<br />
{{Style|Network topologies (sections [[#Host-only networking]], [[#Internal networking]] and info spread out across other sections) should not be described alongside the various virtual interfaces implementations, such as [[#User-mode networking]], [[#Tap networking with QEMU]], [[#Networking with VDE2]].}}<br />
<br />
The performance of virtual networking should be better with tap devices and bridges than with user-mode networking or vde because tap devices and bridges are implemented in-kernel.<br />
<br />
In addition, networking performance can be improved by assigning virtual machines a [https://wiki.libvirt.org/page/Virtio virtio] network device rather than the default emulation of an e1000 NIC. See [[#Installing virtio drivers]] for more information.<br />
<br />
=== Link-level address caveat ===<br />
<br />
By giving the {{ic|-net nic}} argument to QEMU, it will, by default, assign a virtual machine a network interface with the link-level address {{ic|52:54:00:12:34:56}}. However, when using bridged networking with multiple virtual machines, it is essential that each virtual machine has a unique link-level (MAC) address on the virtual machine side of the tap device. Otherwise, the bridge will not work correctly, because it will receive packets from multiple sources that have the same link-level address. This problem occurs even if the tap devices themselves have unique link-level addresses because the source link-level address is not rewritten as packets pass through the tap device.<br />
<br />
Make sure that each virtual machine has a unique link-level address, but it should always start with {{ic|52:54:}}. Use the following option, replace ''X'' with arbitrary hexadecimal digit:<br />
<br />
$ qemu-system-x86_64 -net nic,macaddr=52:54:''XX:XX:XX:XX'' -net vde ''disk_image''<br />
<br />
Generating unique link-level addresses can be done in several ways:<br />
<br />
* Manually specify unique link-level address for each NIC. The benefit is that the DHCP server will assign the same IP address each time the virtual machine is run, but it is unusable for large number of virtual machines.<br />
* Generate random link-level address each time the virtual machine is run. Practically zero probability of collisions, but the downside is that the DHCP server will assign a different IP address each time. You can use the following command in a script to generate random link-level address in a {{ic|macaddr}} variable:<br />
<br />
{{bc|1=<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
qemu-system-x86_64 -net nic,macaddr="$macaddr" -net vde ''disk_image''<br />
}}<br />
<br />
* Use the following script {{ic|qemu-mac-hasher.py}} to generate the link-level address from the virtual machine name using a hashing function. Given that the names of virtual machines are unique, this method combines the benefits of the aforementioned methods: it generates the same link-level address each time the script is run, yet it preserves the practically zero probability of collisions.<br />
<br />
{{hc|qemu-mac-hasher.py|2=<br />
#!/usr/bin/env python<br />
# usage: qemu-mac-hasher.py <VMName><br />
<br />
import sys<br />
import zlib<br />
<br />
crc = str(hex(zlib.crc32(sys.argv[1].encode("utf-8")))).replace("x", "")[-8:]<br />
print("52:54:%s%s:%s%s:%s%s:%s%s" % tuple(crc))<br />
}}<br />
<br />
In a script, you can use for example:<br />
<br />
vm_name="''VM Name''"<br />
qemu-system-x86_64 -name "$vm_name" -net nic,macaddr=$(qemu-mac-hasher.py "$vm_name") -net vde ''disk_image''<br />
<br />
=== User-mode networking ===<br />
<br />
By default, without any {{ic|-netdev}} arguments, QEMU will use user-mode networking with a built-in DHCP server. Your virtual machines will be assigned an IP address when they run their DHCP client, and they will be able to access the physical host's network through IP masquerading done by QEMU.<br />
<br />
{{Note|ICMPv6 will not work, as support for it is not implemented: {{ic|Slirp: external icmpv6 not supported yet}}. [[Ping]]ing an IPv6 address will not work.}}<br />
<br />
This default configuration allows your virtual machines to easily access the Internet, provided that the host is connected to it, but the virtual machines will not be directly visible on the external network, nor will virtual machines be able to talk to each other if you start up more than one concurrently.<br />
<br />
QEMU's user-mode networking can offer more capabilities such as built-in TFTP or SMB servers, redirecting host ports to the guest (for example to allow SSH connections to the guest) or attaching guests to VLANs so that they can talk to each other. See the QEMU documentation on the {{ic|-net user}} flag for more details.<br />
<br />
However, user-mode networking has limitations in both utility and performance. More advanced network configurations require the use of tap devices or other methods.<br />
<br />
{{Note|If the host system uses [[systemd-networkd]], make sure to symlink the {{ic|/etc/resolv.conf}} file as described in [[systemd-networkd#Required services and setup]], otherwise the DNS lookup in the guest system will not work.}}<br />
<br />
{{Tip|<br />
* To use the virtio driver with user-mode networking, the option is: {{ic|1=-nic user,model=virtio-net-pci}}.<br />
* You can isolate user-mode networking from the host and the outside world by adding {{ic|1=restrict=y}}, for example: {{ic|1=-net user,restrict=y}}<br />
}}<br />
<br />
=== Tap networking with QEMU ===<br />
<br />
[[wikipedia:TUN/TAP|Tap devices]] are a Linux kernel feature that allows you to create virtual network interfaces that appear as real network interfaces. Packets sent to a tap interface are delivered to a userspace program, such as QEMU, that has bound itself to the interface.<br />
<br />
QEMU can use tap networking for a virtual machine so that packets sent to the tap interface will be sent to the virtual machine and appear as coming from a network interface (usually an Ethernet interface) in the virtual machine. Conversely, everything that the virtual machine sends through its network interface will appear on the tap interface.<br />
<br />
Tap devices are supported by the Linux bridge drivers, so it is possible to bridge together tap devices with each other and possibly with other host interfaces such as {{ic|eth0}}. This is desirable if you want your virtual machines to be able to talk to each other, or if you want other machines on your LAN to be able to talk to the virtual machines.<br />
<br />
{{Warning|If you bridge together tap device and some host interface, such as {{ic|eth0}}, your virtual machines will appear directly on the external network, which will expose them to possible attack. Depending on what resources your virtual machines have access to, you may need to take all the [[Firewalls|precautions]] you normally would take in securing a computer to secure your virtual machines. If the risk is too great, virtual machines have little resources or you set up multiple virtual machines, a better solution might be to use [[#Host-only networking|host-only networking]] and set up NAT. In this case you only need one firewall on the host instead of multiple firewalls for each guest.}}<br />
<br />
As indicated in the user-mode networking section, tap devices offer higher networking performance than user-mode. If the guest OS supports virtio network driver, then the networking performance will be increased considerably as well. Supposing the use of the tap0 device, that the virtio driver is used on the guest, and that no scripts are used to help start/stop networking, next is part of the qemu command one should see:<br />
<br />
-device virtio-net,netdev=network0 -netdev tap,id=network0,ifname=tap0,script=no,downscript=no<br />
<br />
But if already using a tap device with virtio networking driver, one can even boost the networking performance by enabling vhost, like:<br />
<br />
-device virtio-net,netdev=network0 -netdev tap,id=network0,ifname=tap0,script=no,downscript=no,vhost=on<br />
<br />
See [https://web.archive.org/web/20160222161955/http://www.linux-kvm.com:80/content/how-maximize-virtio-net-performance-vhost-net] for more information.<br />
<br />
==== Host-only networking ====<br />
<br />
If the bridge is given an IP address and traffic destined for it is allowed, but no real interface (e.g. {{ic|eth0}}) is connected to the bridge, then the virtual machines will be able to talk to each other and the host system. However, they will not be able to talk to anything on the external network, provided that you do not set up IP masquerading on the physical host. This configuration is called ''host-only networking'' by other virtualization software such as [[VirtualBox]].<br />
<br />
{{Tip|<br />
* If you want to set up IP masquerading, e.g. NAT for virtual machines, see the [[Internet sharing#Enable NAT]] page.<br />
* See [[Network bridge]] for information on creating bridge.<br />
* You may want to have a DHCP server running on the bridge interface to service the virtual network. For example, to use the {{ic|172.20.0.1/16}} subnet with [[dnsmasq]] as the DHCP server:<br />
<br />
{{bc|1=<br />
# ip addr add 172.20.0.1/16 dev br0<br />
# ip link set br0 up<br />
# dnsmasq --interface=br0 --bind-interfaces --dhcp-range=172.20.0.2,172.20.255.254<br />
}}<br />
}}<br />
<br />
==== Internal networking ====<br />
<br />
If you do not give the bridge an IP address and add an [[iptables]] rule to drop all traffic to the bridge in the INPUT chain, then the virtual machines will be able to talk to each other, but not to the physical host or to the outside network. This configuration is called ''internal networking'' by other virtualization software such as [[VirtualBox]]. You will need to either assign static IP addresses to the virtual machines or run a DHCP server on one of them.<br />
<br />
By default iptables would drop packets in the bridge network. You may need to use such iptables rule to allow packets in a bridged network:<br />
<br />
# iptables -I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Bridged networking using qemu-bridge-helper ====<br />
<br />
This method does not require a start-up script and readily accommodates multiple taps and multiple bridges. It uses {{ic|/usr/lib/qemu/qemu-bridge-helper}} binary, which allows creating tap devices on an existing bridge.<br />
<br />
{{Tip|<br />
* See [[Network bridge]] for information on creating bridge.<br />
* See https://wiki.qemu.org/Features/HelperNetworking for more information on QEMU's network helper.<br />
}}<br />
<br />
First, create a configuration file containing the names of all bridges to be used by QEMU:<br />
<br />
{{hc|/etc/qemu/bridge.conf|<br />
allow ''br0''<br />
allow ''br1''<br />
...}}<br />
<br />
Make sure {{ic|/etc/qemu/}} has {{ic|755}} [[permissions]]. [https://gitlab.com/qemu-project/qemu/-/issues/515 QEMU issues] and [https://www.gns3.com/community/discussions/gns3-cannot-work-with-qemu GNS3 issues] may arise if this is not the case.<br />
<br />
Now start the virtual machine; the most basic usage to run QEMU with the default network helper and default bridge {{ic|br0}}:<br />
<br />
$ qemu-system-x86_64 -nic bridge ''[...]''<br />
<br />
Using the bridge {{ic|br1}} and the virtio driver:<br />
<br />
$ qemu-system-x86_64 -nic bridge,br=''br1'',model=virtio-net-pci ''[...]''<br />
<br />
==== Creating bridge manually ====<br />
<br />
{{Style|This section needs serious cleanup and may contain out-of-date information.}}<br />
<br />
{{Tip|Since QEMU 1.1, the [https://wiki.qemu.org/Features/HelperNetworking network bridge helper] can set tun/tap up for you without the need for additional scripting. See [[#Bridged networking using qemu-bridge-helper]].}}<br />
<br />
The following describes how to bridge a virtual machine to a host interface such as {{ic|eth0}}, which is probably the most common configuration. This configuration makes it appear that the virtual machine is located directly on the external network, on the same Ethernet segment as the physical host machine.<br />
<br />
We will replace the normal Ethernet adapter with a bridge adapter and bind the normal Ethernet adapter to it.<br />
<br />
* Install {{Pkg|bridge-utils}}, which provides {{ic|brctl}} to manipulate bridges.<br />
<br />
* Enable IPv4 forwarding:<br />
<br />
# sysctl -w net.ipv4.ip_forward=1<br />
<br />
To make the change permanent, change {{ic|1=net.ipv4.ip_forward = 0}} to {{ic|1=net.ipv4.ip_forward = 1}} in {{ic|/etc/sysctl.d/99-sysctl.conf}}.<br />
<br />
* Load the {{ic|tun}} module and configure it to be loaded on boot. See [[Kernel modules]] for details.<br />
<br />
* Optionally create the bridge. See [[Bridge with netctl]] for details. Remember to name your bridge as {{ic|br0}}, or change the scripts below to your bridge's name. In the {{ic|run-qemu}} script below, {{ic|br0}} is set up if not listed, as it is assumed that by default the host is not accessing network via the bridge.<br />
<br />
* Create the script that QEMU uses to bring up the tap adapter with {{ic|root:kvm}} 750 permissions:<br />
<br />
{{hc|/etc/qemu-ifup|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifup"<br />
echo "Bringing up $1 for bridged mode..."<br />
sudo /usr/bin/ip link set $1 up promisc on<br />
echo "Adding $1 to br0..."<br />
sudo /usr/bin/brctl addif br0 $1<br />
sleep 2<br />
</nowiki>}}<br />
<br />
* Create the script that QEMU uses to bring down the tap adapter in {{ic|/etc/qemu-ifdown}} with {{ic|root:kvm}} 750 permissions:<br />
{{hc|/etc/qemu-ifdown|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifdown"<br />
sudo /usr/bin/ip link set $1 down<br />
sudo /usr/bin/brctl delif br0 $1<br />
sudo /usr/bin/ip link delete dev $1<br />
</nowiki>}}<br />
<br />
* Use {{ic|visudo}} to add the following to your {{ic|sudoers}} file:<br />
<br />
{{bc|<nowiki><br />
Cmnd_Alias QEMU=/usr/bin/ip,/usr/bin/modprobe,/usr/bin/brctl<br />
%kvm ALL=NOPASSWD: QEMU<br />
</nowiki>}}<br />
<br />
* You launch QEMU using the following {{ic|run-qemu}} script:<br />
<br />
{{hc|run-qemu|<nowiki><br />
#!/bin/bash<br />
: '<br />
e.g. with img created via:<br />
qemu-img create -f qcow2 example.img 90G<br />
run-qemu -cdrom archlinux-x86_64.iso -boot order=d -drive file=example.img,format=qcow2 -m 4G -enable-kvm -cpu host -smp 4<br />
run-qemu -drive file=example.img,format=qcow2 -m 4G -enable-kvm -cpu host -smp 4<br />
'<br />
<br />
nicbr0() {<br />
sudo ip link set dev $1 promisc on up &> /dev/null<br />
sudo ip addr flush dev $1 scope host &>/dev/null<br />
sudo ip addr flush dev $1 scope site &>/dev/null<br />
sudo ip addr flush dev $1 scope global &>/dev/null<br />
sudo ip link set dev $1 master br0 &> /dev/null<br />
}<br />
_nicbr0() {<br />
sudo ip link set $1 promisc off down &> /dev/null<br />
sudo ip link set dev $1 nomaster &> /dev/null<br />
}<br />
<br />
HASBR0="$( ip link show | grep br0 )"<br />
if [ -z $HASBR0 ] ; then<br />
ROUTER="192.168.1.1"<br />
SUBNET="192.168.1."<br />
NIC=$(ip link show | grep en | grep 'state UP' | head -n 1 | cut -d":" -f 2 | xargs)<br />
IPADDR=$(ip addr show | grep -o "inet $SUBNET\([0-9]*\)" | cut -d ' ' -f2)<br />
sudo ip link add name br0 type bridge &> /dev/null<br />
sudo ip link set dev br0 up<br />
sudo ip addr add $IPADDR/24 brd + dev br0<br />
sudo ip route del default &> /dev/null<br />
sudo ip route add default via $ROUTER dev br0 onlink<br />
nicbr0 $NIC<br />
sudo iptables -I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
fi<br />
<br />
USERID=$(whoami)<br />
precreationg=$(ip tuntap list | cut -d: -f1 | sort)<br />
sudo ip tuntap add user $USERID mode tap<br />
postcreation=$(ip tuntap list | cut -d: -f1 | sort)<br />
TAP=$(comm -13 <(echo "$precreationg") <(echo "$postcreation"))<br />
nicbr0 $TAP<br />
<br />
printf -v MACADDR "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
qemu-system-x86_64 -net nic,macaddr=$MACADDR,model=virtio \<br />
-net tap,ifname=$TAP,script=no,downscript=no,vhost=on \<br />
$@<br />
<br />
_nicbr0 $TAP<br />
sudo ip link set dev $TAP down &> /dev/null<br />
sudo ip tuntap del $TAP mode tap<br />
<br />
if [ -z $HASBR0 ] ; then<br />
_nicbr0 $NIC<br />
sudo ip addr del dev br0 $IPADDR/24 &> /dev/null<br />
sudo ip link set dev br0 down<br />
sudo ip link delete br0 type bridge &> /dev/null<br />
sudo ip route del default &> /dev/null<br />
sudo ip link set dev $NIC up<br />
sudo ip route add default via $ROUTER dev $NIC onlink &> /dev/null<br />
fi<br />
</nowiki>}}<br />
<br />
Then to launch a virtual machine, do something like this<br />
<br />
$ run-qemu -hda ''myvm.img'' -m 512<br />
<br />
* It is recommended for performance and security reasons to disable the [http://ebtables.netfilter.org/documentation/bridge-nf.html firewall on the bridge]:<br />
<br />
{{hc|/etc/sysctl.d/10-disable-firewall-on-bridge.conf|<nowiki><br />
net.bridge.bridge-nf-call-ip6tables = 0<br />
net.bridge.bridge-nf-call-iptables = 0<br />
net.bridge.bridge-nf-call-arptables = 0<br />
</nowiki>}}<br />
<br />
In order to apply the parameters described above on boot, you will also need to load the br-netfilter module on boot. Otherwise, the parameters will not exist when sysctl will try to modify them.<br />
<br />
{{hc|/etc/modules-load.d/br_netfilter.conf|<nowiki><br />
br_netfilter<br />
</nowiki>}}<br />
<br />
Run {{ic|sysctl -p /etc/sysctl.d/10-disable-firewall-on-bridge.conf}} to apply the changes immediately.<br />
<br />
See the [https://wiki.libvirt.org/page/Networking#Creating_network_initscripts libvirt wiki] and [https://bugzilla.redhat.com/show_bug.cgi?id=512206 Fedora bug 512206]. If you get errors by sysctl during boot about non-existing files, make the {{ic|bridge}} module load at boot. See [[Kernel module#systemd]].<br />
<br />
Alternatively, you can configure [[iptables]] to allow all traffic to be forwarded across the bridge by adding a rule like this:<br />
<br />
-I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Network sharing between physical device and a Tap device through iptables ====<br />
<br />
{{Merge|Internet_sharing|Duplication, not specific to QEMU.}}<br />
<br />
Bridged networking works fine between a wired interface (Eg. eth0), and it is easy to setup. However if the host gets connected to the network through a wireless device, then bridging is not possible.<br />
<br />
See [[Network bridge#Wireless interface on a bridge]] as a reference.<br />
<br />
One way to overcome that is to setup a tap device with a static IP, making linux automatically handle the routing for it, and then forward traffic between the tap interface and the device connected to the network through iptables rules.<br />
<br />
See [[Internet sharing]] as a reference.<br />
<br />
There you can find what is needed to share the network between devices, included tap and tun ones. The following just hints further on some of the host configurations required. As indicated in the reference above, the client needs to be configured for a static IP, using the IP assigned to the tap interface as the gateway. The caveat is that the DNS servers on the client might need to be manually edited if they change when changing from one host device connected to the network to another.<br />
<br />
To allow IP forwarding on every boot, one need to add the following lines to sysctl configuration file inside {{ic|/etc/sysctl.d}}:<br />
<br />
net.ipv4.ip_forward = 1<br />
net.ipv6.conf.default.forwarding = 1<br />
net.ipv6.conf.all.forwarding = 1<br />
<br />
The iptables rules can look like:<br />
<br />
# Forwarding from/to outside<br />
iptables -A FORWARD -i ${INT} -o ${EXT_0} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_1} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_2} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_0} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_1} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_2} -o ${INT} -j ACCEPT<br />
# NAT/Masquerade (network address translation)<br />
iptables -t nat -A POSTROUTING -o ${EXT_0} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_1} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_2} -j MASQUERADE<br />
<br />
The prior supposes there are 3 devices connected to the network sharing traffic with one internal device, where for example:<br />
<br />
INT=tap0<br />
EXT_0=eth0<br />
EXT_1=wlan0<br />
EXT_2=tun0<br />
<br />
The prior shows a forwarding that would allow sharing wired and wireless connections with the tap device.<br />
<br />
The forwarding rules shown are stateless, and for pure forwarding. One could think of restricting specific traffic, putting a firewall in place to protect the guest and others. However those would decrease the networking performance, while a simple bridge does not include any of that.<br />
<br />
Bonus: Whether the connection is wired or wireless, if one gets connected through VPN to a remote site with a tun device, supposing the tun device opened for that connection is tun0, and the prior iptables rules are applied, then the remote connection gets also shared with the guest. This avoids the need for the guest to also open a VPN connection. Again, as the guest networking needs to be static, then if connecting the host remotely this way, one most probably will need to edit the DNS servers on the guest.<br />
<br />
=== Networking with VDE2 ===<br />
<br />
{{Style|This section needs serious cleanup and may contain out-of-date information.}}<br />
<br />
==== What is VDE? ====<br />
<br />
VDE stands for Virtual Distributed Ethernet. It started as an enhancement of [[User-mode Linux|uml]]_switch. It is a toolbox to manage virtual networks.<br />
<br />
The idea is to create virtual switches, which are basically sockets, and to "plug" both physical and virtual machines in them. The configuration we show here is quite simple; However, VDE is much more powerful than this, it can plug virtual switches together, run them on different hosts and monitor the traffic in the switches. You are invited to read [https://wiki.virtualsquare.org/ the documentation of the project].<br />
<br />
The advantage of this method is you do not have to add sudo privileges to your users. Regular users should not be allowed to run modprobe.<br />
<br />
==== Basics ====<br />
<br />
VDE support can be [[install]]ed via the {{Pkg|vde2}} package.<br />
<br />
In our config, we use tun/tap to create a virtual interface on my host. Load the {{ic|tun}} module (see [[Kernel modules]] for details):<br />
<br />
# modprobe tun<br />
<br />
Now create the virtual switch:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
<br />
This line creates the switch, creates {{ic|tap0}}, "plugs" it, and allows the users of the group {{ic|users}} to use it.<br />
<br />
The interface is plugged in but not configured yet. To configure it, run this command:<br />
<br />
# ip addr add 192.168.100.254/24 dev tap0<br />
<br />
Now, you just have to run KVM with these {{ic|-net}} options as a normal user:<br />
<br />
$ qemu-system-x86_64 -net nic -net vde -hda ''[...]''<br />
<br />
Configure networking for your guest as you would do in a physical network.<br />
<br />
{{Tip|You might want to set up NAT on tap device to access the internet from the virtual machine. See [[Internet sharing#Enable NAT]] for more information.}}<br />
<br />
==== Startup scripts ====<br />
<br />
Example of main script starting VDE:<br />
<br />
{{hc|/etc/systemd/scripts/qemu-network-env|<nowiki><br />
#!/bin/sh<br />
# QEMU/VDE network environment preparation script<br />
<br />
# The IP configuration for the tap device that will be used for<br />
# the virtual machine network:<br />
<br />
TAP_DEV=tap0<br />
TAP_IP=192.168.100.254<br />
TAP_MASK=24<br />
TAP_NETWORK=192.168.100.0<br />
<br />
# Host interface<br />
NIC=eth0<br />
<br />
case "$1" in<br />
start)<br />
echo -n "Starting VDE network for QEMU: "<br />
<br />
# If you want tun kernel module to be loaded by script uncomment here<br />
#modprobe tun 2>/dev/null<br />
## Wait for the module to be loaded<br />
#while ! lsmod | grep -q "^tun"; do echo "Waiting for tun device"; sleep 1; done<br />
<br />
# Start tap switch<br />
vde_switch -tap "$TAP_DEV" -daemon -mod 660 -group users<br />
<br />
# Bring tap interface up<br />
ip address add "$TAP_IP"/"$TAP_MASK" dev "$TAP_DEV"<br />
ip link set "$TAP_DEV" up<br />
<br />
# Start IP Forwarding<br />
echo "1" > /proc/sys/net/ipv4/ip_forward<br />
iptables -t nat -A POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
;;<br />
stop)<br />
echo -n "Stopping VDE network for QEMU: "<br />
# Delete the NAT rules<br />
iptables -t nat -D POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
<br />
# Bring tap interface down<br />
ip link set "$TAP_DEV" down<br />
<br />
# Kill VDE switch<br />
pgrep vde_switch | xargs kill -TERM<br />
;;<br />
restart|reload)<br />
$0 stop<br />
sleep 1<br />
$0 start<br />
;;<br />
*)<br />
echo "Usage: $0 {start|stop|restart|reload}"<br />
exit 1<br />
esac<br />
exit 0<br />
</nowiki>}}<br />
<br />
Example of systemd service using the above script:<br />
<br />
{{hc|/etc/systemd/system/qemu-network-env.service|<nowiki><br />
[Unit]<br />
Description=Manage VDE Switch<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/etc/systemd/scripts/qemu-network-env start<br />
ExecStop=/etc/systemd/scripts/qemu-network-env stop<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
Change permissions for {{ic|qemu-network-env}} to be [[executable]]. <br />
<br />
You can [[start]] {{ic|qemu-network-env.service}} as usual.<br />
<br />
==== Alternative method ====<br />
<br />
If the above method does not work or you do not want to mess with kernel configs, TUN, dnsmasq, and iptables you can do the following for the same result.<br />
<br />
# vde_switch -daemon -mod 660 -group users<br />
# slirpvde --dhcp --daemon<br />
<br />
Then, to start the virtual machine with a connection to the network of the host:<br />
<br />
$ qemu-system-x86_64 -net nic,macaddr=52:54:00:00:EE:03 -net vde ''disk_image''<br />
<br />
=== VDE2 Bridge ===<br />
<br />
Based on [https://selamatpagicikgu.wordpress.com/2011/06/08/quickhowto-qemu-networking-using-vde-tuntap-and-bridge/ quickhowto: qemu networking using vde, tun/tap, and bridge] graphic. Any virtual machine connected to vde is externally exposed. For example, each virtual machine can receive DHCP configuration directly from your ADSL router.<br />
<br />
==== Basics ====<br />
<br />
Remember that you need {{ic|tun}} module and {{Pkg|bridge-utils}} package.<br />
<br />
Create the vde2/tap device:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
# ip link set tap0 up<br />
<br />
Create bridge:<br />
<br />
# brctl addbr br0<br />
<br />
Add devices:<br />
<br />
# brctl addif br0 eth0<br />
# brctl addif br0 tap0<br />
<br />
And configure bridge interface:<br />
<br />
# dhcpcd br0<br />
<br />
==== Startup scripts ====<br />
<br />
All devices must be set up. And only the bridge needs an IP address. For physical devices on the bridge (e.g. {{ic|eth0}}), this can be done with [[netctl]] using a custom Ethernet profile with:<br />
<br />
{{hc|/etc/netctl/ethernet-noip|2=<br />
Description='A more versatile static Ethernet connection'<br />
Interface=eth0<br />
Connection=ethernet<br />
IP=no<br />
}}<br />
<br />
The following custom systemd service can be used to create and activate a VDE2 tap interface for users in the {{ic|users}} user group.<br />
<br />
{{hc|/etc/systemd/system/vde2@.service|2=<br />
[Unit]<br />
Description=Network Connectivity for %i<br />
Wants=network.target<br />
Before=network.target<br />
<br />
[Service]<br />
Type=oneshot<br />
RemainAfterExit=yes<br />
ExecStart=/usr/bin/vde_switch -tap %i -daemon -mod 660 -group users<br />
ExecStart=/usr/bin/ip link set dev %i up<br />
ExecStop=/usr/bin/ip addr flush dev %i<br />
ExecStop=/usr/bin/ip link set dev %i down<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
}}<br />
<br />
And finally, you can create the [[Bridge with netctl|bridge interface with netctl]].<br />
<br />
=== Shorthand configuration ===<br />
<br />
If you are using QEMU with various networking options a lot, you probably have created a lot of {{ic|-netdev}} and {{ic|-device}} argument pairs, which gets quite repetitive. You can instead use the {{ic|-nic}} argument to combine {{ic|-netdev}} and {{ic|-device}} together, so that, for example, these arguments:<br />
<br />
-netdev tap,id=network0,ifname=tap0,script=no,downscript=no,vhost=on -device virtio-net-pci,netdev=network0<br />
<br />
become:<br />
<br />
-nic tap,script=no,downscript=no,vhost=on,model=virtio-net-pci<br />
<br />
Notice the lack of network IDs, and that the device was created with {{ic|1=model=}}. The first half of the {{ic|-nic}} parameters are {{ic|-netdev}} parameters, whereas the second half (after {{ic|1=model=}}) are related with the device. The same parameters (for example, {{ic|1=smb=}}) are used. To completely disable the networking use {{ic|-nic none}}.<br />
<br />
See [https://qemu.weilnetz.de/doc/6.0/system/net.html QEMU networking documentation] for more information on parameters you can use.<br />
<br />
== Graphic card ==<br />
<br />
QEMU can emulate a standard graphic card text mode using {{ic|-display curses}} command line option. This allows to type text and see text output directly inside a text terminal. Alternatively, {{ic|-nographic}} serves a similar purpose.<br />
<br />
QEMU can emulate several types of VGA card. The card type is passed in the {{ic|-vga ''type''}} command line option and can be {{ic|std}}, {{ic|qxl}}, {{ic|vmware}}, {{ic|virtio}}, {{ic|cirrus}} or {{ic|none}}.<br />
<br />
=== std ===<br />
<br />
With {{ic|-vga std}} you can get a resolution of up to 2560 x 1600 pixels without requiring guest drivers. This is the default since QEMU 2.2.<br />
<br />
=== qxl ===<br />
<br />
QXL is a paravirtual graphics driver with 2D support. To use it, pass the {{ic|-vga qxl}} option and install drivers in the guest. You may want to use [[#SPICE]] for improved graphical performance when using QXL.<br />
<br />
On Linux guests, the {{ic|qxl}} and {{ic|bochs_drm}} kernel modules must be loaded in order to gain a decent performance.<br />
<br />
Default VGA memory size for QXL devices is 16M which is sufficient to drive resolutions approximately up to QHD (2560x1440). To enable higher resolutions, [[#Multi-monitor support|increase vga_memmb]].<br />
<br />
=== vmware ===<br />
<br />
Although it is a bit buggy, it performs better than std and cirrus. Install the VMware drivers {{Pkg|xf86-video-vmware}} and {{Pkg|xf86-input-vmmouse}} for Arch Linux guests.<br />
<br />
=== virtio ===<br />
<br />
{{ic|virtio-vga}} / {{ic|virtio-gpu}} is a paravirtual 3D graphics driver based on [https://virgil3d.github.io/ virgl]. It's mature, currently supporting only Linux guests with {{Pkg|mesa}} compiled with the option {{ic|1=gallium-drivers=virgl}}.<br />
<br />
To enable 3D acceleration on the guest system, select this vga with {{ic|-device virtio-vga-gl}} and enable the OpenGL context in the display device with {{ic|1=-display sdl,gl=on}} or {{ic|1=-display gtk,gl=on}} for the SDL and GTK display output respectively. Successful configuration can be confirmed looking at the kernel log in the guest:<br />
<br />
{{hc|# dmesg {{!}} grep drm |<br />
[drm] pci: virtio-vga detected<br />
[drm] virgl 3d acceleration enabled<br />
}}<br />
<br />
=== cirrus ===<br />
<br />
The cirrus graphical adapter was the default [https://wiki.qemu.org/ChangeLog/2.2#VGA before 2.2]. It [https://www.kraxel.org/blog/2014/10/qemu-using-cirrus-considered-harmful/ should not] be used on modern systems.<br />
<br />
=== none ===<br />
<br />
This is like a PC that has no VGA card at all. You would not even be able to access it with the {{ic|-vnc}} option. Also, this is different from the {{ic|-nographic}} option which lets QEMU emulate a VGA card, but disables the SDL display.<br />
<br />
== SPICE ==<br />
<br />
The [https://www.spice-space.org/ SPICE project] aims to provide a complete open source solution for remote access to virtual machines in a seamless way.<br />
<br />
=== Enabling SPICE support on the host ===<br />
<br />
The following is an example of booting with SPICE as the remote desktop protocol, including the support for copy and paste from host:<br />
<br />
$ qemu-system-x86_64 -vga qxl -device virtio-serial-pci -spice port=5930,disable-ticketing=on -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
The parameters have the following meaning:<br />
<br />
# {{ic|-device virtio-serial-pci}} adds a virtio-serial device<br />
# {{ic|1=-spice port=5930,disable-ticketing=on}} set TCP port {{ic|5930}} for spice channels listening and allow client to connect without authentication{{Tip|Using [[wikipedia:Unix_socket|Unix sockets]] instead of TCP ports does not involve using network stack on the host system. It does not imply that packets are encapsulated and decapsulated to use the network and the related protocol. The sockets are identified solely by the inodes on the hard drive. It is therefore considered better for performance. Use instead {{ic|1=-spice unix=on,addr=/tmp/vm_spice.socket,disable-ticketing=on}}.}}<br />
# {{ic|1=-device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0}} opens a port for spice vdagent in the virtio-serial device,<br />
# {{ic|1=-chardev spicevmc,id=spicechannel0,name=vdagent}} adds a spicevmc chardev for that port. It is important that the {{ic|1=chardev=}} option of the {{ic|virtserialport}} device matches the {{ic|1=id=}} option given to the {{ic|chardev}} option ({{ic|spicechannel0}} in this example). It is also important that the port name is {{ic|com.redhat.spice.0}}, because that is the namespace where vdagent is looking for in the guest. And finally, specify {{ic|1=name=vdagent}} so that spice knows what this channel is for.<br />
<br />
=== Connecting to the guest with a SPICE client ===<br />
<br />
A SPICE client is necessary to connect to the guest. In Arch, the following clients are available:<br />
<br />
* {{App|virt-viewer|SPICE client recommended by the protocol developers, a subset of the virt-manager project.|https://virt-manager.org/|{{Pkg|virt-viewer}}}}<br />
* {{App|spice-gtk|SPICE GTK client, a subset of the SPICE project. Embedded into other applications as a widget.|https://www.spice-space.org/|{{Pkg|spice-gtk}}}}<br />
<br />
For clients that run on smartphone or on other platforms, refer to the ''Other clients'' section in [https://www.spice-space.org/download.html spice-space download].<br />
<br />
==== Manually running a SPICE client ====<br />
<br />
One way of connecting to a guest listening on Unix socket {{ic|/tmp/vm_spice.socket}} is to manually run the SPICE client using {{ic|$ remote-viewer spice+unix:///tmp/vm_spice.socket}} or {{ic|1=$ spicy --uri="spice+unix:///tmp/vm_spice.socket"}}, depending on the desired client. Since QEMU in SPICE mode acts similarly to a remote desktop server, it may be more convenient to run QEMU in daemon mode with the {{ic|-daemonize}} parameter.<br />
<br />
{{Tip|<br />
To connect to the guest through SSH tunneling, the following type of command can be used: {{bc|$ ssh -fL 5999:localhost:5930 ''my.domain.org'' sleep 10; spicy -h 127.0.0.1 -p 5999}}<br />
This example connects ''spicy'' to the local port {{ic|5999}} which is forwarded through SSH to the guest's SPICE server located at the address ''my.domain.org'', port {{ic|5930}}.<br />
Note the {{ic|-f}} option that requests ssh to execute the command {{ic|sleep 10}} in the background. This way, the ssh session runs while the client is active and auto-closes once the client ends.<br />
}}<br />
<br />
==== Running a SPICE client with QEMU ====<br />
<br />
QEMU can automatically start a SPICE client with an appropriate socket, if the display is set to SPICE with the {{ic|-display spice-app}} parameter. This will use the system's default SPICE client as the viewer, determined by your [[XDG MIME Applications#mimeapps.list|mimeapps.list]] files.<br />
<br />
=== Enabling SPICE support on the guest ===<br />
<br />
For '''Arch Linux guests''', for improved support for multiple monitors or clipboard sharing, the following packages should be installed:<br />
* {{Pkg|spice-vdagent}}: Spice agent xorg client that enables copy and paste between client and X-session and more. (Refer to this [https://github.com/systemd/systemd/issues/18791 issue], until fixed, for workarounds to get this to work on non-GNOME desktops.)<br />
* {{Pkg|xf86-video-qxl}}: Xorg X11 qxl video driver<br />
* {{AUR|x-resize}}: Desktop environments other than GNOME do not react automatically when the SPICE client window is resized. This package uses a [[udev]] rule and [[xrandr]] to implement auto-resizing for all X11-based desktop environments and window managers.<br />
For guests under '''other operating systems''', refer to the ''Guest'' section in spice-space [https://www.spice-space.org/download.html download].<br />
<br />
=== Password authentication with SPICE ===<br />
<br />
If you want to enable password authentication with SPICE you need to remove {{ic|disable-ticketing}} from the {{ic|-spice}} argument and instead add {{ic|1=password=''yourpassword''}}. For example:<br />
<br />
$ qemu-system-x86_64 -vga qxl -spice port=5900,password=''yourpassword'' -device virtio-serial-pci -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
Your SPICE client should now ask for the password to be able to connect to the SPICE server.<br />
<br />
=== TLS encrypted communication with SPICE ===<br />
<br />
You can also configure TLS encryption for communicating with the SPICE server. First, you need to have a directory which contains the following files (the names must be exactly as indicated):<br />
<br />
* {{ic|ca-cert.pem}}: the CA master certificate.<br />
* {{ic|server-cert.pem}}: the server certificate signed with {{ic|ca-cert.pem}}.<br />
* {{ic|server-key.pem}}: the server private key.<br />
<br />
An example of generation of self-signed certificates with your own generated CA for your server is shown in the [https://www.spice-space.org/spice-user-manual.html#_generating_self_signed_certificates Spice User Manual].<br />
<br />
Afterwards, you can run QEMU with SPICE as explained above but using the following {{ic|-spice}} argument: {{ic|1=-spice tls-port=5901,password=''yourpassword'',x509-dir=''/path/to/pki_certs''}}, where {{ic|''/path/to/pki_certs''}} is the directory path that contains the three needed files shown earlier.<br />
<br />
It is now possible to connect to the server using {{Pkg|virt-viewer}}:<br />
<br />
$ remote-viewer spice://''hostname''?tls-port=5901 --spice-ca-file=''/path/to/ca-cert.pem'' --spice-host-subject="C=''XX'',L=''city'',O=''organization'',CN=''hostname''" --spice-secure-channels=all<br />
<br />
Keep in mind that the {{ic|--spice-host-subject}} parameter needs to be set according to your {{ic|server-cert.pem}} subject. You also need to copy {{ic|ca-cert.pem}} to every client to verify the server certificate.<br />
<br />
{{Tip|You can get the subject line of the server certificate in the correct format for {{ic|--spice-host-subject}} (with entries separated by commas) using the following command: {{bc|<nowiki>$ openssl x509 -noout -subject -in server-cert.pem | cut -d' ' -f2- | sed 's/\///' | sed 's/\//,/g'</nowiki>}}<br />
}}<br />
<br />
The equivalent {{Pkg|spice-gtk}} command is:<br />
<br />
$ spicy -h ''hostname'' -s 5901 --spice-ca-file=ca-cert.pem --spice-host-subject="C=''XX'',L=''city'',O=''organization'',CN=''hostname''" --spice-secure-channels=all<br />
<br />
== VNC ==<br />
<br />
One can add the {{ic|-vnc :''X''}} option to have QEMU redirect the VGA display to the VNC session. Substitute {{ic|''X''}} for the number of the display (0 will then listen on 5900, 1 on 5901...).<br />
<br />
$ qemu-system-x86_64 -vnc :0<br />
<br />
An example is also provided in the [[#Starting QEMU virtual machines on boot]] section.<br />
<br />
{{Warning|The default VNC server setup does not use any form of authentication. Any user can connect from any host.}}<br />
<br />
=== Basic password authentication ===<br />
<br />
An access password can be setup easily by using the {{ic|password}} option. The password must be indicated in the QEMU monitor and connection is only possible once the password is provided.<br />
<br />
$ qemu-system-x86_64 -vnc :0,password -monitor stdio<br />
<br />
In the QEMU monitor, password is set using the command {{ic|change vnc password}} and then indicating the password.<br />
<br />
The following command line directly runs vnc with a password:<br />
<br />
$ printf "change vnc password\n%s\n" MYPASSWORD | qemu-system-x86_64 -vnc :0,password -monitor stdio<br />
<br />
{{Note|The password is limited to 8 characters and can be guessed through brute force attack. More elaborated protection is strongly recommended for public network.}}<br />
<br />
== Audio ==<br />
<br />
=== Creating an audio backend ===<br />
<br />
The {{ic|-audiodev}} flag sets the audio backend driver on the host and its options.<br />
<br />
To list availabe audio backend drivers:<br />
<br />
$ qemu-system-x86_64 -audiodev help<br />
<br />
Their optional settings are detailed in the {{man|1|qemu}} man page.<br />
<br />
At the bare minimum, one need to choose an audio backend and set an id, for [[PulseAudio]] for example:<br />
<br />
-audiodev pa,id=snd0<br />
<br />
=== Using the audio backend ===<br />
<br />
==== Intel HD Audio ====<br />
<br />
For Intel HD Audio emulation, add both controller and codec devices. To list the available Intel HDA Audio devices:<br />
<br />
$ qemu-system-x86_64 -device help | grep hda<br />
<br />
Add the audio controller:<br />
<br />
-device ich9-intel-hda<br />
<br />
Also add the audio codec and map it to a host audio backend id:<br />
<br />
-device hda-output,audiodev=snd0<br />
<br />
==== Intel 82801AA AC97 ====<br />
<br />
For AC97 emulation just add the audio card device and map it to a host audio backend id<br />
<br />
-device AC97,audiodev=snd0<br />
<br />
{{Note|<br />
* If the audiodev backend is not provided, QEMU looks up for it and adds it automatically, this only works for a single audiodev. For example {{ic|-device intel-hda -device hda-duplex}} will emulate {{ic|intel-hda}} on the guest using the default audiodev backend.<br />
* Video graphic card emulated drivers for the guest machine may also cause a problem with the sound quality. Test one by one to make it work. You can list possible options with {{ic|<nowiki>qemu-system-x86_64 -h | grep vga</nowiki>}}.<br />
}}<br />
<br />
==== VirtIO-Sound ====<br />
<br />
VirtIO sound is also available since QEMU 8.2.0 and onwards.<br />
<br />
Example usage:<br />
<br />
-device virtio-sound-pci,audiodev=my_audiodev \<br />
-audiodev alsa,id=my_audiodev<br />
<br />
More information can be found [https://qemu-project.gitlab.io/qemu/system/devices/virtio-snd.html here].<br />
<br />
== Installing virtio drivers ==<br />
<br />
QEMU offers guests the ability to use paravirtualized block and network devices using the [https://wiki.libvirt.org/page/Virtio virtio] drivers, which provide better performance and lower overhead.<br />
<br />
* A virtio block device requires the option {{ic|-drive}} for passing a disk image, with parameter {{ic|1=if=virtio}}:<br />
$ qemu-system-x86_64 -drive file=''disk_image'',if='''virtio'''<br />
<br />
* Almost the same goes for the network:<br />
$ qemu-system-x86_64 -nic user,model='''virtio-net-pci'''<br />
<br />
{{Note|This will only work if the guest machine has drivers for virtio devices. Linux does, and the required drivers are included in Arch Linux, but there is no guarantee that virtio devices will work with other operating systems.}}<br />
<br />
=== Preparing an Arch Linux guest ===<br />
<br />
To use virtio devices after an Arch Linux guest has been installed, the following modules must be loaded in the guest: {{ic|virtio}}, {{ic|virtio_pci}}, {{ic|virtio_blk}}, {{ic|virtio_net}}, and {{ic|virtio_ring}}. For 32-bit guests, the specific "virtio" module is not necessary.<br />
<br />
If you want to boot from a virtio disk, the initial ramdisk must contain the necessary modules. By default, this is handled by [[mkinitcpio]]'s {{ic|autodetect}} hook. Otherwise use the {{ic|MODULES}} array in {{ic|/etc/mkinitcpio.conf}} to include the necessary modules and rebuild the initial ramdisk.<br />
<br />
{{hc|/etc/mkinitcpio.conf|2=<br />
MODULES=(virtio virtio_blk virtio_pci virtio_net)}}<br />
<br />
Virtio disks are recognized with the prefix {{ic|'''v'''}} (e.g. {{ic|'''v'''da}}, {{ic|'''v'''db}}, etc.); therefore, changes must be made in at least {{ic|/etc/fstab}} and {{ic|/boot/grub/grub.cfg}} when booting from a virtio disk.<br />
<br />
{{Tip|When referencing disks by [[UUID]] in both {{ic|/etc/fstab}} and boot loader, nothing has to be done.}}<br />
<br />
Further information on paravirtualization with KVM can be found [https://www.linux-kvm.org/page/Boot_from_virtio_block_device here].<br />
<br />
You might also want to install {{Pkg|qemu-guest-agent}} to implement support for QMP commands that will enhance the hypervisor management capabilities.<br />
<br />
=== Preparing a Windows guest ===<br />
<br />
==== Virtio drivers for Windows ====<br />
<br />
Windows does not come with the virtio drivers. The latest and stable versions of the drivers are regularly built by Fedora, details on downloading the drivers are given on [https://github.com/virtio-win/virtio-win-pkg-scripts/blob/master/README.md virtio-win on GitHub]. In the following sections we will mostly use the stable ISO file provided here: [https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/stable-virtio/virtio-win.iso virtio-win.iso]. Alternatively, use {{AUR|virtio-win}}.<br />
<br />
==== Block device drivers ====<br />
<br />
===== New Install of Windows =====<br />
<br />
The drivers need to be loaded during installation, the procedure is to load the ISO image with the virtio drivers in a cdrom device along with the primary disk device and the Windows ISO install media:<br />
<br />
$ qemu-system-x86_64 ... \<br />
-drive file=''disk_image'',index=0,media=disk,if=virtio \<br />
-drive file=''windows.iso'',index=2,media=cdrom \<br />
-drive file=''virtio-win.iso'',index=3,media=cdrom \<br />
...<br />
<br />
During the installation, at some stage, the Windows installer will ask "Where do you want to install Windows?", it will give a warning that no disks are found. Follow the example instructions below (based on Windows Server 2012 R2 with Update).<br />
<br />
* Select the option ''Load Drivers''.<br />
* Uncheck the box for ''Hide drivers that are not compatible with this computer's hardware''.<br />
* Click the browse button and open the CDROM for the virtio iso, usually named "virtio-win-XX".<br />
* Now browse to {{ic|E:\viostor\[your-os]\amd64}}, select it, and confirm.<br />
<br />
You should now see your virtio disk(s) listed here, ready to be selected, formatted and installed to.<br />
<br />
===== Change existing Windows virtual machine to use virtio =====<br />
<br />
Modifying an existing Windows guest for booting from virtio disk requires that the virtio driver is loaded by the guest at boot time.<br />
We will therefore need to teach Windows to load the virtio driver at boot time before being able to boot a disk image in virtio mode.<br />
<br />
To achieve that, first create a new disk image that will be attached in virtio mode and trigger the search for the driver:<br />
<br />
$ qemu-img create -f qcow2 ''dummy.qcow2'' 1G<br />
<br />
Run the original Windows guest with the boot disk still in IDE mode, the fake disk in virtio mode and the driver ISO image.<br />
<br />
$ qemu-system-x86_64 -m 4G -drive file=''disk_image'',if=ide -drive file=''dummy.qcow2'',if=virtio -cdrom virtio-win.iso<br />
<br />
Windows will detect the fake disk and look for a suitable driver. If it fails, go to ''Device Manager'', locate the SCSI drive with an exclamation mark icon (should be open), click ''Update driver'' and select the virtual CD-ROM. Do not navigate to the driver folder within the CD-ROM, simply select the CD-ROM drive and Windows will find the appropriate driver automatically (tested for Windows 7 SP1).<br />
<br />
Request Windows to boot in safe mode next time it starts up. This can be done using the ''msconfig.exe'' tool in Windows. In safe mode all the drivers will be loaded at boot time including the new virtio driver. Once Windows knows that the virtio driver is required at boot it will memorize it for future boot.<br />
<br />
Once instructed to boot in safe mode, you can turn off the virtual machine and launch it again, now with the boot disk attached in virtio mode:<br />
<br />
$ qemu-system-x86_64 -m 4G -drive file=''disk_image'',if=virtio<br />
<br />
You should boot in safe mode with virtio driver loaded, you can now return to ''msconfig.exe'' disable safe mode boot and restart Windows.<br />
<br />
{{Note|If you encounter the blue screen of death using the {{ic|1=if=virtio}} parameter, it probably means the virtio disk driver is not installed or not loaded at boot time, reboot in safe mode and check your driver configuration.}}<br />
<br />
==== Network drivers ====<br />
<br />
Installing virtio network drivers is a bit easier, simply add the {{ic|-nic}} argument.<br />
<br />
$ qemu-system-x86_64 -m 4G -drive file=''windows_disk_image'',if=virtio -nic user,model=virtio-net-pci -cdrom virtio-win.iso<br />
<br />
Windows will detect the network adapter and try to find a driver for it. If it fails, go to the ''Device Manager'', locate the network adapter with an exclamation mark icon (should be open), click ''Update driver'' and select the virtual CD-ROM. Do not forget to select the checkbox which says to search for directories recursively.<br />
<br />
==== Balloon driver ====<br />
<br />
If you want to track you guest memory state (for example via {{ic|virsh}} command {{ic|dommemstat}}) or change guest's memory size in runtime (you still will not be able to change memory size, but can limit memory usage via inflating balloon driver) you will need to install guest balloon driver.<br />
<br />
For this you will need to go to ''Device Manager'', locate ''PCI standard RAM Controller'' in ''System devices'' (or unrecognized PCI controller from ''Other devices'') and choose ''Update driver''. In opened window you will need to choose ''Browse my computer...'' and select the CD-ROM (and do not forget the ''Include subdirectories'' checkbox). Reboot after installation. This will install the driver and you will be able to inflate the balloon (for example via hmp command {{ic|balloon ''memory_size''}}, which will cause balloon to take as much memory as possible in order to shrink the guest's available memory size to ''memory_size''). However, you still will not be able to track guest memory state. In order to do this you will need to install ''Balloon'' service properly. For that open command line as administrator, go to the CD-ROM, ''Balloon'' directory and deeper, depending on your system and architecture. Once you are in ''amd64'' (''x86'') directory, run {{ic|blnsrv.exe -i}} which will do the installation. After that {{ic|virsh}} command {{ic|dommemstat}} should be outputting all supported values.<br />
<br />
=== Preparing a FreeBSD guest ===<br />
<br />
Install the {{ic|emulators/virtio-kmod}} port if you are using FreeBSD 8.3 or later up until 10.0-CURRENT where they are included into the kernel. After installation, add the following to your {{ic|/boot/loader.conf}} file:<br />
<br />
{{bc|1=<br />
virtio_load="YES"<br />
virtio_pci_load="YES"<br />
virtio_blk_load="YES"<br />
if_vtnet_load="YES"<br />
virtio_balloon_load="YES"<br />
}}<br />
<br />
Then modify your {{ic|/etc/fstab}} by doing the following:<br />
<br />
# sed -ibak "s/ada/vtbd/g" /etc/fstab<br />
<br />
And verify that {{ic|/etc/fstab}} is consistent. If anything goes wrong, just boot into a rescue CD and copy {{ic|/etc/fstab.bak}} back to {{ic|/etc/fstab}}.<br />
<br />
== QEMU monitor ==<br />
<br />
While QEMU is running, a monitor console is provided in order to provide several ways to interact with the virtual machine running. The QEMU monitor offers interesting capabilities such as obtaining information about the current virtual machine, hotplugging devices, creating snapshots of the current state of the virtual machine, etc. To see the list of all commands, run {{ic|help}} or {{ic|?}} in the QEMU monitor console or review the relevant section of the [https://www.qemu.org/docs/master/system/monitor.html official QEMU documentation].<br />
<br />
=== Accessing the monitor console ===<br />
<br />
==== Graphical view ====<br />
<br />
When using the {{ic|std}} default graphics option, one can access the QEMU monitor by pressing {{ic|Ctrl+Alt+2}} or by clicking ''View > compatmonitor0'' in the QEMU window. To return to the virtual machine graphical view either press {{ic|Ctrl+Alt+1}} or click ''View > VGA''.<br />
<br />
However, the standard method of accessing the monitor is not always convenient and does not work in all graphic outputs QEMU supports.<br />
<br />
==== Telnet ====<br />
<br />
To enable [[telnet]], run QEMU with the {{ic|-monitor telnet:127.0.0.1:''port'',server,nowait}} parameter. When the virtual machine is started you will be able to access the monitor via telnet:<br />
<br />
$ telnet 127.0.0.1 ''port''<br />
<br />
{{Note|If {{ic|127.0.0.1}} is specified as the IP to listen it will be only possible to connect to the monitor from the same host QEMU is running on. If connecting from remote hosts is desired, QEMU must be told to listen {{ic|0.0.0.0}} as follows: {{ic|-monitor telnet:0.0.0.0:''port'',server,nowait}}. Keep in mind that it is recommended to have a [[firewall]] configured in this case or make sure your local network is completely trustworthy since this connection is completely unauthenticated and unencrypted.}}<br />
<br />
==== UNIX socket ====<br />
<br />
Run QEMU with the {{ic|-monitor unix:''socketfile'',server,nowait}} parameter. Then you can connect with either {{Pkg|socat}}, {{Pkg|nmap}} or {{Pkg|openbsd-netcat}}.<br />
<br />
For example, if QEMU is run via:<br />
<br />
$ qemu-system-x86_64 -monitor unix:/tmp/monitor.sock,server,nowait ''[...]''<br />
<br />
It is possible to connect to the monitor with:<br />
<br />
$ socat - UNIX-CONNECT:/tmp/monitor.sock<br />
<br />
Or with:<br />
<br />
$ nc -U /tmp/monitor.sock<br />
<br />
Alternatively with {{Pkg|nmap}}:<br />
<br />
$ ncat -U /tmp/monitor.sock<br />
<br />
==== TCP ====<br />
<br />
You can expose the monitor over TCP with the argument {{ic|-monitor tcp:127.0.0.1:''port'',server,nowait}}. Then connect with netcat, either {{Pkg|openbsd-netcat}} or {{Pkg|gnu-netcat}} by running:<br />
<br />
$ nc 127.0.0.1 ''port''<br />
<br />
{{Note|In order to be able to connect to the tcp socket from other devices other than the same host QEMU is being run on you need to listen to {{ic|0.0.0.0}} like explained in the telnet case. The same security warnings apply in this case as well.}}<br />
<br />
==== Standard I/O ====<br />
<br />
It is possible to access the monitor automatically from the same terminal QEMU is being run by running it with the argument {{ic|-monitor stdio}}.<br />
<br />
=== Sending keyboard presses to the virtual machine using the monitor console ===<br />
<br />
Some combinations of keys may be difficult to perform on virtual machines due to the host intercepting them instead in some configurations (a notable example is the {{ic|Ctrl+Alt+F*}} key combinations, which change the active tty). To avoid this problem, the problematic combination of keys may be sent via the monitor console instead. Switch to the monitor and use the {{ic|sendkey}} command to forward the necessary keypresses to the virtual machine. For example:<br />
<br />
(qemu) sendkey ctrl-alt-f2<br />
<br />
=== Creating and managing snapshots via the monitor console ===<br />
<br />
{{Note|This feature will '''only''' work when the virtual machine disk image is in ''qcow2'' format. It will not work with ''raw'' images.}}<br />
<br />
It is sometimes desirable to save the current state of a virtual machine and having the possibility of reverting the state of the virtual machine to that of a previously saved snapshot at any time. The QEMU monitor console provides the user with the necessary utilities to create snapshots, manage them, and revert the machine state to a saved snapshot.<br />
<br />
* Use {{ic|savevm ''name''}} in order to create a snapshot with the tag ''name''.<br />
* Use {{ic|loadvm ''name''}} to revert the virtual machine to the state of the snapshot ''name''.<br />
* Use {{ic|delvm ''name''}} to delete the snapshot tagged as ''name''.<br />
* Use {{ic|info snapshots}} to see a list of saved snapshots. Snapshots are identified by both an auto-incremented ID number and a text tag (set by the user on snapshot creation).<br />
<br />
=== Running the virtual machine in immutable mode ===<br />
<br />
It is possible to run a virtual machine in a frozen state so that all changes will be discarded when the virtual machine is powered off just by running QEMU with the {{ic|-snapshot}} parameter. When the disk image is written by the guest, changes will be saved in a temporary file in {{ic|/tmp}} and will be discarded when QEMU halts.<br />
<br />
However, if a machine is running in frozen mode it is still possible to save the changes to the disk image if it is afterwards desired by using the monitor console and running the following command:<br />
<br />
(qemu) commit all<br />
<br />
If snapshots are created when running in frozen mode they will be discarded as soon as QEMU is exited unless changes are explicitly commited to disk, as well.<br />
<br />
=== Pause and power options via the monitor console ===<br />
<br />
Some operations of a physical machine can be emulated by QEMU using some monitor commands:<br />
<br />
* {{ic|system_powerdown}} will send an ACPI shutdown request to the virtual machine. This effect is similar to the power button in a physical machine.<br />
* {{ic|system_reset}} will reset the virtual machine similarly to a reset button in a physical machine. This operation can cause data loss and file system corruption since the virtual machine is not cleanly restarted.<br />
* {{ic|stop}} will pause the virtual machine.<br />
* {{ic|cont}} will resume a virtual machine previously paused.<br />
<br />
=== Taking screenshots of the virtual machine ===<br />
<br />
Screenshots of the virtual machine graphic display can be obtained in the PPM format by running the following command in the monitor console:<br />
<br />
(qemu) screendump ''file.ppm''<br />
<br />
== QEMU machine protocol ==<br />
<br />
The QEMU machine protocol (QMP) is a JSON-based protocol which allows applications to control a QEMU instance. Similarly to the [[#QEMU monitor]] it offers ways to interact with a running machine and the JSON protocol allows to do it programmatically. The description of all the QMP commands can be found in [https://raw.githubusercontent.com/coreos/qemu/master/qmp-commands.hx qmp-commands].<br />
<br />
=== Start QMP ===<br />
<br />
The usual way to control the guest using the QMP protocol, is to open a TCP socket when launching the machine using the {{ic|-qmp}} option. Here it is using for example the TCP port 4444:<br />
<br />
$ qemu-system-x86_64 ''[...]'' -qmp tcp:localhost:4444,server,nowait<br />
<br />
Then one way to communicate with the QMP agent is to use [[netcat]]:<br />
<br />
{{hc|nc localhost 4444|{"QMP": {"version": {"qemu": {"micro": 0, "minor": 1, "major": 3}, "package": ""}, "capabilities": []} } }}<br />
<br />
At this stage, the only command that can be recognized is {{ic|qmp_capabilities}}, so that QMP enters into command mode. Type:<br />
<br />
{"execute": "qmp_capabilities"}<br />
<br />
Now, QMP is ready to receive commands, to retrieve the list of recognized commands, use:<br />
<br />
{"execute": "query-commands"}<br />
<br />
=== Live merging of child image into parent image ===<br />
<br />
It is possible to merge a running snapshot into its parent by issuing a {{ic|block-commit}} command. In its simplest form the following line will commit the child into its parent:<br />
<br />
{"execute": "block-commit", "arguments": {"device": "''devicename''"}}<br />
<br />
Upon reception of this command, the handler looks for the base image and converts it from read only to read write mode and then runs the commit job.<br />
<br />
Once the ''block-commit'' operation has completed, the event {{ic|BLOCK_JOB_READY}} will be emitted, signalling that the synchronization has finished. The job can then be gracefully completed by issuing the command {{ic|block-job-complete}}:<br />
<br />
{"execute": "block-job-complete", "arguments": {"device": "''devicename''"}}<br />
<br />
Until such a command is issued, the ''commit'' operation remains active.<br />
After successful completion, the base image remains in read write mode and becomes the new active layer. On the other hand, the child image becomes invalid and it is the responsibility of the user to clean it up.<br />
<br />
{{Tip|The list of device and their names can be retrieved by executing the command {{ic|query-block}} and parsing the results. The device name is in the {{ic|device}} field, for example {{ic|ide0-hd0}} for the hard disk in this example: {{hc|{"execute": "query-block"}|{"return": [{"io-status": "ok", "device": "'''ide0-hd0'''", "locked": false, "removable": false, "inserted": {"iops_rd": 0, "detect_zeroes": "off", "image": {"backing-image": {"virtual-size": 27074281472, "filename": "parent.qcow2", ... } }} }}<br />
<br />
=== Live creation of a new snapshot ===<br />
<br />
To create a new snapshot out of a running image, run the command:<br />
<br />
{"execute": "blockdev-snapshot-sync", "arguments": {"device": "''devicename''","snapshot-file": "''new_snapshot_name''.qcow2"}}<br />
<br />
This creates an overlay file named {{ic|''new_snapshot_name''.qcow2}} which then becomes the new active layer.<br />
<br />
== Tips and tricks ==<br />
<br />
=== Improve virtual machine performance ===<br />
<br />
There are a number of techniques that you can use to improve the performance of the virtual machine. For example:<br />
<br />
* Apply [[#Enabling KVM]] for full virtualization.<br />
* Use the {{ic|-cpu host}} option to make QEMU emulate the host's exact CPU rather than a more generic CPU.<br />
* Especially for Windows guests, enable [https://blog.wikichoon.com/2014/07/enabling-hyper-v-enlightenments-with-kvm.html Hyper-V enlightenments]: {{ic|1=-cpu host,hv_relaxed,hv_spinlocks=0x1fff,hv_vapic,hv_time}}. See the [https://www.qemu.org/docs/master/system/i386/hyperv.html QEMU documentation] for more information and flags.<br />
* multiple cores can be assigned to the guest using the {{ic|-smp cores{{=}}x,threads{{=}}y,sockets{{=}}1,maxcpus{{=}}z}} option. The threads parameter is used to assign [https://www.tomshardware.com/reviews/simultaneous-multithreading-definition,5762.html SMT cores]. Leaving a physical core for QEMU, the hypervisor and the host system to operate unimpeded is highly beneficial.<br />
* Make sure you have assigned the virtual machine enough memory. By default, QEMU only assigns 128 MiB of memory to each virtual machine. Use the {{ic|-m}} option to assign more memory. For example, {{ic|-m 1024}} runs a virtual machine with 1024 MiB of memory.<br />
* If supported by drivers in the guest operating system, use virtio for network and/or block devices, see [[#Installing virtio drivers]].<br />
* Use TAP devices instead of user-mode networking, see [[#Tap networking with QEMU]].<br />
* If the guest OS is doing heavy writing to its disk, you may benefit from certain mount options on the host's file system. For example, you can mount an [[Ext4|ext4 file system]] with the option {{ic|1=barrier=0}}. You should read the documentation for any options that you change because sometimes performance-enhancing options for file systems come at the cost of data integrity.<br />
* If you have a raw disk or partition, you may want to disable the cache: {{bc|1=$ qemu-system-x86_64 -drive file=/dev/''disk'',if=virtio,'''cache=none'''}}<br />
* Use the native Linux AIO: {{bc|1=$ qemu-system-x86_64 -drive file=''disk_image'',if=virtio''',aio=native,cache.direct=on'''}}<br />
* If you are running multiple virtual machines concurrently that all have the same operating system installed, you can save memory by enabling [[wikipedia:Kernel_SamePage_Merging_(KSM)|kernel same-page merging]]. See [[#Enabling KSM]].<br />
* In some cases, memory can be reclaimed from running virtual machines by running a memory ballooning driver in the guest operating system and launching QEMU using {{ic|-device virtio-balloon}}.<br />
* It is possible to use a emulation layer for an ICH-9 AHCI controller (although it may be unstable). The AHCI emulation supports [[Wikipedia:Native_Command_Queuing|NCQ]], so multiple read or write requests can be outstanding at the same time: {{bc|1=$ qemu-system-x86_64 -drive id=disk,file=''disk_image'',if=none -device ich9-ahci,id=ahci -device ide-drive,drive=disk,bus=ahci.0}}<br />
<br />
See https://www.linux-kvm.org/page/Tuning_KVM for more information.<br />
<br />
=== Starting QEMU virtual machines on boot ===<br />
<br />
==== With libvirt ====<br />
<br />
If a virtual machine is set up with [[libvirt]], it can be configured with {{ic|virsh autostart}} or through the ''virt-manager'' GUI to start at host boot by going to the Boot Options for the virtual machine and selecting "Start virtual machine on host boot up".<br />
<br />
==== With systemd service ====<br />
<br />
To run QEMU virtual machines on boot, you can use following systemd unit and config.<br />
<br />
{{hc|/etc/systemd/system/qemu@.service|2=<br />
[Unit]<br />
Description=QEMU virtual machine<br />
<br />
[Service]<br />
Environment="haltcmd=kill -INT $MAINPID"<br />
EnvironmentFile=/etc/conf.d/qemu.d/%i<br />
ExecStart=/usr/bin/qemu-system-x86_64 -name %i -enable-kvm -m 512 -nographic $args<br />
ExecStop=/usr/bin/bash -c ${haltcmd}<br />
ExecStop=/usr/bin/bash -c 'while nc localhost 7100; do sleep 1; done'<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
}}<br />
<br />
{{Note|This service will wait for the console port to be released, which means that the virtual machine has been shutdown, to graciously end.}}<br />
<br />
Then create per-VM configuration files, named {{ic|/etc/conf.d/qemu.d/''vm_name''}}, with the variables {{ic|args}} and {{ic|haltcmd}} set. Example configs:<br />
<br />
{{hc|/etc/conf.d/qemu.d/one|2=<br />
args="-hda /dev/vg0/vm1 -serial telnet:localhost:7000,server,nowait,nodelay \<br />
-monitor telnet:localhost:7100,server,nowait,nodelay -vnc :0"<br />
<br />
haltcmd="echo 'system_powerdown' {{!}} nc localhost 7100" # or netcat/ncat}}<br />
<br />
{{hc|/etc/conf.d/qemu.d/two|2=<br />
args="-hda /srv/kvm/vm2 -serial telnet:localhost:7001,server,nowait,nodelay -vnc :1"<br />
<br />
haltcmd="ssh powermanager@vm2 sudo poweroff"}}<br />
<br />
The description of the variables is the following:<br />
<br />
* {{ic|args}} - QEMU command line arguments to be used.<br />
* {{ic|haltcmd}} - Command to shut down a virtual machine safely. In the first example, the QEMU monitor is exposed via telnet using {{ic|-monitor telnet:..}} and the virtual machines are powered off via ACPI by sending {{ic|system_powerdown}} to monitor with the {{ic|nc}} command. In the other example, SSH is used.<br />
<br />
To set which virtual machines will start on boot-up, [[enable]] the {{ic|qemu@''vm_name''.service}} systemd unit.<br />
<br />
=== Mouse integration ===<br />
<br />
To prevent the mouse from being grabbed when clicking on the guest operating system's window, add the options {{ic|-usb -device usb-tablet}}. This means QEMU is able to report the mouse position without having to grab the mouse. This also overrides PS/2 mouse emulation when activated. For example:<br />
<br />
$ qemu-system-x86_64 -hda ''disk_image'' -m 512 -usb -device usb-tablet<br />
<br />
If that does not work, try using {{ic|-vga qxl}} parameter, also look at the instructions [[#Mouse cursor is jittery or erratic]].<br />
<br />
=== Pass-through host USB device ===<br />
<br />
It is possible to access the physical device connected to a USB port of the host from the guest. The first step is to identify where the device is connected, this can be found running the {{ic|lsusb}} command. For example:<br />
<br />
{{hc|$ lsusb|<br />
...<br />
Bus '''003''' Device '''007''': ID '''0781''':'''5406''' SanDisk Corp. Cruzer Micro U3<br />
}}<br />
<br />
The outputs in bold above will be useful to identify respectively the ''host_bus'' and ''host_addr'' or the ''vendor_id'' and ''product_id''.<br />
<br />
In qemu, the idea is to emulate an EHCI (USB 2) or XHCI (USB 1.1 USB 2 USB 3) controller with the option {{ic|1=-device usb-ehci,id=ehci}} or {{ic|1=-device qemu-xhci,id=xhci}} respectively and then attach the physical device to it with the option {{ic|1=-device usb-host,..}}. We will consider that ''controller_id'' is either {{ic|ehci}} or {{ic|xhci}} for the rest of this section.<br />
<br />
Then, there are two ways to connect to the USB of the host with qemu:<br />
<br />
# Identify the device and connect to it on any bus and address it is attached to on the host, the generic syntax is: {{bc|1=-device usb-host,bus=''controller_id''.0,vendorid=0x''vendor_id'',productid=0x''product_id''}}Applied to the device used in the example above, it becomes:{{bc|1=-device usb-ehci,id=ehci -device usb-host,bus=ehci.0,vendorid=0x'''0781''',productid=0x'''5406'''}}One can also add the {{ic|1=...,port=''port_number''}} setting to the previous option to specify in which physical port of the virtual controller the device should be attached, useful in the case one wants to add multiple USB devices to the virtual machine. Another option is to use the new {{ic|hostdevice}} property of {{ic|usb-host}} which is available since QEMU 5.1.0, the syntax is: {{bc|1=-device qemu-xhci,id=xhci -device usb-host,hostdevice=/dev/bus/usb/003/007}}<br />
# Attach whatever is connected to a given USB bus and address, the syntax is:{{bc|1=-device usb-host,bus=''controller_id''.0,hostbus=''host_bus'',host_addr=''host_addr''}}Applied to the bus and the address in the example above, it becomes:{{bc|1=-device usb-ehci,id=ehci -device usb-host,bus=ehci.0,hostbus='''3''',hostaddr='''7'''}}<br />
See [https://www.qemu.org/docs/master/system/devices/usb.html QEMU/USB emulation] for more information.<br />
{{Note|If you encounter permission errors when running QEMU, see [[udev#About udev rules]] for information on how to set permissions of the device.}}<br />
<br />
=== USB redirection with SPICE ===<br />
<br />
When using [[#SPICE]] it is possible to redirect USB devices from the client to the virtual machine without needing to specify them in the QEMU command. It is possible to configure the number of USB slots available for redirected devices (the number of slots will determine the maximum number of devices which can be redirected simultaneously). The main advantages of using SPICE for redirection compared to the previously-mentioned {{ic|-usbdevice}} method is the possibility of hot-swapping USB devices after the virtual machine has started, without needing to halt it in order to remove USB devices from the redirection or adding new ones. This method of USB redirection also allows us to redirect USB devices over the network, from the client to the server. In summary, it is the most flexible method of using USB devices in a QEMU virtual machine.<br />
<br />
We need to add one EHCI/UHCI controller per available USB redirection slot desired as well as one SPICE redirection channel per slot. For example, adding the following arguments to the QEMU command you use for starting the virtual machine in SPICE mode will start the virtual machine with three available USB slots for redirection:<br />
<br />
{{bc|1=<br />
-device ich9-usb-ehci1,id=usb \<br />
-device ich9-usb-uhci1,masterbus=usb.0,firstport=0,multifunction=on \<br />
-device ich9-usb-uhci2,masterbus=usb.0,firstport=2 \<br />
-device ich9-usb-uhci3,masterbus=usb.0,firstport=4 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev1 -device usb-redir,chardev=usbredirchardev1,id=usbredirdev1 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev2 -device usb-redir,chardev=usbredirchardev2,id=usbredirdev2 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev3 -device usb-redir,chardev=usbredirchardev3,id=usbredirdev3<br />
}}<br />
<br />
See [https://www.spice-space.org/usbredir.html SPICE/usbredir] for more information.<br />
<br />
Both {{ic|spicy}} from {{Pkg|spice-gtk}} (''Input > Select USB Devices for redirection'') and {{ic|remote-viewer}} from {{Pkg|virt-viewer}} (''File > USB device selection'') support this feature. Please make sure that you have installed the necessary SPICE Guest Tools on the virtual machine for this functionality to work as expected (see the [[#SPICE]] section for more information).<br />
<br />
{{Warning|Keep in mind that when a USB device is redirected from the client, it will not be usable from the client operating system itself until the redirection is stopped. It is specially important to never redirect the input devices (namely mouse and keyboard), since it will be then difficult to access the SPICE client menus to revert the situation, because the client will not respond to the input devices after being redirected to the virtual machine.}}<br />
<br />
==== Automatic USB forwarding with udev ====<br />
<br />
Normally, forwarded devices must be available at the boot time of the virtual machine to be forwarded. If that device is disconnected, it will not be forwarded anymore.<br />
<br />
You can use [[udev rule]]s to automatically attach a device when it comes online. Create a {{ic|hostdev}} entry somewhere on disk. [[chown]] it to root to prevent other users modifying it.<br />
<br />
{{hc|/usr/local/hostdev-mydevice.xml|2=<br />
<hostdev mode='subsystem' type='usb'><br />
<source><br />
<vendor id='0x03f0'/><br />
<product id='0x4217'/><br />
</source><br />
</hostdev><br />
}}<br />
<br />
Then create a ''udev'' rule which will attach/detach the device:<br />
<br />
{{hc|/usr/lib/udev/rules.d/90-libvirt-mydevice|2=<br />
ACTION=="add", \<br />
SUBSYSTEM=="usb", \<br />
ENV{ID_VENDOR_ID}=="03f0", \<br />
ENV{ID_MODEL_ID}=="4217", \<br />
RUN+="/usr/bin/virsh attach-device GUESTNAME /usr/local/hostdev-mydevice.xml"<br />
ACTION=="remove", \<br />
SUBSYSTEM=="usb", \<br />
ENV{ID_VENDOR_ID}=="03f0", \<br />
ENV{ID_MODEL_ID}=="4217", \<br />
RUN+="/usr/bin/virsh detach-device GUESTNAME /usr/local/hostdev-mydevice.xml"<br />
}}<br />
<br />
[https://rolandtapken.de/blog/2011-04/how-auto-hotplug-usb-devices-libvirt-vms-update-1 Source and further reading].<br />
<br />
=== Enabling KSM ===<br />
<br />
Kernel Samepage Merging (KSM) is a feature of the Linux kernel that allows for an application to register with the kernel to have its pages merged with other processes that also register to have their pages merged. The KSM mechanism allows for guest virtual machines to share pages with each other. In an environment where many of the guest operating systems are similar, this can result in significant memory savings.<br />
<br />
{{Note|Although KSM may reduce memory usage, it may increase CPU usage. Also note some security issues may occur, see [[Wikipedia:Kernel same-page merging]].}}<br />
<br />
To enable KSM:<br />
<br />
# echo 1 > /sys/kernel/mm/ksm/run<br />
<br />
To make it permanent, use [[systemd#systemd-tmpfiles - temporary files|systemd's temporary files]]:<br />
<br />
{{hc|/etc/tmpfiles.d/ksm.conf|<br />
w /sys/kernel/mm/ksm/run - - - - 1<br />
}}<br />
<br />
If KSM is running, and there are pages to be merged (i.e. at least two similar virtual machines are running), then {{ic|/sys/kernel/mm/ksm/pages_shared}} should be non-zero. See https://docs.kernel.org/admin-guide/mm/ksm.html for more information.<br />
<br />
{{Tip|An easy way to see how well KSM is performing is to simply print the contents of all the files in that directory:<br />
<br />
$ grep -r . /sys/kernel/mm/ksm/<br />
<br />
}}<br />
<br />
=== Multi-monitor support ===<br />
<br />
The Linux QXL driver supports four heads (virtual screens) by default. This can be changed via the {{ic|1=qxl.heads=N}} kernel parameter.<br />
<br />
The default VGA memory size for QXL devices is 16M (VRAM size is 64M). This is not sufficient if you would like to enable two 1920x1200 monitors since that requires 2 × 1920 × 4 (color depth) × 1200 = 17.6 MiB VGA memory. This can be changed by replacing {{ic|-vga qxl}} by {{ic|<nowiki>-vga none -device qxl-vga,vgamem_mb=32</nowiki>}}. If you ever increase vgamem_mb beyond 64M, then you also have to increase the {{ic|vram_size_mb}} option.<br />
<br />
=== Custom display resolution ===<br />
<br />
A custom display resolution can be set with {{ic|1=-device VGA,edid=on,xres=1280,yres=720}} (see [[wikipedia:Extended_Display_Identification_Data|EDID]] and [[wikipedia:Display_resolution|display resolution]]).<br />
<br />
=== Copy and paste ===<br />
<br />
==== SPICE ====<br />
<br />
One way to share the clipboard between the host and the guest is to enable the SPICE remote desktop protocol and access the client with a SPICE client.<br />
One needs to follow the steps described in [[#SPICE]]. A guest run this way will support copy paste with the host.<br />
<br />
==== qemu-vdagent ====<br />
<br />
QEMU provides its own implementation of the spice vdagent chardev called {{ic|qemu-vdagent}}. It interfaces with the spice-vdagent guest service and allows the guest and host share a clipboard.<br />
<br />
To access this shared clipboard with QEMU's GTK display, you will need to [[#Custom build|compile QEMU from source]] with the {{ic|--enable-gtk-clipboard}} configure parameter. It is sufficient to replace the installed {{ic|qemu-ui-gtk}} package.<br />
<br />
{{Note|<br />
* Feature request {{Bug|79716}} submitted to enable the functionality in the official package.<br />
* The shared clipboard in qemu-ui-gtk has been pushed back to experimental as it can [https://gitlab.com/qemu-project/qemu/-/issues/1150 freeze guests under certain circumstances]. A fix has been proposed to solve the issue upstream.<br />
}}<br />
<br />
Add the following QEMU command line arguments:<br />
<br />
-device virtio-serial,packed=on,ioeventfd=on<br />
-device virtserialport,name=com.redhat.spice.0,chardev=vdagent0<br />
-chardev qemu-vdagent,id=vdagent0,name=vdagent,clipboard=on,mouse=off<br />
<br />
These arguments are also valid if converted to [[Libvirt#QEMU command line arguments|libvirt form]].<br />
<br />
{{Note|While the spicevmc chardev will start the spice-vdagent service of the guest automatically, the qemu-vdagent chardev may not.}}<br />
<br />
On linux guests, you may [[start]] the {{ic|spice-vdagent.service}} [[user unit]] manually. On Windows guests, set the spice-agent startup type to automatic.<br />
<br />
=== Windows-specific notes ===<br />
<br />
QEMU can run any version of Windows from Windows 95 through Windows 11.<br />
<br />
It is possible to run [[Windows PE]] in QEMU.<br />
<br />
==== Fast startup ====<br />
<br />
{{Note|An administrator account is required to change power settings.}}<br />
<br />
For Windows 8 (or later) guests it is better to disable "Turn on fast startup (recommended)" from the Power Options of the Control Panel as explained in the following [https://www.tenforums.com/tutorials/4189-turn-off-fast-startup-windows-10-a.html forum page], as it causes the guest to hang during every other boot.<br />
<br />
Fast Startup may also need to be disabled for changes to the {{ic|-smp}} option to be properly applied.<br />
<br />
==== Remote Desktop Protocol ====<br />
<br />
If you use a MS Windows guest, you might want to use RDP to connect to your guest virtual machine. If you are using a VLAN or are not in the same network as the guest, use:<br />
<br />
$ qemu-system-x86_64 -nographic -nic user,hostfwd=tcp::5555-:3389<br />
<br />
Then connect with either {{Pkg|rdesktop}} or {{Pkg|freerdp}} to the guest. For example:<br />
<br />
$ xfreerdp -g 2048x1152 localhost:5555 -z -x lan<br />
<br />
=== Clone Linux system installed on physical equipment ===<br />
<br />
Linux system installed on physical equipment can be cloned for running on a QEMU virtual machine. See [https://coffeebirthday.wordpress.com/2018/09/14/clone-linux-system-for-qemu-virtual-machine/ Clone Linux system from hardware for QEMU virtual machine]<br />
<br />
=== Chrooting into arm/arm64 environment from x86_64 ===<br />
<br />
Sometimes it is easier to work directly on a disk image instead of the real ARM based device. This can be achieved by mounting an SD card/storage containing the ''root'' partition and chrooting into it.<br />
<br />
Another use case for an ARM chroot is building ARM packages on an x86_64 machine. Here, the chroot environment can be created from an image tarball from [https://archlinuxarm.org Arch Linux ARM] - see [https://nerdstuff.org/posts/2020/2020-003_simplest_way_to_create_an_arm_chroot/] for a detailed description of this approach.<br />
<br />
Either way, from the chroot it should be possible to run ''pacman'' and install more packages, compile large libraries etc. Since the executables are for the ARM architecture, the translation to x86 needs to be performed by [[QEMU]].<br />
<br />
Install {{Pkg|qemu-user-static}} on the x86_64 machine/host, and {{Pkg|qemu-user-static-binfmt}} to register the qemu binaries to binfmt service.<br />
<br />
''qemu-user-static'' is used to allow the execution of compiled programs from other architectures. This is similar to what is provided by {{Pkg|qemu-emulators-full}}, but the "static" variant is required for chroot. Examples:<br />
<br />
qemu-arm-static path_to_sdcard/usr/bin/ls<br />
qemu-aarch64-static path_to_sdcard/usr/bin/ls<br />
<br />
These two lines execute the {{ic|ls}} command compiled for 32-bit ARM and 64-bit ARM respectively. Note that this will not work without chrooting, because it will look for libraries not present in the host system.<br />
<br />
{{Pkg|qemu-user-static}} allows automatically prefixing the ARM exectuable with {{ic|qemu-arm-static}} or {{ic|qemu-aarch64-static}}.<br />
<br />
Make sure that the ARM executable support is active:<br />
<br />
{{hc|$ ls /proc/sys/fs/binfmt_misc|<br />
qemu-aarch64 qemu-arm qemu-cris qemu-microblaze qemu-mipsel qemu-ppc64 qemu-riscv64 qemu-sh4 qemu-sparc qemu-sparc64 status<br />
qemu-alpha qemu-armeb qemu-m68k qemu-mips qemu-ppc qemu-ppc64abi32 qemu-s390x qemu-sh4eb qemu-sparc32plus register<br />
}}<br />
<br />
Each executable must be listed.<br />
<br />
If it is not active, [[restart]] {{ic|systemd-binfmt.service}}.<br />
<br />
Mount the SD card to {{ic|/mnt/sdcard}} (the device name may be different).<br />
<br />
# mount --mkdir /dev/mmcblk0p2 /mnt/sdcard<br />
<br />
Mount boot partition if needed (again, use the suitable device name):<br />
<br />
# mount /dev/mmcblk0p1 /mnt/sdcard/boot<br />
<br />
Finally ''chroot'' into the SD card root as described in [[Change root#Using chroot]]:<br />
<br />
# chroot /mnt/sdcard /bin/bash<br />
<br />
Alternatively, you can use ''arch-chroot'' from {{Pkg|arch-install-scripts}}, as it will provide an easier way to get network support:<br />
<br />
# arch-chroot /mnt/sdcard /bin/bash<br />
<br />
You can also use [[systemd-nspawn]] to chroot into the ARM environment:<br />
<br />
# systemd-nspawn -D /mnt/sdcard -M myARMMachine --bind-ro=/etc/resolv.conf<br />
<br />
{{ic|1=--bind-ro=/etc/resolv.conf}} is optional and gives a working network DNS inside the chroot<br />
<br />
==== sudo in chroot ====<br />
<br />
If you install [[sudo]] in the chroot and receive the following error when trying to use it:<br />
<br />
sudo: effective uid is not 0, is /usr/bin/sudo on a file system with the 'nosuid' option set or an NFS file system without root privileges?<br />
<br />
then you may need to modify the binfmt flags, for example for {{ic|aarch64}}:<br />
<br />
# cp /usr/lib/binfmt.d/qemu-aarch64-static.conf /etc/binfmt.d/<br />
# vi /etc/binfmt.d/qemu-aarch64-static.conf<br />
<br />
and add a {{ic|C}} at the end of this file:<br />
<br />
:qemu-aarch64:M::\x7fELF\x02\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\xb7\x00:\xff\xff\xff\xff\xff\xff\xff\x00\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff\xff:/usr/bin/qemu-aarch64-static:FPC<br />
<br />
Then [[restart]] {{ic|systemd-binfmt.service}} and check that the changes have taken effect (note the {{ic|C}} on the {{ic|flags}} line):<br />
<br />
{{hc|# cat /proc/sys/fs/binfmt_misc/qemu-aarch64|<br />
enabled<br />
interpreter /usr/bin/qemu-aarch64-static<br />
flags: POCF<br />
offset 0<br />
magic 7f454c460201010000000000000000000200b700<br />
mask ffffffffffffff00fffffffffffffffffeffffff<br />
}}<br />
<br />
See the "flags" section of the [https://docs.kernel.org/admin-guide/binfmt-misc.html kernel binfmt documentation] for more information.<br />
<br />
=== Not grabbing mouse input ===<br />
<br />
{{Style|It is not explained what the option actually does. Is it causing or avoiding the side effect?}}<br />
<br />
Tablet mode has side effect of not grabbing mouse input in QEMU window:<br />
<br />
-usb -device usb-tablet<br />
<br />
It works with several {{ic|-vga}} backends one of which is virtio.<br />
<br />
== Troubleshooting ==<br />
<br />
{{Merge|QEMU/Troubleshooting|This section is long enough to be split into a dedicated subpage.}}<br />
<br />
=== Mouse cursor is jittery or erratic ===<br />
<br />
If the cursor jumps around the screen uncontrollably, entering this on the terminal before starting QEMU might help:<br />
<br />
$ export SDL_VIDEO_X11_DGAMOUSE=0<br />
<br />
If this helps, you can add this to your {{ic|~/.bashrc}} file.<br />
<br />
=== No visible Cursor ===<br />
<br />
Add {{ic|1=-display default,show-cursor=on}} to QEMU's options to see a mouse cursor.<br />
<br />
If that still does not work, make sure you have set your display device appropriately, for example: {{ic|-vga qxl}}.<br />
<br />
Another option to try is {{ic|-usb -device usb-tablet}} as mentioned in [[#Mouse integration]]. This overrides the default PS/2 mouse emulation and synchronizes pointer location between host and guest as an added bonus.<br />
<br />
=== Two different mouse cursors are visible ===<br />
<br />
Apply the tip [[#Mouse integration]].<br />
<br />
=== Keyboard issues when using VNC ===<br />
<br />
When using VNC, you might experience keyboard problems described (in gory details) [https://www.berrange.com/posts/2010/07/04/more-than-you-or-i-ever-wanted-to-know-about-virtual-keyboard-handling/ here]. The solution is ''not'' to use the {{ic|-k}} option on QEMU, and to use {{ic|gvncviewer}} from {{Pkg|gtk-vnc}}. See also [https://www.mail-archive.com/libvir-list@redhat.com/msg13340.html this] message posted on libvirt's mailing list.<br />
<br />
=== Keyboard seems broken or the arrow keys do not work ===<br />
<br />
Should you find that some of your keys do not work or "press" the wrong key (in particular, the arrow keys), you likely need to specify your keyboard layout as an option. The keyboard layouts can be found in {{ic|/usr/share/qemu/keymaps/}}.<br />
<br />
$ qemu-system-x86_64 -k ''keymap'' ''disk_image''<br />
<br />
=== Could not read keymap file ===<br />
<br />
qemu-system-x86_64: -display vnc=0.0.0.0:0: could not read keymap file: 'en'<br />
<br />
is caused by an invalid ''keymap'' passed to the {{ic|-k}} argument. For example, {{ic|en}} is invalid, but {{ic|en-us}} is valid - see {{ic|/usr/share/qemu/keymaps/}}.<br />
<br />
=== Guest display stretches on window resize ===<br />
<br />
To restore default window size, press {{ic|Ctrl+Alt+u}}.<br />
<br />
=== ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy ===<br />
<br />
If an error message like this is printed when starting QEMU with {{ic|-enable-kvm}} option:<br />
<br />
ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy<br />
failed to initialize KVM: Device or resource busy<br />
<br />
that means another [[hypervisor]] is currently running. It is not recommended or possible to run several hypervisors in parallel.<br />
<br />
=== libgfapi error message ===<br />
<br />
The error message displayed at startup:<br />
<br />
Failed to open module: libgfapi.so.0: cannot open shared object file: No such file or directory<br />
<br />
[[Install]] {{Pkg|glusterfs}} or ignore the error message as GlusterFS is a optional dependency.<br />
<br />
=== Kernel panic on LIVE-environments ===<br />
<br />
If you start a live-environment (or better: booting a system) you may encounter this:<br />
<br />
[ end Kernel panic - not syncing: VFS: Unable to mount root fs on unknown block(0,0)<br />
<br />
or some other boot hindering process (e.g. cannot unpack initramfs, cant start service foo).<br />
Try starting the virtual machine with the {{ic|-m VALUE}} switch and an appropriate amount of RAM, if the ram is to low you will probably encounter similar issues as above/without the memory-switch.<br />
<br />
=== Windows 7 guest suffers low-quality sound ===<br />
<br />
Using the {{ic|hda}} audio driver for Windows 7 guest may result in low-quality sound. Changing the audio driver to {{ic|ac97}} by passing the {{ic|-soundhw ac97}} arguments to QEMU and installing the AC97 driver from [https://www.realtek.com/en/component/zoo/category/pc-audio-codecs-ac-97-audio-codecs-software Realtek AC'97 Audio Codecs] in the guest may solve the problem. See [https://bugzilla.redhat.com/show_bug.cgi?id=1176761#c16 Red Hat Bugzilla – Bug 1176761] for more information.<br />
<br />
=== Could not access KVM kernel module: Permission denied ===<br />
<br />
If you encounter the following error:<br />
<br />
libvirtError: internal error: process exited while connecting to monitor: Could not access KVM kernel module: Permission denied failed to initialize KVM: Permission denied<br />
<br />
Systemd 234 assigns a dynamic ID for the {{ic|kvm}} group (see {{Bug|54943}}). To avoid this error, you need edit the file {{ic|/etc/libvirt/qemu.conf}} and change the line with {{ic|1=group = "78"}} to {{ic|1=group = "kvm"}}.<br />
<br />
=== "System Thread Exception Not Handled" when booting a Windows virtual machine ===<br />
<br />
Windows 8 or Windows 10 guests may raise a generic compatibility exception at boot, namely "System Thread Exception Not Handled", which tends to be caused by legacy drivers acting strangely on real machines. On KVM machines this issue can generally be solved by setting the CPU model to {{ic|core2duo}}.<br />
<br />
=== Certain Windows games/applications crashing/causing a bluescreen ===<br />
<br />
Occasionally, applications running in the virtual machine may crash unexpectedly, whereas they would run normally on a physical machine. If, while running {{ic|dmesg -wH}} as root, you encounter an error mentioning {{ic|MSR}}, the reason for those crashes is that KVM injects a [[wikipedia:General protection fault|General protection fault]] (GPF) when the guest tries to access unsupported [[wikipedia:Model-specific register|Model-specific registers]] (MSRs) - this often results in guest applications/OS crashing. A number of those issues can be solved by passing the {{ic|1=ignore_msrs=1}} option to the KVM module, which will ignore unimplemented MSRs.<br />
<br />
{{hc|/etc/modprobe.d/kvm.conf|2=<br />
...<br />
options kvm ignore_msrs=1<br />
...<br />
}}<br />
<br />
Cases where adding this option might help:<br />
<br />
* GeForce Experience complaining about an unsupported CPU being present.<br />
* StarCraft 2 and L.A. Noire reliably blue-screening Windows 10 with {{ic|KMODE_EXCEPTION_NOT_HANDLED}}. The blue screen information does not identify a driver file in these cases.<br />
<br />
{{Warning|While this is normally safe and some applications might not work without this, silently ignoring unknown MSR accesses could potentially break other software within the virtual machine or other virtual machine.}}<br />
<br />
=== Applications in the virtual machine experience long delays or take a long time to start ===<br />
<br />
{{Out of date|No longer true since kernel 5.6}}<br />
<br />
This may be caused by insufficient available entropy in the virtual machine. Consider allowing the guest to access the hosts's entropy pool by adding a [https://wiki.qemu.org/Features/VirtIORNG VirtIO RNG device] to the virtual machine, or by installing an entropy generating daemon such as [[Haveged]].<br />
<br />
Anecdotally, OpenSSH takes a while to start accepting connections under insufficient entropy, without the logs revealing why.<br />
<br />
=== High interrupt latency and microstuttering ===<br />
<br />
This problem manifests itself as small pauses (stutters) and is particularly noticeable in graphics-intensive applications, such as games.<br />
<br />
* One of the causes is CPU power saving features, which are controlled by [[CPU frequency scaling]]. Change this to {{ic|performance}} for all processor cores. <br />
* Another possible cause is PS/2 inputs. Switch from PS/2 to Virtio inputs, see [[PCI passthrough via OVMF#Passing keyboard/mouse via Evdev]].<br />
<br />
=== QXL video causes low resolution ===<br />
<br />
QEMU 4.1.0 introduced a regression where QXL video can fall back to low resolutions, when being displayed through spice. [https://bugs.launchpad.net/qemu/+bug/1843151] For example, when KMS starts, text resolution may become as low as 4x10 characters. When trying to increase GUI resolution, it may go to the lowest supported resolution.<br />
<br />
As a workaround, create your device in this form:<br />
<br />
-device qxl-vga,max_outputs=1...<br />
<br />
=== Virtual machine not booting when using a Secure Boot enabled OVMF ===<br />
<br />
{{ic|OVMF_CODE.secboot.4m.fd}} and {{ic|OVMF_CODE.secboot.fd}} files from {{Pkg|edk2-ovmf}} are built with [[Wikipedia:System Management Mode|SMM]] support. If S3 support is not disabled in the virtual machine, then the virtual machine might not boot at all.<br />
<br />
Add the {{ic|1=-global ICH9-LPC.disable_s3=1}} option to the ''qemu'' command.<br />
<br />
See {{Bug|59465}} and https://github.com/tianocore/edk2/blob/master/OvmfPkg/README for more details and the required options to use Secure Boot in QEMU.<br />
<br />
=== Virtual machine not booting into Arch ISO ===<br />
<br />
When trying to boot the virtual machine for the first time from an Arch ISO image, the boot process hangs. Adding {{ic|1=console=ttyS0}} to kernel boot options by pressing {{ic|e}} in the boot menu you will get more boot messages and the following error:<br />
<br />
:: Mounting '/dev/disk/by-label/ARCH_202204' to '/run/archiso/bootmnt'<br />
Waiting 30 seconds for device /dev/disk/by-label/ARCH_202204 ...<br />
ERROR: '/dev/disk/by-label/ARCH_202204' device did not show up after 30 seconds...<br />
Falling back to interactive prompt<br />
You can try to fix the problem manually, log out when you are finished<br />
sh: can't access tty; job control turned off<br />
<br />
The error message does not give a good clue as to what the real issue is. The problem is with the default 128MB of RAM that QEMU allocates to the virtual machine. Increasing the limit to 1024MB with {{ic|-m 1024}} solves the issue and lets the system boot. You can continue installing Arch Linux as usual after that. Once the installation is complete, the memory allocation for the virtual machine can be decreased. The need for 1024MB is due to RAM disk requirements and size of the installation media. See [https://lists.archlinux.org/archives/list/arch-releng@lists.archlinux.org/message/D5HSGOFTPGYI6IZUEB3ZNAX4D3F3ID37/ this message on the arch-releng mailing list] and [https://bbs.archlinux.org/viewtopic.php?id=204023 this forum thread].<br />
<br />
=== Guest CPU interrupts are not firing ===<br />
<br />
If you are writing your own operating system by following the [https://wiki.osdev.org/ OSDev wiki], or are simply getting stepping through the guest architecture assembly code using QEMU's {{ic|gdb}} interface using the {{ic|-s}} flag, it is useful to know that many emulators, QEMU included, usually implement some CPU interrupts leaving many hardware interrupts unimplemented. One way to know if your code is firing an interrupt, is by using:<br />
<br />
-d int<br />
<br />
to enable showing interrupts/exceptions on stdout.<br />
<br />
To see what other guest debugging features QEMU has to offer, see:<br />
<br />
qemu-system-x86_64 -d help<br />
<br />
or replace {{ic|x86_64}} for your chosen guest architecture.<br />
<br />
=== KDE with sddm does not start spice-vdagent at login automatically ===<br />
<br />
Remove or comment out {{ic|X-GNOME-Autostart-Phase{{=}}WindowManager}} from {{ic|/etc/xdg/autostart/spice-vdagent.desktop}}. [https://github.com/systemd/systemd/issues/18791]<br />
<br />
=== Error starting domain: Requested operation is not valid: network 'default' is not active ===<br />
<br />
If for any reason the default network is deactivated, you will not be able to start any guest virtual machines which are configured to use the network. Your first attempt can be simply trying to start the network with virsh.<br />
<br />
# virsh net-start default<br />
<br />
For additional troubleshooting steps, see [https://www.xmodulo.com/network-default-is-not-active.html].<br />
<br />
== See also ==<br />
<br />
* [https://qemu.org Official QEMU website]<br />
* [https://www.linux-kvm.org Official KVM website]<br />
* [https://qemu.weilnetz.de/doc/6.0/ QEMU Emulator User Documentation]<br />
* [[Wikibooks:QEMU|QEMU Wikibook]]<br />
* [http://alien.slackbook.org/dokuwiki/doku.php?id=slackware:qemu Hardware virtualization with QEMU] by AlienBOB (last updated in 2008)<br />
* [http://blog.falconindy.com/articles/build-a-virtual-army.html Building a Virtual Army] by Falconindy<br />
* [https://git.qemu.org/?p=qemu.git;a=tree;f=docs Lastest docs]<br />
* [https://qemu.weilnetz.de/ QEMU on Windows]<br />
* [[wikipedia:Qemu|Wikipedia]]<br />
* [[debian:QEMU|Debian Wiki - QEMU]]<br />
* [https://people.gnome.org/~markmc/qemu-networking.html QEMU Networking on gnome.org]{{Dead link|2022|09|22|status=404}}<br />
* [http://bsdwiki.reedmedia.net/wiki/networking_qemu_virtual_bsd_systems.html Networking QEMU Virtual BSD Systems]<br />
* [https://www.gnu.org/software/hurd/hurd/running/qemu.html QEMU on gnu.org]<br />
* [https://wiki.freebsd.org/qemu QEMU on FreeBSD as host]<br />
* [https://wiki.mikejung.biz/KVM_/_Xen KVM/QEMU Virtio Tuning and SSD VM Optimization Guide]{{Dead link|2022|09|22|status=404}}<br />
* [https://doc.opensuse.org/documentation/leap/virtualization/html/book-virt/part-virt-qemu.html Managing Virtual Machines with QEMU - openSUSE documentation]<br />
* [https://www.ibm.com/support/knowledgecenter/en/linuxonibm/liaat/liaatkvm.htm KVM on IBM Knowledge Center]</div>Malcontenthttps://wiki.archlinux.org/index.php?title=QEMU&diff=795920QEMU2024-01-03T13:09:50Z<p>Malcontent: Add VirtIO sound example (QEMU 8.2.0)</p>
<hr />
<div>[[Category:Emulation]]<br />
[[Category:Hypervisors]]<br />
[[de:QEMU]]<br />
[[es:QEMU]]<br />
[[fr:QEMU]]<br />
[[ja:QEMU]]<br />
[[zh-hans:QEMU]]<br />
{{Related articles start}}<br />
{{Related|:Category:Hypervisors}}<br />
{{Related|Libvirt}}<br />
{{Related|QEMU/Guest graphics acceleration}}<br />
{{Related|PCI passthrough via OVMF}}<br />
{{Related articles end}}<br />
<br />
According to the [https://wiki.qemu.org/Main_Page QEMU about page], "QEMU is a generic and open source machine emulator and virtualizer."<br />
<br />
When used as a machine emulator, QEMU can run OSes and programs made for one machine (e.g. an ARM board) on a different machine (e.g. your x86 PC). By using dynamic translation, it achieves very good performance.<br />
<br />
QEMU can use other hypervisors like [[Xen]] or [[KVM]] to use CPU extensions ([[Wikipedia:Hardware-assisted virtualization|HVM]]) for virtualization. When used as a virtualizer, QEMU achieves near native performances by executing the guest code directly on the host CPU.<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|qemu-full}} package (or {{Pkg|qemu-base}} for the version without GUI) and below optional packages for your needs:<br />
<br />
* {{Pkg|qemu-block-gluster}} - [[Glusterfs]] block support<br />
* {{Pkg|qemu-block-iscsi}} - [[iSCSI]] block support<br />
* {{Pkg|samba}} - [[Samba|SMB/CIFS]] server support<br />
<br />
Alternatively, {{Pkg|qemu-user-static}} exists as a usermode and static variant.<br />
<br />
=== QEMU variants ===<br />
<br />
QEMU is offered in several variants suited for different use cases.<br />
<br />
As a first classification, QEMU is offered in full-system and usermode emulation modes:<br />
<br />
; Full-system emulation<br />
: In this mode, QEMU emulates a full system, including one or several processors and various peripherals. It is more accurate but slower, and does not require the emulated OS to be Linux.<br />
: QEMU commands for full-system emulation are named {{ic|qemu-system-''target_architecture''}}, e.g. {{ic|qemu-system-x86_64}} for emulating [[Wikipedia:x86_64|x86_64]] CPUs, {{ic|qemu-system-i386}} for Intel [[Wikipedia:i386|32-bit x86]] CPUs, {{ic|qemu-system-arm}} for [[Wikipedia:ARM architecture family#32-bit architecture|ARM (32 bits)]], {{ic|qemu-system-aarch64}} for [[Wikipedia:AArch64|ARM64]], etc.<br />
: If the target architecture matches the host CPU, this mode may still benefit from a significant speedup by using a hypervisor like [[#Enabling KVM|KVM]] or Xen.<br />
; [https://www.qemu.org/docs/master/user/main.html Usermode emulation]<br />
: In this mode, QEMU is able to invoke a Linux executable compiled for a (potentially) different architecture by leveraging the host system resources. There may be compatibility issues, e.g. some features may not be implemented, dynamically linked executables will not work out of the box (see [[#Chrooting into arm/arm64 environment from x86_64]] to address this) and only Linux is supported (although [https://wiki.winehq.org/Emulation Wine may be used] for running Windows executables).<br />
: QEMU commands for usermode emulation are named {{ic|qemu-''target_architecture''}}, e.g. {{ic|qemu-x86_64}} for emulating 64-bit CPUs.<br />
<br />
QEMU is offered in dynamically-linked and statically-linked variants:<br />
<br />
; Dynamically-linked (default): {{ic|qemu-*}} commands depend on the host OS libraries, so executables are smaller.<br />
; Statically-linked: {{ic|qemu-*}} commands can be copied to any Linux system with the same architecture.<br />
<br />
In the case of Arch Linux, full-system emulation is offered as:<br />
<br />
; Non-headless (default): This variant enables GUI features that require additional dependencies (like SDL or GTK).<br />
; Headless: This is a slimmer variant that does not require GUI (this is suitable e.g. for servers).<br />
<br />
Note that headless and non-headless versions install commands with the same name (e.g. {{ic|qemu-system-x86_64}}) and thus cannot be both installed at the same time.<br />
<br />
=== Details on packages available in Arch Linux ===<br />
<br />
* The {{Pkg|qemu-desktop}} package provides the {{ic|x86_64}} architecture emulators for full-system emulation ({{ic|qemu-system-x86_64}}). The {{Pkg|qemu-emulators-full}} package provides the {{ic|x86_64}} usermode variant ({{ic|qemu-x86_64}}) and also for the rest of supported architectures it includes both full-system and usermode variants (e.g. {{ic|qemu-system-arm}} and {{ic|qemu-arm}}).<br />
* The headless versions of these packages (only applicable to full-system emulation) are {{Pkg|qemu-base}} ({{ic|x86_64}}-only) and {{Pkg|qemu-emulators-full}} (rest of architectures).<br />
* Full-system emulation can be expanded with some QEMU modules present in separate packages: {{Pkg|qemu-block-gluster}}, {{Pkg|qemu-block-iscsi}} and {{Pkg|qemu-guest-agent}}.<br />
* {{Pkg|qemu-user-static}} provides a usermode and static variant for all target architectures supported by QEMU. The installed QEMU commands are named {{ic|qemu-''target_architecture''-static}}, for example, {{ic|qemu-x86_64-static}} for intel 64-bit CPUs.<br />
<br />
{{Note|At present, Arch does not offer a full-system mode and statically linked variant (neither officially nor via AUR), as this is usually not needed.}}<br />
<br />
=== Custom build ===<br />
<br />
{{Remove|Explaining how to use the [[Arch build system]] is out of scope here. There is no motivation for the customization in the first place.}}<br />
<br />
To obtain a customized version of QEMU, [[Git#Getting a Git repository|clone]] the package source of {{Pkg|qemu-common}} or {{AUR|qemu-git}}.<br />
<br />
The respective [[PKGBUILD]] file calls QEMU's [https://www.gnu.org/prep/standards/html_node/Configuration.html configure script] which accepts parameters obtainable by first manually running --help on it. <br />
To access this help beforehand, you may [[Makepkg#Usage|use makepkg]] to let it download and extract the QEMU source, canceling the build process as soon as the configure script begins.<br />
<br />
With the PKGBUILD file's configure script calls modified as desired, you may [[Makepkg#Usage|use makepkg]] (again) to let it build the packages, though it is inadvisable to let it install them as conflicting headless / static packages will be built as well and a typical user certainly won't need the additional system emulators for the other architectures.<br />
<br />
When the build process completes, it is advisable to instead copy your desired packages (see the [[#Removal|list for qemu-desktop in "Removal"]]{{Broken section link}}) to a different directory, [[Pacman#Additional commands|let pacman install them all]] and add them to the [[Pacman#Skip package from being upgraded|IgnorePkg]] list so you get to upgrade them manually.<br />
<br />
== Graphical front-ends for QEMU ==<br />
<br />
Unlike other virtualization programs such as [[VirtualBox]] and [[VMware]], QEMU does not provide a GUI to manage virtual machines (other than the window that appears when running a virtual machine), nor does it provide a way to create persistent virtual machines with saved settings. All parameters to run a virtual machine must be specified on the command line at every launch, unless you have created a custom script to start your virtual machine(s).<br />
<br />
[[Libvirt]] provides a convenient way to manage QEMU virtual machines. See [[Libvirt#Client|list of libvirt clients]] for available front-ends.<br />
<br />
== Creating new virtualized system ==<br />
<br />
=== Creating a hard disk image ===<br />
<br />
{{Accuracy|If I get the man page right the raw format only allocates the full size if the filesystem does not support "holes" or it is <br />
explicitly told to preallocate. See {{man|1|qemu-img|NOTES}}.}} <br />
<br />
{{Tip|See [[Wikibooks:QEMU/Images]] for more information on QEMU images.}}<br />
<br />
To run QEMU you will need a hard disk image, unless you are booting a live system from CD-ROM or the network (and not doing so to install an operating system to a hard disk image). A hard disk image is a file which stores the contents of the emulated hard disk.<br />
<br />
A hard disk image can be ''raw'', so that it is literally byte-by-byte the same as what the guest sees, and will always use the full capacity of the guest hard drive on the host. This method provides the least I/O overhead, but can waste a lot of space, as not-used space on the guest cannot be used on the host.<br />
<br />
Alternatively, the hard disk image can be in a format such as ''qcow2'' which only allocates space to the image file when the guest operating system actually writes to those sectors on its virtual hard disk. The image appears as the full size to the guest operating system, even though it may take up only a very small amount of space on the host system. This image format also supports QEMU snapshotting functionality (see [[#Creating and managing snapshots via the monitor console]] for details). However, using this format instead of ''raw'' will likely affect performance.<br />
<br />
QEMU provides the {{ic|qemu-img}} command to create hard disk images. For example to create a 4 GiB image in the ''raw'' format:<br />
<br />
$ qemu-img create -f raw ''image_file'' 4G<br />
<br />
You may use {{ic|-f qcow2}} to create a ''qcow2'' disk instead.<br />
<br />
{{Note|You can also simply create a ''raw'' image by creating a file of the needed size using {{ic|dd}} or {{ic|fallocate}}.}}<br />
<br />
{{Warning|If you store the hard disk images on a [[Btrfs]] file system, you should consider disabling [[Btrfs#Copy-on-Write (CoW)|Copy-on-Write]] for the directory before creating any images.}}<br />
<br />
==== Overlay storage images ====<br />
<br />
You can create a storage image once (the 'backing' image) and have QEMU keep mutations to this image in an overlay image. This allows you to revert to a previous state of this storage image. You could revert by creating a new overlay image at the time you wish to revert, based on the original backing image.<br />
<br />
To create an overlay image, issue a command like:<br />
<br />
$ qemu-img create -o backing_file=''img1.raw'',backing_fmt=''raw'' -f ''qcow2'' ''img1.cow''<br />
<br />
After that you can run your QEMU virtual machine as usual (see [[#Running virtualized system]]):<br />
<br />
$ qemu-system-x86_64 ''img1.cow''<br />
<br />
The backing image will then be left intact and mutations to this storage will be recorded in the overlay image file.<br />
<br />
When the path to the backing image changes, repair is required.<br />
<br />
{{Warning|The backing image's absolute filesystem path is stored in the (binary) overlay image file. Changing the backing image's path requires some effort.}}<br />
<br />
Make sure that the original backing image's path still leads to this image. If necessary, make a symbolic link at the original path to the new path. Then issue a command like:<br />
<br />
$ qemu-img rebase -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
At your discretion, you may alternatively perform an 'unsafe' rebase where the old path to the backing image is not checked:<br />
<br />
$ qemu-img rebase -u -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
==== Resizing an image ====<br />
<br />
{{Warning|Resizing an image containing an NTFS boot file system could make the operating system installed on it unbootable. It is recommended to create a backup first.}}<br />
<br />
The {{ic|qemu-img}} executable has the {{ic|resize}} option, which enables easy resizing of a hard drive image. It works for both ''raw'' and ''qcow2''. For example, to increase image space by 10 GiB, run:<br />
<br />
$ qemu-img resize ''disk_image'' +10G<br />
<br />
After enlarging the disk image, you must use file system and partitioning tools inside the virtual machine to actually begin using the new space. <br />
<br />
===== Shrinking an image =====<br />
<br />
When shrinking a disk image, you must first reduce the allocated file systems and partition sizes using the file system and partitioning tools inside the virtual machine and then shrink the disk image accordingly. For a Windows guest, this can be performed from the "create and format hard disk partitions" control panel.<br />
<br />
{{Warning|Proceeding to shrink the disk image without reducing the guest partition sizes will result in data loss.}}<br />
<br />
Then, to decrease image space by 10 GiB, run:<br />
<br />
$ qemu-img resize --shrink ''disk_image'' -10G<br />
<br />
==== Converting an image ====<br />
<br />
You can convert an image to other formats using {{ic|qemu-img convert}}. This example shows how to convert a ''raw'' image to ''qcow2'':<br />
<br />
$ qemu-img convert -f raw -O qcow2 ''input''.img ''output''.qcow2<br />
<br />
This will not remove the original input file.<br />
<br />
=== Preparing the installation media ===<br />
<br />
To install an operating system into your disk image, you need the installation medium (e.g. optical disc, USB-drive, or ISO image) for the operating system. The installation medium should not be mounted because QEMU accesses the media directly.<br />
<br />
{{Tip|If using an optical disc, it is a good idea to first dump the media to a file because this both improves performance and does not require you to have direct access to the devices (that is, you can run QEMU as a regular user without having to change access permissions on the media's device file). For example, if the CD-ROM device node is named {{ic|/dev/cdrom}}, you can dump it to a file with the command: {{bc|1=$ dd if=/dev/cdrom of=''cd_image.iso'' bs=4k}}}}<br />
<br />
=== Installing the operating system ===<br />
<br />
This is the first time you will need to start the emulator. To install the operating system on the disk image, you must attach both the disk image and the installation media to the virtual machine, and have it boot from the installation media.<br />
<br />
For example on i386 guests, to install from a bootable ISO file as CD-ROM and a raw disk image:<br />
<br />
$ qemu-system-x86_64 -cdrom ''iso_image'' -boot order=d -drive file=''disk_image'',format=raw<br />
<br />
See {{man|1|qemu}} for more information about loading other media types (such as floppy, disk images or physical drives) and [[#Running virtualized system]] for other useful options.<br />
<br />
After the operating system has finished installing, the QEMU image can be booted directly (see [[#Running virtualized system]]).<br />
<br />
{{Note|By default only 128 MiB of memory is assigned to the machine. The amount of memory can be adjusted with the {{ic|-m}} switch, for example {{ic|-m 512M}} or {{ic|-m 2G}}.}}<br />
<br />
{{Tip|<br />
* Instead of specifying {{ic|1=-boot order=x}}, some users may feel more comfortable using a boot menu: {{ic|1=-boot menu=on}}, at least during configuration and experimentation.<br />
* When running QEMU in headless mode, it starts a local VNC server on port 5900 per default. You can use [[TigerVNC]] to connect to the guest OS: {{ic|vncviewer :5900}}<br />
* If you need to replace floppies or CDs as part of the installation process, you can use the QEMU machine monitor (press {{ic|Ctrl+Alt+2}} in the virtual machine's window) to remove and attach storage devices to a virtual machine. Type {{ic|info block}} to see the block devices, and use the {{ic|change}} command to swap out a device. Press {{ic|Ctrl+Alt+1}} to go back to the virtual machine.<br />
}}<br />
<br />
== Running virtualized system ==<br />
<br />
{{ic|qemu-system-*}} binaries (for example {{ic|qemu-system-i386}} or {{ic|qemu-system-x86_64}}, depending on guest's architecture) are used to run the virtualized guest. The usage is:<br />
<br />
$ qemu-system-x86_64 ''options'' ''disk_image''<br />
<br />
Options are the same for all {{ic|qemu-system-*}} binaries, see {{man|1|qemu}} for documentation of all options.<br />
<br />
Usually, if an option has many possible values, you can use<br />
<br />
$ qemu-system-x86_64 ''option'' ''help''<br />
<br />
to list all possible values. If it supports properties, you can use<br />
<br />
$ qemu-system-x86_64 ''option'' ''value,help''<br />
<br />
to list all available properties.<br />
<br />
For example:<br />
$ qemu-system-x86_64 -machine help<br />
$ qemu-system-x86_64 -machine q35,help<br />
$ qemu-system-x86_64 -device help<br />
$ qemu-system-x86_64 -device qxl,help<br />
<br />
You can use these methods and the {{man|1|qemu}} documentation to understand the options used in follow sections.<br />
<br />
By default, QEMU will show the virtual machine's video output in a window. One thing to keep in mind: when you click inside the QEMU window, the mouse pointer is grabbed. To release it, press {{ic|Ctrl+Alt+g}}.<br />
<br />
{{Warning|QEMU should never be run as root. If you must launch it in a script as root, you should use the {{ic|-runas}} option to make QEMU drop root privileges.}}<br />
<br />
=== Enabling KVM ===<br />
<br />
KVM (''Kernel-based Virtual Machine'') full virtualization must be supported by your Linux kernel and your hardware, and necessary [[kernel modules]] must be loaded. See [[KVM]] for more information.<br />
<br />
To start QEMU in KVM mode, append {{ic|-accel kvm}} to the additional start options. To check if KVM is enabled for a running virtual machine, enter the [[#QEMU monitor]] and type {{ic|info kvm}}.<br />
<br />
{{Note|<br />
* The argument {{ic|1=accel=kvm}} of the {{ic|-machine}} option is equivalent to the {{ic|-enable-kvm}} or the {{ic|-accel kvm}} option.<br />
* CPU model {{ic|host}} requires KVM.<br />
* If you start your virtual machine with a GUI tool and experience very bad performance, you should check for proper KVM support, as QEMU may be falling back to software emulation.<br />
* KVM needs to be enabled in order to start Windows 7 or Windows 8 properly without a ''blue screen''.<br />
}}<br />
<br />
=== Enabling IOMMU (Intel VT-d/AMD-Vi) support ===<br />
<br />
First enable IOMMU, see [[PCI passthrough via OVMF#Setting up IOMMU]].<br />
<br />
Add {{ic|-device intel-iommu}} to create the IOMMU device:<br />
<br />
$ qemu-system-x86_64 '''-enable-kvm -machine q35 -device intel-iommu''' -cpu host ..<br />
<br />
{{Note|<br />
On Intel CPU based systems creating an IOMMU device in a QEMU guest with {{ic|-device intel-iommu}} will disable PCI passthrough with an error like: {{bc|Device at bus pcie.0 addr 09.0 requires iommu notifier which is currently not supported by intel-iommu emulation}} While adding the kernel parameter {{ic|1=intel_iommu=on}} is still needed for remapping IO (e.g. [[PCI passthrough via OVMF#Isolating the GPU|PCI passthrough with vfio-pci]]), {{ic|-device intel-iommu}} should not be set if PCI passthrough is required.<br />
}}<br />
<br />
=== Booting in UEFI mode ===<br />
<br />
The default firmware used by QEMU is [https://www.coreboot.org/SeaBIOS SeaBIOS], which is a Legacy BIOS implementation. QEMU uses {{ic|/usr/share/qemu/bios-256k.bin}} (provided by the {{Pkg|seabios}} package) as a default read-only (ROM) image. You can use the {{ic|-bios}} argument to select another firmware file. However, UEFI requires writable memory to work properly, so you need to emulate [https://wiki.qemu.org/Features/PC_System_Flash PC System Flash] instead.<br />
<br />
[https://github.com/tianocore/tianocore.github.io/wiki/OVMF OVMF] is a TianoCore project to enable UEFI support for Virtual Machines. It can be [[install]]ed with the {{Pkg|edk2-ovmf}} package.<br />
<br />
There are two ways to use OVMF as a firmware. The first is to copy {{ic|/usr/share/edk2/x64/OVMF.4m.fd}}, make it writable and use as a pflash drive:<br />
<br />
-drive if=pflash,format=raw,file=''/copy/of/OVMF.4m.fd''<br />
<br />
All changes to the UEFI settings will be saved directly to this file.<br />
<br />
Another and more preferable way is to split OVMF into two files. The first one will be read-only and store the firmware executable, and the second one will be used as a writable variable store. The advantage is that you can use the firmware file directly without copying, so it will be updated automatically by [[pacman]].<br />
<br />
Use {{ic|/usr/share/edk2/x64/OVMF_CODE.4m.fd}} as a first read-only pflash drive. Copy {{ic|/usr/share/edk2/x64/OVMF_VARS.4m.fd}}, make it writable and use as a second writable pflash drive:<br />
<br />
-drive if=pflash,format=raw,readonly=on,file=/usr/share/edk2/x64/OVMF_CODE.4m.fd \<br />
-drive if=pflash,format=raw,file=''/copy/of/OVMF_VARS.4m.fd''<br />
<br />
If secure boot is wanted, replace {{ic|/usr/share/edk2/x64/OVMF_CODE.4m.fd}} with {{ic|/usr/share/edk2/x64/OVMF_CODE.secboot.4m.fd}}.<br />
<br />
=== Trusted Platform Module emulation ===<br />
<br />
QEMU can emulate [[Trusted Platform Module]], which is required by some systems such as Windows 11 (which requires TPM 2.0).<br />
<br />
[[Install]] the {{Pkg|swtpm}} package, which provides a software TPM implementation. Create some directory for storing TPM data ({{ic|''/path/to/mytpm''}} will be used as an example). Run this command to start the emulator:<br />
<br />
$ swtpm socket --tpm2 --tpmstate dir=''/path/to/mytpm'' --ctrl type=unixio,path=''/path/to/mytpm/swtpm-sock''<br />
<br />
{{ic|''/path/to/mytpm/swtpm-sock''}} will be created by ''swtpm'': this is a UNIX socket to which QEMU will connect. You can put it in any directory.<br />
<br />
By default, ''swtpm'' starts a TPM version 1.2 emulator. The {{ic|--tpm2}} option enables TPM 2.0 emulation.<br />
<br />
Finally, add the following options to QEMU:<br />
<br />
-chardev socket,id=chrtpm,path=''/path/to/mytpm/swtpm-sock'' \<br />
-tpmdev emulator,id=tpm0,chardev=chrtpm \<br />
-device tpm-tis,tpmdev=tpm0<br />
<br />
and TPM will be available inside the virtual machine. After shutting down the virtual machine, ''swtpm'' will be automatically terminated.<br />
<br />
See [https://qemu-project.gitlab.io/qemu/specs/tpm.html the QEMU documentation] for more information. <br />
<br />
If guest OS still doesn't recognize the TPM device, try to adjust ''CPU Models and Topology'' options. It might cause problem.<br />
<br />
== Sharing data between host and guest ==<br />
<br />
=== Network ===<br />
<br />
Data can be shared between the host and guest OS using any network protocol that can transfer files, such as [[NFS]], [[SMB]], [[Wikipedia:Network block device|NBD]], HTTP, [[Very Secure FTP Daemon|FTP]], or [[SSH]], provided that you have set up the network appropriately and enabled the appropriate services.<br />
<br />
The default user-mode networking allows the guest to access the host OS at the IP address 10.0.2.2. Any servers that you are running on your host OS, such as a SSH server or SMB server, will be accessible at this IP address. So on the guests, you can mount directories exported on the host via [[SMB]] or [[NFS]], or you can access the host's HTTP server, etc.<br />
It will not be possible for the host OS to access servers running on the guest OS, but this can be done with other network configurations (see [[#Tap networking with QEMU]]).<br />
<br />
=== QEMU's port forwarding ===<br />
<br />
{{Note|QEMU's port forwarding is IPv4-only. IPv6 port forwarding is not implemented and the last patches were proposed in 2018.[https://lore.kernel.org/qemu-devel/1540512223-21199-1-git-send-email-max7255@yandex-team.ru/T/#u]}}<br />
<br />
QEMU can forward ports from the host to the guest to enable e.g. connecting from the host to an SSH server running on the guest.<br />
<br />
For example, to bind port 60022 on the host with port 22 (SSH) on the guest, start QEMU with a command like:<br />
<br />
$ qemu-system-x86_64 ''disk_image'' -nic user,hostfwd=tcp::60022-:22<br />
<br />
Make sure the sshd is running on the guest and connect with:<br />
<br />
$ ssh ''guest-user''@127.0.0.1 -p 60022<br />
<br />
You can use [[SSHFS]] to mount the guest's file system at the host for shared read and write access.<br />
<br />
To forward several ports, you just repeat the {{ic|hostfwd}} in the {{ic|-nic}} argument, e.g. for VNC's port:<br />
<br />
$ qemu-system-x86_64 ''disk_image'' -nic user,hostfwd=tcp::60022-:22,hostfwd=tcp::5900-:5900<br />
<br />
=== QEMU's built-in SMB server ===<br />
<br />
QEMU's documentation says it has a "built-in" SMB server, but actually it just starts up [[Samba]] on the host with an automatically generated {{ic|smb.conf}} file located in {{ic|/tmp/qemu-smb.''random_string''}} and makes it accessible to the guest at a different IP address (10.0.2.4 by default). This only works for user networking, and is useful when you do not want to start the normal [[Samba]] service on the host, which the guest can also access if you have set up shares on it.<br />
<br />
Only a single directory can be set as shared with the option {{ic|1=smb=}}, but adding more directories (even while the virtual machine is running) could be as easy as creating symbolic links in the shared directory if QEMU configured SMB to follow symbolic links. It does not do so, but the configuration of the running SMB server can be changed as described below.<br />
<br />
''Samba'' must be installed on the host. To enable this feature, start QEMU with a command like:<br />
<br />
$ qemu-system-x86_64 -nic user,id=nic0,smb=''shared_dir_path'' ''disk_image''<br />
<br />
where {{ic|''shared_dir_path''}} is a directory that you want to share between the guest and host.<br />
<br />
Then, in the guest, you will be able to access the shared directory on the host 10.0.2.4 with the share name "qemu". For example, in Windows Explorer you would go to {{ic|\\10.0.2.4\qemu}}.<br />
<br />
{{Note|<br />
* If you are using sharing options multiple times like {{ic|1=-net user,smb=''shared_dir_path1'' -net user,smb=''shared_dir_path2''}} or {{ic|1=-net user,smb=''shared_dir_path1'',smb=''shared_dir_path2''}} then it will share only the last defined one.<br />
* If you cannot access the shared folder and the guest system is Windows, check that the [http://ecross.mvps.org/howto/enable-netbios-over-tcp-ip-with-windows.htm NetBIOS protocol is enabled]{{Dead link|2023|05|06|status=domain name not resolved}} and that a firewall does not block [https://technet.microsoft.com/en-us/library/cc940063.aspx ports] used by the NetBIOS protocol.<br />
* If you cannot access the shared folder and the guest system is Windows 10 Enterprise or Education or Windows Server 2016, [https://support.microsoft.com/en-us/help/4046019 enable guest access].<br />
* If you use [[#Tap networking with QEMU]], use {{ic|1=-device virtio-net,netdev=vmnic -netdev user,id=vmnic,smb=''shared_dir_path''}} to get SMB.<br />
}}<br />
<br />
One way to share multiple directories and to add or remove them while the virtual machine is running, is to share an empty directory and create/remove symbolic links to the directories in the shared directory. For this to work, the configuration of the running SMB server can be changed with the following script, which also allows the execution of files on the guest that are not set executable on the host:<br />
<br />
#!/bin/sh<br />
eval $(ps h -C smbd -o pid,args | grep /tmp/qemu-smb | gawk '{print "pid="$1";conf="$6}')<br />
echo "[global]<br />
allow insecure wide links = yes<br />
[qemu]<br />
follow symlinks = yes<br />
wide links = yes<br />
acl allow execute always = yes" >> "$conf"<br />
# in case the change is not detected automatically:<br />
smbcontrol --configfile="$conf" "$pid" reload-config<br />
<br />
This can be applied to the running server started by qemu only after the guest has connected to the network drive the first time. An alternative to this method is to add additional shares to the configuration file like so:<br />
<br />
echo "[''myshare'']<br />
path=''another_path''<br />
read only=no<br />
guest ok=yes<br />
force user=''username''" >> $conf<br />
<br />
This share will be available on the guest as {{ic|\\10.0.2.4\''myshare''}}.<br />
<br />
=== Using filesystem passthrough and VirtFS ===<br />
<br />
See the [https://wiki.qemu.org/Documentation/9psetup QEMU documentation].<br />
<br />
=== Host file sharing with virtiofsd ===<br />
<br />
{{Style|See [[Help:Style/Formatting and punctuation]].}}<br />
<br />
virtiofsd is shipped with QEMU package. Documentation is available [https://qemu-stsquad.readthedocs.io/en/docs-next/tools/virtiofsd.html online]{{Dead link|2023|05|06|status=404}} or {{ic|/usr/share/doc/qemu/qemu/tools/virtiofsd.html}} on local file system with {{Pkg|qemu-docs}} installed.<br />
<br />
Add user that runs qemu to the 'kvm' [[user group]], because it needs to access the virtiofsd socket. You might have to logout for change to take effect.<br />
<br />
{{Accuracy|Running services as root is not secure. Also the process should be wrapped in a systemd service.}}<br />
<br />
Start as virtiofsd as root:<br />
<br />
# /usr/lib/virtiofsd --socket-path=/var/run/qemu-vm-001.sock --shared-dir /tmp/vm-001 --cache always<br />
<br />
where<br />
<br />
* {{ic|/var/run/qemu-vm-001.sock}} is a socket file,<br />
* {{ic|/tmp/vm-001}} is a shared directory between the host and the guest virtual machine.<br />
<br />
The created socket file has root only access permission. Give group kvm access to it with:<br />
<br />
# chgrp kvm qemu-vm-001.sock; chmod g+rxw qemu-vm-001.sock<br />
<br />
Add the following configuration options when starting the virtual machine:<br />
<br />
-object memory-backend-memfd,id=mem,size=4G,share=on \<br />
-numa node,memdev=mem \<br />
-chardev socket,id=char0,path=/var/run/qemu-vm-001.sock \<br />
-device vhost-user-fs-pci,chardev=char0,tag=myfs<br />
<br />
where<br />
<br />
{{Expansion|Explain the remaining options (or remove them if they are not necessary).}}<br />
<br />
* {{ic|1=size=4G}} shall match size specified with {{ic|-m 4G}} option,<br />
* {{ic|/var/run/qemu-vm-001.sock}} points to socket file started earlier,<br />
<br />
{{Style|The section should not be specific to Windows.}}<br />
<br />
Remember, that guest must be configured to enable sharing. For Windows there are [https://virtio-fs.gitlab.io/howto-windows.html instructions]. Once configured, Windows will have the {{ic|Z:}} drive mapped automatically with shared directory content.<br />
<br />
Your Windows 10 guest system is properly configured if it has:<br />
<br />
* VirtioFSSService windows service,<br />
* WinFsp.Launcher windows service,<br />
* VirtIO FS Device driver under "System devices" in Windows "Device Manager".<br />
<br />
If the above installed and {{ic|Z:}} drive is still not listed, try repairing "Virtio-win-guest-tools" in Windows ''Add/Remove programs''.<br />
<br />
=== Mounting a partition of the guest on the host ===<br />
<br />
It can be useful to mount a drive image under the host system, it can be a way to transfer files in and out of the guest. This should be done when the virtual machine is not running.<br />
<br />
The procedure to mount the drive on the host depends on the type of qemu image, ''raw'' or ''qcow2''. We detail thereafter the steps to mount a drive in the two formats in [[#Mounting a partition from a raw image]] and [[#Mounting a partition from a qcow2 image]]. For the full documentation see [[Wikibooks:QEMU/Images#Mounting an image on the host]].<br />
<br />
{{Warning|You must unmount the partitions before running the virtual machine again. Otherwise, data corruption is very likely to occur.}}<br />
<br />
==== Mounting a partition from a raw image ====<br />
<br />
It is possible to mount partitions that are inside a raw disk image file by setting them up as loopback devices.<br />
<br />
===== With manually specifying byte offset =====<br />
<br />
One way to mount a disk image partition is to mount the disk image at a certain offset using a command like the following:<br />
<br />
# mount -o loop,offset=32256 ''disk_image'' ''mountpoint''<br />
<br />
The {{ic|1=offset=32256}} option is actually passed to the {{ic|losetup}} program to set up a loopback device that starts at byte offset 32256 of the file and continues to the end. This loopback device is then mounted. You may also use the {{ic|sizelimit}} option to specify the exact size of the partition, but this is usually unnecessary.<br />
<br />
Depending on your disk image, the needed partition may not start at offset 32256. Run {{ic|fdisk -l ''disk_image''}} to see the partitions in the image. fdisk gives the start and end offsets in 512-byte sectors, so multiply by 512 to get the correct offset to pass to {{ic|mount}}.<br />
<br />
===== With loop module autodetecting partitions =====<br />
<br />
The Linux loop driver actually supports partitions in loopback devices, but it is disabled by default. To enable it, do the following:<br />
<br />
* Get rid of all your loopback devices (unmount all mounted images, etc.).<br />
* [[Kernel modules#Manual module handling|Unload]] the {{ic|loop}} kernel module, and load it with the {{ic|1=max_part=15}} parameter set. Additionally, the maximum number of loop devices can be controlled with the {{ic|max_loop}} parameter.<br />
<br />
{{Tip|You can put an entry in {{ic|/etc/modprobe.d}} to load the loop module with {{ic|1=max_part=15}} every time, or you can put {{ic|1=loop.max_part=15}} on the kernel command-line, depending on whether you have the {{ic|loop.ko}} module built into your kernel or not.}}<br />
<br />
Set up your image as a loopback device:<br />
<br />
# losetup -f -P ''disk_image''<br />
<br />
Then, if the device created was {{ic|/dev/loop0}}, additional devices {{ic|/dev/loop0p''X''}} will have been automatically created, where X is the number of the partition. These partition loopback devices can be mounted directly. For example:<br />
<br />
# mount /dev/loop0p1 ''mountpoint''<br />
<br />
To mount the disk image with ''udisksctl'', see [[Udisks#Mount loop devices]].<br />
<br />
===== With kpartx =====<br />
<br />
''kpartx'' from the {{Pkg|multipath-tools}} package can read a partition table on a device and create a new device for each partition. For example:<br />
<br />
# kpartx -a ''disk_image''<br />
<br />
This will setup the loopback device and create the necessary partition(s) device(s) in {{ic|/dev/mapper/}}.<br />
<br />
==== Mounting a partition from a qcow2 image ====<br />
<br />
We will use {{ic|qemu-nbd}}, which lets use the NBD (''network block device'') protocol to share the disk image.<br />
<br />
First, we need the ''nbd'' module loaded:<br />
<br />
# modprobe nbd max_part=16<br />
<br />
Then, we can share the disk and create the device entries:<br />
<br />
# qemu-nbd -c /dev/nbd0 ''/path/to/image.qcow2''<br />
<br />
Discover the partitions:<br />
<br />
# partprobe /dev/nbd0<br />
<br />
''fdisk'' can be used to get information regarding the different partitions in {{ic|''nbd0''}}:<br />
<br />
{{hc|# fdisk -l /dev/nbd0|2=<br />
Disk /dev/nbd0: 25.2 GiB, 27074281472 bytes, 52879456 sectors<br />
Units: sectors of 1 * 512 = 512 bytes<br />
Sector size (logical/physical): 512 bytes / 512 bytes<br />
I/O size (minimum/optimal): 512 bytes / 512 bytes<br />
Disklabel type: dos<br />
Disk identifier: 0xa6a4d542<br />
<br />
Device Boot Start End Sectors Size Id Type<br />
/dev/nbd0p1 * 2048 1026047 1024000 500M 7 HPFS/NTFS/exFAT<br />
/dev/nbd0p2 1026048 52877311 51851264 24.7G 7 HPFS/NTFS/exFAT}}<br />
<br />
Then mount any partition of the drive image, for example the partition 2:<br />
<br />
# mount /dev/nbd0'''p2''' ''mountpoint''<br />
<br />
After the usage, it is important to unmount the image and reverse previous steps, i.e. unmount the partition and disconnect the nbd device:<br />
<br />
# umount ''mountpoint''<br />
# qemu-nbd -d /dev/nbd0<br />
<br />
=== Using any real partition as the single primary partition of a hard disk image ===<br />
<br />
Sometimes, you may wish to use one of your system partitions from within QEMU. Using a raw partition for a virtual machine will improve performance, as the read and write operations do not go through the file system layer on the physical host. Such a partition also provides a way to share data between the host and guest.<br />
<br />
In Arch Linux, device files for raw partitions are, by default, owned by ''root'' and the ''disk'' group. If you would like to have a non-root user be able to read and write to a raw partition, you must either change the owner of the partition's device file to that user, add that user to the ''disk'' group, or use [[ACL]] for more fine-grained access control.<br />
<br />
{{Warning|<br />
* Although it is possible, it is not recommended to allow virtual machines to alter critical data on the host system, such as the root partition.<br />
* You must not mount a file system on a partition read-write on both the host and the guest at the same time. Otherwise, data corruption will result.<br />
}}<br />
<br />
After doing so, you can attach the partition to a QEMU virtual machine as a virtual disk.<br />
<br />
However, things are a little more complicated if you want to have the ''entire'' virtual machine contained in a partition. In that case, there would be no disk image file to actually boot the virtual machine since you cannot install a boot loader to a partition that is itself formatted as a file system and not as a partitioned device with an MBR. Such a virtual machine can be booted either by: [[#Specifying kernel and initrd manually]], [[#Simulating a virtual disk with MBR]], [[#Using the device-mapper]], [[#Using a linear RAID]] or [[#Using a Network Block Device]].<br />
<br />
==== Specifying kernel and initrd manually ====<br />
<br />
QEMU supports loading [[Kernels|Linux kernels]] and [[initramfs|init ramdisks]] directly, thereby circumventing boot loaders such as [[GRUB]]. It then can be launched with the physical partition containing the root file system as the virtual disk, which will not appear to be partitioned. This is done by issuing a command similar to the following:<br />
<br />
{{Note|In this example, it is the '''host's''' images that are being used, not the guest's. If you wish to use the guest's images, either mount {{ic|/dev/sda3}} read-only (to protect the file system from the host) and specify the {{ic|/full/path/to/images}} or use some kexec hackery in the guest to reload the guest's kernel (extends boot time). }}<br />
<br />
$ qemu-system-x86_64 -kernel /boot/vmlinuz-linux -initrd /boot/initramfs-linux.img -append root=/dev/sda /dev/sda3<br />
<br />
In the above example, the physical partition being used for the guest's root file system is {{ic|/dev/sda3}} on the host, but it shows up as {{ic|/dev/sda}} on the guest.<br />
<br />
You may, of course, specify any kernel and initrd that you want, and not just the ones that come with Arch Linux.<br />
<br />
When there are multiple [[kernel parameters]] to be passed to the {{ic|-append}} option, they need to be quoted using single or double quotes. For example:<br />
<br />
... -append 'root=/dev/sda1 console=ttyS0'<br />
<br />
==== Simulating a virtual disk with MBR ====<br />
<br />
A more complicated way to have a virtual machine use a physical partition, while keeping that partition formatted as a file system and not just having the guest partition the partition as if it were a disk, is to simulate an MBR for it so that it can boot using a boot loader such as GRUB.<br />
<br />
For the following, suppose you have a plain, unmounted {{ic|/dev/hda''N''}} partition with some file system on it you wish to make part of a QEMU disk image. The trick is to dynamically prepend a master boot record (MBR) to the real partition you wish to embed in a QEMU raw disk image. More generally, the partition can be any part of a larger simulated disk, in particular a block device that simulates the original physical disk but only exposes {{ic|/dev/hda''N''}} to the virtual machine.<br />
<br />
A virtual disk of this type can be represented by a VMDK file that contains references to (a copy of) the MBR and the partition, but QEMU does not support this VMDK format. For instance, a virtual disk [https://www.virtualbox.org/manual/ch09.html#rawdisk created by]<br />
<br />
$ VBoxManage internalcommands createrawvmdk -filename ''/path/to/file.vmdk'' -rawdisk /dev/hda<br />
<br />
will be rejected by QEMU with the error message<br />
<br />
Unsupported image type 'partitionedDevice'<br />
<br />
Note that {{ic|VBoxManage}} creates two files, {{ic|''file.vmdk''}} and {{ic|''file-pt.vmdk''}}, the latter being a copy of the MBR, to which the text file {{ic|file.vmdk}} points. Read operations outside the target partition or the MBR would give zeros, while written data would be discarded.<br />
<br />
===== Using the device-mapper =====<br />
<br />
A method that is similar to the use of a VMDK descriptor file uses the [https://docs.kernel.org/admin-guide/device-mapper/index.html device-mapper] to prepend a loop device attached to the MBR file to the target partition. In case we do not need our virtual disk to have the same size as the original, we first create a file to hold the MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=2048<br />
<br />
Here, a 1 MiB (2048 * 512 bytes) file is created in accordance with partition alignment policies used by modern disk partitioning tools. For compatibility with older partitioning software, 63 sectors instead of 2048 might be required. The MBR only needs a single 512 bytes block, the additional free space can be used for a BIOS boot partition and, in the case of a hybrid partitioning scheme, for a GUID Partition Table. Then, we attach a loop device to the MBR file:<br />
<br />
{{hc|# losetup --show -f ''/path/to/mbr''|/dev/loop0}}<br />
<br />
In this example, the resulting device is {{ic|/dev/loop0}}. The device mapper is now used to join the MBR and the partition:<br />
<br />
# echo "0 2048 linear /dev/loop0 0<br />
2048 `blockdev --getsz /dev/hda''N''` linear /dev/hda''N'' 0" | dmsetup create qemu<br />
<br />
The resulting {{ic|/dev/mapper/qemu}} is what we will use as a QEMU raw disk image. Additional steps are required to create a partition table (see the section that describes the use of a linear RAID for an example) and boot loader code on the virtual disk (which will be stored in {{ic|''/path/to/mbr''}}).<br />
<br />
The following setup is an example where the position of {{ic|/dev/hda''N''}} on the virtual disk is to be the same as on the physical disk and the rest of the disk is hidden, except for the MBR, which is provided as a copy:<br />
<br />
# dd if=/dev/hda count=1 of=''/path/to/mbr''<br />
# loop=`losetup --show -f ''/path/to/mbr''`<br />
# start=`blockdev --report /dev/hda''N'' | tail -1 | awk '{print $5}'`<br />
# size=`blockdev --getsz /dev/hda''N''`<br />
# disksize=`blockdev --getsz /dev/hda`<br />
# echo "0 1 linear $loop 0<br />
1 $((start-1)) zero<br />
$start $size linear /dev/hda''N'' 0<br />
$((start+size)) $((disksize-start-size)) zero" | dmsetup create qemu<br />
<br />
The table provided as standard input to {{ic|dmsetup}} has a similar format as the table in a VDMK descriptor file produced by {{ic|VBoxManage}} and can alternatively be loaded from a file with {{ic|dmsetup create qemu --table ''table_file''}}. To the virtual machine, only {{ic|/dev/hda''N''}} is accessible, while the rest of the hard disk reads as zeros and discards written data, except for the first sector. We can print the table for {{ic|/dev/mapper/qemu}} with {{ic|dmsetup table qemu}} (use {{ic|udevadm info -rq name /sys/dev/block/''major'':''minor''}} to translate {{ic|''major'':''minor''}} to the corresponding {{ic|/dev/''blockdevice''}} name). Use {{ic|dmsetup remove qemu}} and {{ic|losetup -d $loop}} to delete the created devices.<br />
<br />
A situation where this example would be useful is an existing Windows XP installation in a multi-boot configuration and maybe a hybrid partitioning scheme (on the physical hardware, Windows XP could be the only operating system that uses the MBR partition table, while more modern operating systems installed on the same computer could use the GUID Partition Table). Windows XP supports hardware profiles, so that that the same installation can be used with different hardware configurations alternatingly (in this case bare metal vs. virtual) with Windows needing to install drivers for newly detected hardware only once for every profile. Note that in this example the boot loader code in the copied MBR needs to be updated to directly load Windows XP from {{ic|/dev/hda''N''}} instead of trying to start the multi-boot capable boot loader (like GRUB) present in the original system. Alternatively, a copy of the boot partition containing the boot loader installation can be included in the virtual disk the same way as the MBR.<br />
<br />
===== Using a linear RAID =====<br />
<br />
{{Out of date|[[Wikipedia:Cylinder-head-sector|CHS]] has been obsolete for decades.}}<br />
<br />
You can also do this using software [[RAID]] in linear mode (you need the {{ic|linear.ko}} kernel driver) and a loopback device: <br />
<br />
First, you create some small file to hold the MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=32<br />
<br />
Here, a 16 KiB (32 * 512 bytes) file is created. It is important not to make it too small (even if the MBR only needs a single 512 bytes block), since the smaller it will be, the smaller the chunk size of the software RAID device will have to be, which could have an impact on performance. Then, you setup a loopback device to the MBR file:<br />
<br />
# losetup -f ''/path/to/mbr''<br />
<br />
Let us assume the resulting device is {{ic|/dev/loop0}}, because we would not already have been using other loopbacks. Next step is to create the "merged" MBR + {{ic|/dev/hda''N''}} disk image using software RAID:<br />
<br />
# modprobe linear<br />
# mdadm --build --verbose /dev/md0 --chunk=16 --level=linear --raid-devices=2 /dev/loop0 /dev/hda''N''<br />
<br />
The resulting {{ic|/dev/md0}} is what you will use as a QEMU raw disk image (do not forget to set the permissions so that the emulator can access it). The last (and somewhat tricky) step is to set the disk configuration (disk geometry and partitions table) so that the primary partition start point in the MBR matches the one of {{ic|/dev/hda''N''}} inside {{ic|/dev/md0}} (an offset of exactly 16 * 512 = 16384 bytes in this example). Do this using {{ic|fdisk}} on the host machine, not in the emulator: the default raw disc detection routine from QEMU often results in non-kibibyte-roundable offsets (such as 31.5 KiB, as in the previous section) that cannot be managed by the software RAID code. Hence, from the host:<br />
<br />
# fdisk /dev/md0<br />
<br />
Press {{ic|X}} to enter the expert menu. Set number of 's'ectors per track so that the size of one cylinder matches the size of your MBR file. For two heads and a sector size of 512, the number of sectors per track should be 16, so we get cylinders of size 2x16x512=16k.<br />
<br />
Now, press {{ic|R}} to return to the main menu.<br />
<br />
Press {{ic|P}} and check that the cylinder size is now 16k.<br />
<br />
Now, create a single primary partition corresponding to {{ic|/dev/hda''N''}}. It should start at cylinder 2 and end at the end of the disk (note that the number of cylinders now differs from what it was when you entered fdisk.<br />
<br />
Finally, 'w'rite the result to the file: you are done. You now have a partition you can mount directly from your host, as well as part of a QEMU disk image:<br />
<br />
$ qemu-system-x86_64 -hdc /dev/md0 ''[...]''<br />
<br />
You can, of course, safely set any boot loader on this disk image using QEMU, provided the original {{ic|/dev/hda''N''}} partition contains the necessary tools.<br />
<br />
===== Using a Network Block Device =====<br />
<br />
With [https://docs.kernel.org/admin-guide/blockdev/nbd.html Network Block Device], Linux can use a remote server as one of its block device. You may use {{ic|nbd-server}} (from the {{Pkg|nbd}} package) to create an MBR wrapper for QEMU.<br />
<br />
Assuming you have already set up your MBR wrapper file like above, rename it to {{ic|wrapper.img.0}}. Then create a symbolic link named {{ic|wrapper.img.1}} in the same directory, pointing to your partition. Then put the following script in the same directory:<br />
<br />
{{bc|1=<br />
#!/bin/sh<br />
dir="$(realpath "$(dirname "$0")")"<br />
cat >wrapper.conf <<EOF<br />
[generic]<br />
allowlist = true<br />
listenaddr = 127.713705<br />
port = 10809<br />
<br />
[wrap]<br />
exportname = $dir/wrapper.img<br />
multifile = true<br />
EOF<br />
<br />
nbd-server \<br />
-C wrapper.conf \<br />
-p wrapper.pid \<br />
"$@"<br />
}}<br />
<br />
The {{ic|.0}} and {{ic|.1}} suffixes are essential; the rest can be changed. After running the above script (which you may need to do as root to make sure nbd-server is able to access the partition), you can launch QEMU with:<br />
<br />
qemu-system-x86_64 -drive file=nbd:127.713705:10809:exportname=wrap ''[...]''<br />
<br />
=== Using an entire physical disk device inside the virtual machine ===<br />
<br />
{{Style|Duplicates [[#Using any real partition as the single primary partition of a hard disk image]], libvirt instructions do not belong to this page.}}<br />
<br />
You may have a second disk with a different OS (like Windows) on it and may want to gain the ability to also boot it inside a virtual machine.<br />
Since the disk access is raw, the disk will perform quite well inside the virtual machine.<br />
<br />
==== Windows virtual machine boot prerequisites ====<br />
<br />
Be sure to install the [https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/archive-virtio/ virtio drivers] inside the OS on that disk before trying to boot it in the virtual machine.<br />
For Win 7 use version [https://askubuntu.com/questions/1310440/using-virtio-win-drivers-with-win7-sp1-x64 0.1.173-4].<br />
Some singular drivers from newer virtio builds may be used on Win 7 but you will have to install them manually via device manager.<br />
For Win 10 you can use the latest virtio build.<br />
<br />
===== Set up the windows disk interface drivers =====<br />
<br />
You may get a {{ic|0x0000007B}} bluescreen when trying to boot the virtual machine. This means Windows can not access the drive during the early boot stage because the disk interface driver it would need for that is not loaded / is set to start manually.<br />
<br />
The solution is to [https://superuser.com/a/1032769 enable these drivers to start at boot].<br />
<br />
In {{ic|HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services}}, find the folders {{ic|aliide, amdide, atapi, cmdide, iastor (may not exist), iastorV, intelide, LSI_SAS, msahci, pciide and viaide}}.<br />
Inside each of those, set all their "start" values to 0 in order to enable them at boot.<br />
If your drive is a PCIe NVMe drive, also enable that driver (should it exist).<br />
<br />
==== Find the unique path of your disk ====<br />
<br />
Run {{ic|ls /dev/disk/by-id/}}: tere you pick out the ID of the drive you want to insert into the virtual machine, for example {{ic|ata-TS512GMTS930L_C199211383}}.<br />
Now add that ID to {{ic|/dev/disk/by-id/}} so you get {{ic|/dev/disk/by-id/ata-TS512GMTS930L_C199211383}}.<br />
That is the unique path to that disk.<br />
<br />
==== Add the disk in QEMU CLI ====<br />
<br />
In QEMU CLI that would probably be:<br />
<br />
{{ic|1=-drive file=/dev/disk/by-id/ata-TS512GMTS930L_C199211383,format=raw,media=disk}}<br />
<br />
Just modify {{ic|file{{=}}}} to be the unique path of your drive.<br />
<br />
==== Add the disk in libvirt ====<br />
<br />
In libvirt XML that translates to<br />
<br />
{{hc|$ virsh edit ''vmname''|<nowiki><br />
...<br />
<disk type="block" device="disk"><br />
<driver name="qemu" type="raw" cache="none" io="native"/><br />
<source dev="/dev/disk/by-id/ata-TS512GMTS930L_C199211383"/><br />
<target dev="sda" bus="sata"/><br />
<address type="drive" controller="0" bus="0" target="0" unit="0"/><br />
</disk><br />
...<br />
</nowiki>}}<br />
<br />
Just modify "source dev" to be the unique path of your drive.<br />
<br />
==== Add the disk in virt-manager ====<br />
<br />
When creating a virtual machine, select "import existing drive" and just paste that unique path.<br />
If you already have the virtual machine, add a device, storage, then select or create custom storage.<br />
Now paste the unique path.<br />
<br />
== Networking ==<br />
<br />
{{Style|Network topologies (sections [[#Host-only networking]], [[#Internal networking]] and info spread out across other sections) should not be described alongside the various virtual interfaces implementations, such as [[#User-mode networking]], [[#Tap networking with QEMU]], [[#Networking with VDE2]].}}<br />
<br />
The performance of virtual networking should be better with tap devices and bridges than with user-mode networking or vde because tap devices and bridges are implemented in-kernel.<br />
<br />
In addition, networking performance can be improved by assigning virtual machines a [https://wiki.libvirt.org/page/Virtio virtio] network device rather than the default emulation of an e1000 NIC. See [[#Installing virtio drivers]] for more information.<br />
<br />
=== Link-level address caveat ===<br />
<br />
By giving the {{ic|-net nic}} argument to QEMU, it will, by default, assign a virtual machine a network interface with the link-level address {{ic|52:54:00:12:34:56}}. However, when using bridged networking with multiple virtual machines, it is essential that each virtual machine has a unique link-level (MAC) address on the virtual machine side of the tap device. Otherwise, the bridge will not work correctly, because it will receive packets from multiple sources that have the same link-level address. This problem occurs even if the tap devices themselves have unique link-level addresses because the source link-level address is not rewritten as packets pass through the tap device.<br />
<br />
Make sure that each virtual machine has a unique link-level address, but it should always start with {{ic|52:54:}}. Use the following option, replace ''X'' with arbitrary hexadecimal digit:<br />
<br />
$ qemu-system-x86_64 -net nic,macaddr=52:54:''XX:XX:XX:XX'' -net vde ''disk_image''<br />
<br />
Generating unique link-level addresses can be done in several ways:<br />
<br />
* Manually specify unique link-level address for each NIC. The benefit is that the DHCP server will assign the same IP address each time the virtual machine is run, but it is unusable for large number of virtual machines.<br />
* Generate random link-level address each time the virtual machine is run. Practically zero probability of collisions, but the downside is that the DHCP server will assign a different IP address each time. You can use the following command in a script to generate random link-level address in a {{ic|macaddr}} variable:<br />
<br />
{{bc|1=<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
qemu-system-x86_64 -net nic,macaddr="$macaddr" -net vde ''disk_image''<br />
}}<br />
<br />
* Use the following script {{ic|qemu-mac-hasher.py}} to generate the link-level address from the virtual machine name using a hashing function. Given that the names of virtual machines are unique, this method combines the benefits of the aforementioned methods: it generates the same link-level address each time the script is run, yet it preserves the practically zero probability of collisions.<br />
<br />
{{hc|qemu-mac-hasher.py|2=<br />
#!/usr/bin/env python<br />
# usage: qemu-mac-hasher.py <VMName><br />
<br />
import sys<br />
import zlib<br />
<br />
crc = str(hex(zlib.crc32(sys.argv[1].encode("utf-8")))).replace("x", "")[-8:]<br />
print("52:54:%s%s:%s%s:%s%s:%s%s" % tuple(crc))<br />
}}<br />
<br />
In a script, you can use for example:<br />
<br />
vm_name="''VM Name''"<br />
qemu-system-x86_64 -name "$vm_name" -net nic,macaddr=$(qemu-mac-hasher.py "$vm_name") -net vde ''disk_image''<br />
<br />
=== User-mode networking ===<br />
<br />
By default, without any {{ic|-netdev}} arguments, QEMU will use user-mode networking with a built-in DHCP server. Your virtual machines will be assigned an IP address when they run their DHCP client, and they will be able to access the physical host's network through IP masquerading done by QEMU.<br />
<br />
{{Note|ICMPv6 will not work, as support for it is not implemented: {{ic|Slirp: external icmpv6 not supported yet}}. [[Ping]]ing an IPv6 address will not work.}}<br />
<br />
This default configuration allows your virtual machines to easily access the Internet, provided that the host is connected to it, but the virtual machines will not be directly visible on the external network, nor will virtual machines be able to talk to each other if you start up more than one concurrently.<br />
<br />
QEMU's user-mode networking can offer more capabilities such as built-in TFTP or SMB servers, redirecting host ports to the guest (for example to allow SSH connections to the guest) or attaching guests to VLANs so that they can talk to each other. See the QEMU documentation on the {{ic|-net user}} flag for more details.<br />
<br />
However, user-mode networking has limitations in both utility and performance. More advanced network configurations require the use of tap devices or other methods.<br />
<br />
{{Note|If the host system uses [[systemd-networkd]], make sure to symlink the {{ic|/etc/resolv.conf}} file as described in [[systemd-networkd#Required services and setup]], otherwise the DNS lookup in the guest system will not work.}}<br />
<br />
{{Tip|<br />
* To use the virtio driver with user-mode networking, the option is: {{ic|1=-nic user,model=virtio-net-pci}}.<br />
* You can isolate user-mode networking from the host and the outside world by adding {{ic|1=restrict=y}}, for example: {{ic|1=-net user,restrict=y}}<br />
}}<br />
<br />
=== Tap networking with QEMU ===<br />
<br />
[[wikipedia:TUN/TAP|Tap devices]] are a Linux kernel feature that allows you to create virtual network interfaces that appear as real network interfaces. Packets sent to a tap interface are delivered to a userspace program, such as QEMU, that has bound itself to the interface.<br />
<br />
QEMU can use tap networking for a virtual machine so that packets sent to the tap interface will be sent to the virtual machine and appear as coming from a network interface (usually an Ethernet interface) in the virtual machine. Conversely, everything that the virtual machine sends through its network interface will appear on the tap interface.<br />
<br />
Tap devices are supported by the Linux bridge drivers, so it is possible to bridge together tap devices with each other and possibly with other host interfaces such as {{ic|eth0}}. This is desirable if you want your virtual machines to be able to talk to each other, or if you want other machines on your LAN to be able to talk to the virtual machines.<br />
<br />
{{Warning|If you bridge together tap device and some host interface, such as {{ic|eth0}}, your virtual machines will appear directly on the external network, which will expose them to possible attack. Depending on what resources your virtual machines have access to, you may need to take all the [[Firewalls|precautions]] you normally would take in securing a computer to secure your virtual machines. If the risk is too great, virtual machines have little resources or you set up multiple virtual machines, a better solution might be to use [[#Host-only networking|host-only networking]] and set up NAT. In this case you only need one firewall on the host instead of multiple firewalls for each guest.}}<br />
<br />
As indicated in the user-mode networking section, tap devices offer higher networking performance than user-mode. If the guest OS supports virtio network driver, then the networking performance will be increased considerably as well. Supposing the use of the tap0 device, that the virtio driver is used on the guest, and that no scripts are used to help start/stop networking, next is part of the qemu command one should see:<br />
<br />
-device virtio-net,netdev=network0 -netdev tap,id=network0,ifname=tap0,script=no,downscript=no<br />
<br />
But if already using a tap device with virtio networking driver, one can even boost the networking performance by enabling vhost, like:<br />
<br />
-device virtio-net,netdev=network0 -netdev tap,id=network0,ifname=tap0,script=no,downscript=no,vhost=on<br />
<br />
See [https://web.archive.org/web/20160222161955/http://www.linux-kvm.com:80/content/how-maximize-virtio-net-performance-vhost-net] for more information.<br />
<br />
==== Host-only networking ====<br />
<br />
If the bridge is given an IP address and traffic destined for it is allowed, but no real interface (e.g. {{ic|eth0}}) is connected to the bridge, then the virtual machines will be able to talk to each other and the host system. However, they will not be able to talk to anything on the external network, provided that you do not set up IP masquerading on the physical host. This configuration is called ''host-only networking'' by other virtualization software such as [[VirtualBox]].<br />
<br />
{{Tip|<br />
* If you want to set up IP masquerading, e.g. NAT for virtual machines, see the [[Internet sharing#Enable NAT]] page.<br />
* See [[Network bridge]] for information on creating bridge.<br />
* You may want to have a DHCP server running on the bridge interface to service the virtual network. For example, to use the {{ic|172.20.0.1/16}} subnet with [[dnsmasq]] as the DHCP server:<br />
<br />
{{bc|1=<br />
# ip addr add 172.20.0.1/16 dev br0<br />
# ip link set br0 up<br />
# dnsmasq --interface=br0 --bind-interfaces --dhcp-range=172.20.0.2,172.20.255.254<br />
}}<br />
}}<br />
<br />
==== Internal networking ====<br />
<br />
If you do not give the bridge an IP address and add an [[iptables]] rule to drop all traffic to the bridge in the INPUT chain, then the virtual machines will be able to talk to each other, but not to the physical host or to the outside network. This configuration is called ''internal networking'' by other virtualization software such as [[VirtualBox]]. You will need to either assign static IP addresses to the virtual machines or run a DHCP server on one of them.<br />
<br />
By default iptables would drop packets in the bridge network. You may need to use such iptables rule to allow packets in a bridged network:<br />
<br />
# iptables -I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Bridged networking using qemu-bridge-helper ====<br />
<br />
This method does not require a start-up script and readily accommodates multiple taps and multiple bridges. It uses {{ic|/usr/lib/qemu/qemu-bridge-helper}} binary, which allows creating tap devices on an existing bridge.<br />
<br />
{{Tip|<br />
* See [[Network bridge]] for information on creating bridge.<br />
* See https://wiki.qemu.org/Features/HelperNetworking for more information on QEMU's network helper.<br />
}}<br />
<br />
First, create a configuration file containing the names of all bridges to be used by QEMU:<br />
<br />
{{hc|/etc/qemu/bridge.conf|<br />
allow ''br0''<br />
allow ''br1''<br />
...}}<br />
<br />
Make sure {{ic|/etc/qemu/}} has {{ic|755}} [[permissions]]. [https://gitlab.com/qemu-project/qemu/-/issues/515 QEMU issues] and [https://www.gns3.com/community/discussions/gns3-cannot-work-with-qemu GNS3 issues] may arise if this is not the case.<br />
<br />
Now start the virtual machine; the most basic usage to run QEMU with the default network helper and default bridge {{ic|br0}}:<br />
<br />
$ qemu-system-x86_64 -nic bridge ''[...]''<br />
<br />
Using the bridge {{ic|br1}} and the virtio driver:<br />
<br />
$ qemu-system-x86_64 -nic bridge,br=''br1'',model=virtio-net-pci ''[...]''<br />
<br />
==== Creating bridge manually ====<br />
<br />
{{Style|This section needs serious cleanup and may contain out-of-date information.}}<br />
<br />
{{Tip|Since QEMU 1.1, the [https://wiki.qemu.org/Features/HelperNetworking network bridge helper] can set tun/tap up for you without the need for additional scripting. See [[#Bridged networking using qemu-bridge-helper]].}}<br />
<br />
The following describes how to bridge a virtual machine to a host interface such as {{ic|eth0}}, which is probably the most common configuration. This configuration makes it appear that the virtual machine is located directly on the external network, on the same Ethernet segment as the physical host machine.<br />
<br />
We will replace the normal Ethernet adapter with a bridge adapter and bind the normal Ethernet adapter to it.<br />
<br />
* Install {{Pkg|bridge-utils}}, which provides {{ic|brctl}} to manipulate bridges.<br />
<br />
* Enable IPv4 forwarding:<br />
<br />
# sysctl -w net.ipv4.ip_forward=1<br />
<br />
To make the change permanent, change {{ic|1=net.ipv4.ip_forward = 0}} to {{ic|1=net.ipv4.ip_forward = 1}} in {{ic|/etc/sysctl.d/99-sysctl.conf}}.<br />
<br />
* Load the {{ic|tun}} module and configure it to be loaded on boot. See [[Kernel modules]] for details.<br />
<br />
* Optionally create the bridge. See [[Bridge with netctl]] for details. Remember to name your bridge as {{ic|br0}}, or change the scripts below to your bridge's name. In the {{ic|run-qemu}} script below, {{ic|br0}} is set up if not listed, as it is assumed that by default the host is not accessing network via the bridge.<br />
<br />
* Create the script that QEMU uses to bring up the tap adapter with {{ic|root:kvm}} 750 permissions:<br />
<br />
{{hc|/etc/qemu-ifup|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifup"<br />
echo "Bringing up $1 for bridged mode..."<br />
sudo /usr/bin/ip link set $1 up promisc on<br />
echo "Adding $1 to br0..."<br />
sudo /usr/bin/brctl addif br0 $1<br />
sleep 2<br />
</nowiki>}}<br />
<br />
* Create the script that QEMU uses to bring down the tap adapter in {{ic|/etc/qemu-ifdown}} with {{ic|root:kvm}} 750 permissions:<br />
{{hc|/etc/qemu-ifdown|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifdown"<br />
sudo /usr/bin/ip link set $1 down<br />
sudo /usr/bin/brctl delif br0 $1<br />
sudo /usr/bin/ip link delete dev $1<br />
</nowiki>}}<br />
<br />
* Use {{ic|visudo}} to add the following to your {{ic|sudoers}} file:<br />
<br />
{{bc|<nowiki><br />
Cmnd_Alias QEMU=/usr/bin/ip,/usr/bin/modprobe,/usr/bin/brctl<br />
%kvm ALL=NOPASSWD: QEMU<br />
</nowiki>}}<br />
<br />
* You launch QEMU using the following {{ic|run-qemu}} script:<br />
<br />
{{hc|run-qemu|<nowiki><br />
#!/bin/bash<br />
: '<br />
e.g. with img created via:<br />
qemu-img create -f qcow2 example.img 90G<br />
run-qemu -cdrom archlinux-x86_64.iso -boot order=d -drive file=example.img,format=qcow2 -m 4G -enable-kvm -cpu host -smp 4<br />
run-qemu -drive file=example.img,format=qcow2 -m 4G -enable-kvm -cpu host -smp 4<br />
'<br />
<br />
nicbr0() {<br />
sudo ip link set dev $1 promisc on up &> /dev/null<br />
sudo ip addr flush dev $1 scope host &>/dev/null<br />
sudo ip addr flush dev $1 scope site &>/dev/null<br />
sudo ip addr flush dev $1 scope global &>/dev/null<br />
sudo ip link set dev $1 master br0 &> /dev/null<br />
}<br />
_nicbr0() {<br />
sudo ip link set $1 promisc off down &> /dev/null<br />
sudo ip link set dev $1 nomaster &> /dev/null<br />
}<br />
<br />
HASBR0="$( ip link show | grep br0 )"<br />
if [ -z $HASBR0 ] ; then<br />
ROUTER="192.168.1.1"<br />
SUBNET="192.168.1."<br />
NIC=$(ip link show | grep en | grep 'state UP' | head -n 1 | cut -d":" -f 2 | xargs)<br />
IPADDR=$(ip addr show | grep -o "inet $SUBNET\([0-9]*\)" | cut -d ' ' -f2)<br />
sudo ip link add name br0 type bridge &> /dev/null<br />
sudo ip link set dev br0 up<br />
sudo ip addr add $IPADDR/24 brd + dev br0<br />
sudo ip route del default &> /dev/null<br />
sudo ip route add default via $ROUTER dev br0 onlink<br />
nicbr0 $NIC<br />
sudo iptables -I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
fi<br />
<br />
USERID=$(whoami)<br />
precreationg=$(ip tuntap list | cut -d: -f1 | sort)<br />
sudo ip tuntap add user $USERID mode tap<br />
postcreation=$(ip tuntap list | cut -d: -f1 | sort)<br />
TAP=$(comm -13 <(echo "$precreationg") <(echo "$postcreation"))<br />
nicbr0 $TAP<br />
<br />
printf -v MACADDR "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
qemu-system-x86_64 -net nic,macaddr=$MACADDR,model=virtio \<br />
-net tap,ifname=$TAP,script=no,downscript=no,vhost=on \<br />
$@<br />
<br />
_nicbr0 $TAP<br />
sudo ip link set dev $TAP down &> /dev/null<br />
sudo ip tuntap del $TAP mode tap<br />
<br />
if [ -z $HASBR0 ] ; then<br />
_nicbr0 $NIC<br />
sudo ip addr del dev br0 $IPADDR/24 &> /dev/null<br />
sudo ip link set dev br0 down<br />
sudo ip link delete br0 type bridge &> /dev/null<br />
sudo ip route del default &> /dev/null<br />
sudo ip link set dev $NIC up<br />
sudo ip route add default via $ROUTER dev $NIC onlink &> /dev/null<br />
fi<br />
</nowiki>}}<br />
<br />
Then to launch a virtual machine, do something like this<br />
<br />
$ run-qemu -hda ''myvm.img'' -m 512<br />
<br />
* It is recommended for performance and security reasons to disable the [http://ebtables.netfilter.org/documentation/bridge-nf.html firewall on the bridge]:<br />
<br />
{{hc|/etc/sysctl.d/10-disable-firewall-on-bridge.conf|<nowiki><br />
net.bridge.bridge-nf-call-ip6tables = 0<br />
net.bridge.bridge-nf-call-iptables = 0<br />
net.bridge.bridge-nf-call-arptables = 0<br />
</nowiki>}}<br />
<br />
In order to apply the parameters described above on boot, you will also need to load the br-netfilter module on boot. Otherwise, the parameters will not exist when sysctl will try to modify them.<br />
<br />
{{hc|/etc/modules-load.d/br_netfilter.conf|<nowiki><br />
br_netfilter<br />
</nowiki>}}<br />
<br />
Run {{ic|sysctl -p /etc/sysctl.d/10-disable-firewall-on-bridge.conf}} to apply the changes immediately.<br />
<br />
See the [https://wiki.libvirt.org/page/Networking#Creating_network_initscripts libvirt wiki] and [https://bugzilla.redhat.com/show_bug.cgi?id=512206 Fedora bug 512206]. If you get errors by sysctl during boot about non-existing files, make the {{ic|bridge}} module load at boot. See [[Kernel module#systemd]].<br />
<br />
Alternatively, you can configure [[iptables]] to allow all traffic to be forwarded across the bridge by adding a rule like this:<br />
<br />
-I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Network sharing between physical device and a Tap device through iptables ====<br />
<br />
{{Merge|Internet_sharing|Duplication, not specific to QEMU.}}<br />
<br />
Bridged networking works fine between a wired interface (Eg. eth0), and it is easy to setup. However if the host gets connected to the network through a wireless device, then bridging is not possible.<br />
<br />
See [[Network bridge#Wireless interface on a bridge]] as a reference.<br />
<br />
One way to overcome that is to setup a tap device with a static IP, making linux automatically handle the routing for it, and then forward traffic between the tap interface and the device connected to the network through iptables rules.<br />
<br />
See [[Internet sharing]] as a reference.<br />
<br />
There you can find what is needed to share the network between devices, included tap and tun ones. The following just hints further on some of the host configurations required. As indicated in the reference above, the client needs to be configured for a static IP, using the IP assigned to the tap interface as the gateway. The caveat is that the DNS servers on the client might need to be manually edited if they change when changing from one host device connected to the network to another.<br />
<br />
To allow IP forwarding on every boot, one need to add the following lines to sysctl configuration file inside {{ic|/etc/sysctl.d}}:<br />
<br />
net.ipv4.ip_forward = 1<br />
net.ipv6.conf.default.forwarding = 1<br />
net.ipv6.conf.all.forwarding = 1<br />
<br />
The iptables rules can look like:<br />
<br />
# Forwarding from/to outside<br />
iptables -A FORWARD -i ${INT} -o ${EXT_0} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_1} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_2} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_0} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_1} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_2} -o ${INT} -j ACCEPT<br />
# NAT/Masquerade (network address translation)<br />
iptables -t nat -A POSTROUTING -o ${EXT_0} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_1} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_2} -j MASQUERADE<br />
<br />
The prior supposes there are 3 devices connected to the network sharing traffic with one internal device, where for example:<br />
<br />
INT=tap0<br />
EXT_0=eth0<br />
EXT_1=wlan0<br />
EXT_2=tun0<br />
<br />
The prior shows a forwarding that would allow sharing wired and wireless connections with the tap device.<br />
<br />
The forwarding rules shown are stateless, and for pure forwarding. One could think of restricting specific traffic, putting a firewall in place to protect the guest and others. However those would decrease the networking performance, while a simple bridge does not include any of that.<br />
<br />
Bonus: Whether the connection is wired or wireless, if one gets connected through VPN to a remote site with a tun device, supposing the tun device opened for that connection is tun0, and the prior iptables rules are applied, then the remote connection gets also shared with the guest. This avoids the need for the guest to also open a VPN connection. Again, as the guest networking needs to be static, then if connecting the host remotely this way, one most probably will need to edit the DNS servers on the guest.<br />
<br />
=== Networking with VDE2 ===<br />
<br />
{{Style|This section needs serious cleanup and may contain out-of-date information.}}<br />
<br />
==== What is VDE? ====<br />
<br />
VDE stands for Virtual Distributed Ethernet. It started as an enhancement of [[User-mode Linux|uml]]_switch. It is a toolbox to manage virtual networks.<br />
<br />
The idea is to create virtual switches, which are basically sockets, and to "plug" both physical and virtual machines in them. The configuration we show here is quite simple; However, VDE is much more powerful than this, it can plug virtual switches together, run them on different hosts and monitor the traffic in the switches. You are invited to read [https://wiki.virtualsquare.org/ the documentation of the project].<br />
<br />
The advantage of this method is you do not have to add sudo privileges to your users. Regular users should not be allowed to run modprobe.<br />
<br />
==== Basics ====<br />
<br />
VDE support can be [[install]]ed via the {{Pkg|vde2}} package.<br />
<br />
In our config, we use tun/tap to create a virtual interface on my host. Load the {{ic|tun}} module (see [[Kernel modules]] for details):<br />
<br />
# modprobe tun<br />
<br />
Now create the virtual switch:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
<br />
This line creates the switch, creates {{ic|tap0}}, "plugs" it, and allows the users of the group {{ic|users}} to use it.<br />
<br />
The interface is plugged in but not configured yet. To configure it, run this command:<br />
<br />
# ip addr add 192.168.100.254/24 dev tap0<br />
<br />
Now, you just have to run KVM with these {{ic|-net}} options as a normal user:<br />
<br />
$ qemu-system-x86_64 -net nic -net vde -hda ''[...]''<br />
<br />
Configure networking for your guest as you would do in a physical network.<br />
<br />
{{Tip|You might want to set up NAT on tap device to access the internet from the virtual machine. See [[Internet sharing#Enable NAT]] for more information.}}<br />
<br />
==== Startup scripts ====<br />
<br />
Example of main script starting VDE:<br />
<br />
{{hc|/etc/systemd/scripts/qemu-network-env|<nowiki><br />
#!/bin/sh<br />
# QEMU/VDE network environment preparation script<br />
<br />
# The IP configuration for the tap device that will be used for<br />
# the virtual machine network:<br />
<br />
TAP_DEV=tap0<br />
TAP_IP=192.168.100.254<br />
TAP_MASK=24<br />
TAP_NETWORK=192.168.100.0<br />
<br />
# Host interface<br />
NIC=eth0<br />
<br />
case "$1" in<br />
start)<br />
echo -n "Starting VDE network for QEMU: "<br />
<br />
# If you want tun kernel module to be loaded by script uncomment here<br />
#modprobe tun 2>/dev/null<br />
## Wait for the module to be loaded<br />
#while ! lsmod | grep -q "^tun"; do echo "Waiting for tun device"; sleep 1; done<br />
<br />
# Start tap switch<br />
vde_switch -tap "$TAP_DEV" -daemon -mod 660 -group users<br />
<br />
# Bring tap interface up<br />
ip address add "$TAP_IP"/"$TAP_MASK" dev "$TAP_DEV"<br />
ip link set "$TAP_DEV" up<br />
<br />
# Start IP Forwarding<br />
echo "1" > /proc/sys/net/ipv4/ip_forward<br />
iptables -t nat -A POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
;;<br />
stop)<br />
echo -n "Stopping VDE network for QEMU: "<br />
# Delete the NAT rules<br />
iptables -t nat -D POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
<br />
# Bring tap interface down<br />
ip link set "$TAP_DEV" down<br />
<br />
# Kill VDE switch<br />
pgrep vde_switch | xargs kill -TERM<br />
;;<br />
restart|reload)<br />
$0 stop<br />
sleep 1<br />
$0 start<br />
;;<br />
*)<br />
echo "Usage: $0 {start|stop|restart|reload}"<br />
exit 1<br />
esac<br />
exit 0<br />
</nowiki>}}<br />
<br />
Example of systemd service using the above script:<br />
<br />
{{hc|/etc/systemd/system/qemu-network-env.service|<nowiki><br />
[Unit]<br />
Description=Manage VDE Switch<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/etc/systemd/scripts/qemu-network-env start<br />
ExecStop=/etc/systemd/scripts/qemu-network-env stop<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
Change permissions for {{ic|qemu-network-env}} to be [[executable]]. <br />
<br />
You can [[start]] {{ic|qemu-network-env.service}} as usual.<br />
<br />
==== Alternative method ====<br />
<br />
If the above method does not work or you do not want to mess with kernel configs, TUN, dnsmasq, and iptables you can do the following for the same result.<br />
<br />
# vde_switch -daemon -mod 660 -group users<br />
# slirpvde --dhcp --daemon<br />
<br />
Then, to start the virtual machine with a connection to the network of the host:<br />
<br />
$ qemu-system-x86_64 -net nic,macaddr=52:54:00:00:EE:03 -net vde ''disk_image''<br />
<br />
=== VDE2 Bridge ===<br />
<br />
Based on [https://selamatpagicikgu.wordpress.com/2011/06/08/quickhowto-qemu-networking-using-vde-tuntap-and-bridge/ quickhowto: qemu networking using vde, tun/tap, and bridge] graphic. Any virtual machine connected to vde is externally exposed. For example, each virtual machine can receive DHCP configuration directly from your ADSL router.<br />
<br />
==== Basics ====<br />
<br />
Remember that you need {{ic|tun}} module and {{Pkg|bridge-utils}} package.<br />
<br />
Create the vde2/tap device:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
# ip link set tap0 up<br />
<br />
Create bridge:<br />
<br />
# brctl addbr br0<br />
<br />
Add devices:<br />
<br />
# brctl addif br0 eth0<br />
# brctl addif br0 tap0<br />
<br />
And configure bridge interface:<br />
<br />
# dhcpcd br0<br />
<br />
==== Startup scripts ====<br />
<br />
All devices must be set up. And only the bridge needs an IP address. For physical devices on the bridge (e.g. {{ic|eth0}}), this can be done with [[netctl]] using a custom Ethernet profile with:<br />
<br />
{{hc|/etc/netctl/ethernet-noip|2=<br />
Description='A more versatile static Ethernet connection'<br />
Interface=eth0<br />
Connection=ethernet<br />
IP=no<br />
}}<br />
<br />
The following custom systemd service can be used to create and activate a VDE2 tap interface for users in the {{ic|users}} user group.<br />
<br />
{{hc|/etc/systemd/system/vde2@.service|2=<br />
[Unit]<br />
Description=Network Connectivity for %i<br />
Wants=network.target<br />
Before=network.target<br />
<br />
[Service]<br />
Type=oneshot<br />
RemainAfterExit=yes<br />
ExecStart=/usr/bin/vde_switch -tap %i -daemon -mod 660 -group users<br />
ExecStart=/usr/bin/ip link set dev %i up<br />
ExecStop=/usr/bin/ip addr flush dev %i<br />
ExecStop=/usr/bin/ip link set dev %i down<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
}}<br />
<br />
And finally, you can create the [[Bridge with netctl|bridge interface with netctl]].<br />
<br />
=== Shorthand configuration ===<br />
<br />
If you are using QEMU with various networking options a lot, you probably have created a lot of {{ic|-netdev}} and {{ic|-device}} argument pairs, which gets quite repetitive. You can instead use the {{ic|-nic}} argument to combine {{ic|-netdev}} and {{ic|-device}} together, so that, for example, these arguments:<br />
<br />
-netdev tap,id=network0,ifname=tap0,script=no,downscript=no,vhost=on -device virtio-net-pci,netdev=network0<br />
<br />
become:<br />
<br />
-nic tap,script=no,downscript=no,vhost=on,model=virtio-net-pci<br />
<br />
Notice the lack of network IDs, and that the device was created with {{ic|1=model=}}. The first half of the {{ic|-nic}} parameters are {{ic|-netdev}} parameters, whereas the second half (after {{ic|1=model=}}) are related with the device. The same parameters (for example, {{ic|1=smb=}}) are used. To completely disable the networking use {{ic|-nic none}}.<br />
<br />
See [https://qemu.weilnetz.de/doc/6.0/system/net.html QEMU networking documentation] for more information on parameters you can use.<br />
<br />
== Graphic card ==<br />
<br />
QEMU can emulate a standard graphic card text mode using {{ic|-display curses}} command line option. This allows to type text and see text output directly inside a text terminal. Alternatively, {{ic|-nographic}} serves a similar purpose.<br />
<br />
QEMU can emulate several types of VGA card. The card type is passed in the {{ic|-vga ''type''}} command line option and can be {{ic|std}}, {{ic|qxl}}, {{ic|vmware}}, {{ic|virtio}}, {{ic|cirrus}} or {{ic|none}}.<br />
<br />
=== std ===<br />
<br />
With {{ic|-vga std}} you can get a resolution of up to 2560 x 1600 pixels without requiring guest drivers. This is the default since QEMU 2.2.<br />
<br />
=== qxl ===<br />
<br />
QXL is a paravirtual graphics driver with 2D support. To use it, pass the {{ic|-vga qxl}} option and install drivers in the guest. You may want to use [[#SPICE]] for improved graphical performance when using QXL.<br />
<br />
On Linux guests, the {{ic|qxl}} and {{ic|bochs_drm}} kernel modules must be loaded in order to gain a decent performance.<br />
<br />
Default VGA memory size for QXL devices is 16M which is sufficient to drive resolutions approximately up to QHD (2560x1440). To enable higher resolutions, [[#Multi-monitor support|increase vga_memmb]].<br />
<br />
=== vmware ===<br />
<br />
Although it is a bit buggy, it performs better than std and cirrus. Install the VMware drivers {{Pkg|xf86-video-vmware}} and {{Pkg|xf86-input-vmmouse}} for Arch Linux guests.<br />
<br />
=== virtio ===<br />
<br />
{{ic|virtio-vga}} / {{ic|virtio-gpu}} is a paravirtual 3D graphics driver based on [https://virgil3d.github.io/ virgl]. It's mature, currently supporting only Linux guests with {{Pkg|mesa}} compiled with the option {{ic|1=gallium-drivers=virgl}}.<br />
<br />
To enable 3D acceleration on the guest system, select this vga with {{ic|-device virtio-vga-gl}} and enable the OpenGL context in the display device with {{ic|1=-display sdl,gl=on}} or {{ic|1=-display gtk,gl=on}} for the SDL and GTK display output respectively. Successful configuration can be confirmed looking at the kernel log in the guest:<br />
<br />
{{hc|# dmesg {{!}} grep drm |<br />
[drm] pci: virtio-vga detected<br />
[drm] virgl 3d acceleration enabled<br />
}}<br />
<br />
=== cirrus ===<br />
<br />
The cirrus graphical adapter was the default [https://wiki.qemu.org/ChangeLog/2.2#VGA before 2.2]. It [https://www.kraxel.org/blog/2014/10/qemu-using-cirrus-considered-harmful/ should not] be used on modern systems.<br />
<br />
=== none ===<br />
<br />
This is like a PC that has no VGA card at all. You would not even be able to access it with the {{ic|-vnc}} option. Also, this is different from the {{ic|-nographic}} option which lets QEMU emulate a VGA card, but disables the SDL display.<br />
<br />
== SPICE ==<br />
<br />
The [https://www.spice-space.org/ SPICE project] aims to provide a complete open source solution for remote access to virtual machines in a seamless way.<br />
<br />
=== Enabling SPICE support on the host ===<br />
<br />
The following is an example of booting with SPICE as the remote desktop protocol, including the support for copy and paste from host:<br />
<br />
$ qemu-system-x86_64 -vga qxl -device virtio-serial-pci -spice port=5930,disable-ticketing=on -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
The parameters have the following meaning:<br />
<br />
# {{ic|-device virtio-serial-pci}} adds a virtio-serial device<br />
# {{ic|1=-spice port=5930,disable-ticketing=on}} set TCP port {{ic|5930}} for spice channels listening and allow client to connect without authentication{{Tip|Using [[wikipedia:Unix_socket|Unix sockets]] instead of TCP ports does not involve using network stack on the host system. It does not imply that packets are encapsulated and decapsulated to use the network and the related protocol. The sockets are identified solely by the inodes on the hard drive. It is therefore considered better for performance. Use instead {{ic|1=-spice unix=on,addr=/tmp/vm_spice.socket,disable-ticketing=on}}.}}<br />
# {{ic|1=-device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0}} opens a port for spice vdagent in the virtio-serial device,<br />
# {{ic|1=-chardev spicevmc,id=spicechannel0,name=vdagent}} adds a spicevmc chardev for that port. It is important that the {{ic|1=chardev=}} option of the {{ic|virtserialport}} device matches the {{ic|1=id=}} option given to the {{ic|chardev}} option ({{ic|spicechannel0}} in this example). It is also important that the port name is {{ic|com.redhat.spice.0}}, because that is the namespace where vdagent is looking for in the guest. And finally, specify {{ic|1=name=vdagent}} so that spice knows what this channel is for.<br />
<br />
=== Connecting to the guest with a SPICE client ===<br />
<br />
A SPICE client is necessary to connect to the guest. In Arch, the following clients are available:<br />
<br />
* {{App|virt-viewer|SPICE client recommended by the protocol developers, a subset of the virt-manager project.|https://virt-manager.org/|{{Pkg|virt-viewer}}}}<br />
* {{App|spice-gtk|SPICE GTK client, a subset of the SPICE project. Embedded into other applications as a widget.|https://www.spice-space.org/|{{Pkg|spice-gtk}}}}<br />
<br />
For clients that run on smartphone or on other platforms, refer to the ''Other clients'' section in [https://www.spice-space.org/download.html spice-space download].<br />
<br />
==== Manually running a SPICE client ====<br />
<br />
One way of connecting to a guest listening on Unix socket {{ic|/tmp/vm_spice.socket}} is to manually run the SPICE client using {{ic|$ remote-viewer spice+unix:///tmp/vm_spice.socket}} or {{ic|1=$ spicy --uri="spice+unix:///tmp/vm_spice.socket"}}, depending on the desired client. Since QEMU in SPICE mode acts similarly to a remote desktop server, it may be more convenient to run QEMU in daemon mode with the {{ic|-daemonize}} parameter.<br />
<br />
{{Tip|<br />
To connect to the guest through SSH tunneling, the following type of command can be used: {{bc|$ ssh -fL 5999:localhost:5930 ''my.domain.org'' sleep 10; spicy -h 127.0.0.1 -p 5999}}<br />
This example connects ''spicy'' to the local port {{ic|5999}} which is forwarded through SSH to the guest's SPICE server located at the address ''my.domain.org'', port {{ic|5930}}.<br />
Note the {{ic|-f}} option that requests ssh to execute the command {{ic|sleep 10}} in the background. This way, the ssh session runs while the client is active and auto-closes once the client ends.<br />
}}<br />
<br />
==== Running a SPICE client with QEMU ====<br />
<br />
QEMU can automatically start a SPICE client with an appropriate socket, if the display is set to SPICE with the {{ic|-display spice-app}} parameter. This will use the system's default SPICE client as the viewer, determined by your [[XDG MIME Applications#mimeapps.list|mimeapps.list]] files.<br />
<br />
=== Enabling SPICE support on the guest ===<br />
<br />
For '''Arch Linux guests''', for improved support for multiple monitors or clipboard sharing, the following packages should be installed:<br />
* {{Pkg|spice-vdagent}}: Spice agent xorg client that enables copy and paste between client and X-session and more. (Refer to this [https://github.com/systemd/systemd/issues/18791 issue], until fixed, for workarounds to get this to work on non-GNOME desktops.)<br />
* {{Pkg|xf86-video-qxl}}: Xorg X11 qxl video driver<br />
* {{AUR|x-resize}}: Desktop environments other than GNOME do not react automatically when the SPICE client window is resized. This package uses a [[udev]] rule and [[xrandr]] to implement auto-resizing for all X11-based desktop environments and window managers.<br />
For guests under '''other operating systems''', refer to the ''Guest'' section in spice-space [https://www.spice-space.org/download.html download].<br />
<br />
=== Password authentication with SPICE ===<br />
<br />
If you want to enable password authentication with SPICE you need to remove {{ic|disable-ticketing}} from the {{ic|-spice}} argument and instead add {{ic|1=password=''yourpassword''}}. For example:<br />
<br />
$ qemu-system-x86_64 -vga qxl -spice port=5900,password=''yourpassword'' -device virtio-serial-pci -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
Your SPICE client should now ask for the password to be able to connect to the SPICE server.<br />
<br />
=== TLS encrypted communication with SPICE ===<br />
<br />
You can also configure TLS encryption for communicating with the SPICE server. First, you need to have a directory which contains the following files (the names must be exactly as indicated):<br />
<br />
* {{ic|ca-cert.pem}}: the CA master certificate.<br />
* {{ic|server-cert.pem}}: the server certificate signed with {{ic|ca-cert.pem}}.<br />
* {{ic|server-key.pem}}: the server private key.<br />
<br />
An example of generation of self-signed certificates with your own generated CA for your server is shown in the [https://www.spice-space.org/spice-user-manual.html#_generating_self_signed_certificates Spice User Manual].<br />
<br />
Afterwards, you can run QEMU with SPICE as explained above but using the following {{ic|-spice}} argument: {{ic|1=-spice tls-port=5901,password=''yourpassword'',x509-dir=''/path/to/pki_certs''}}, where {{ic|''/path/to/pki_certs''}} is the directory path that contains the three needed files shown earlier.<br />
<br />
It is now possible to connect to the server using {{Pkg|virt-viewer}}:<br />
<br />
$ remote-viewer spice://''hostname''?tls-port=5901 --spice-ca-file=''/path/to/ca-cert.pem'' --spice-host-subject="C=''XX'',L=''city'',O=''organization'',CN=''hostname''" --spice-secure-channels=all<br />
<br />
Keep in mind that the {{ic|--spice-host-subject}} parameter needs to be set according to your {{ic|server-cert.pem}} subject. You also need to copy {{ic|ca-cert.pem}} to every client to verify the server certificate.<br />
<br />
{{Tip|You can get the subject line of the server certificate in the correct format for {{ic|--spice-host-subject}} (with entries separated by commas) using the following command: {{bc|<nowiki>$ openssl x509 -noout -subject -in server-cert.pem | cut -d' ' -f2- | sed 's/\///' | sed 's/\//,/g'</nowiki>}}<br />
}}<br />
<br />
The equivalent {{Pkg|spice-gtk}} command is:<br />
<br />
$ spicy -h ''hostname'' -s 5901 --spice-ca-file=ca-cert.pem --spice-host-subject="C=''XX'',L=''city'',O=''organization'',CN=''hostname''" --spice-secure-channels=all<br />
<br />
== VNC ==<br />
<br />
One can add the {{ic|-vnc :''X''}} option to have QEMU redirect the VGA display to the VNC session. Substitute {{ic|''X''}} for the number of the display (0 will then listen on 5900, 1 on 5901...).<br />
<br />
$ qemu-system-x86_64 -vnc :0<br />
<br />
An example is also provided in the [[#Starting QEMU virtual machines on boot]] section.<br />
<br />
{{Warning|The default VNC server setup does not use any form of authentication. Any user can connect from any host.}}<br />
<br />
=== Basic password authentication ===<br />
<br />
An access password can be setup easily by using the {{ic|password}} option. The password must be indicated in the QEMU monitor and connection is only possible once the password is provided.<br />
<br />
$ qemu-system-x86_64 -vnc :0,password -monitor stdio<br />
<br />
In the QEMU monitor, password is set using the command {{ic|change vnc password}} and then indicating the password.<br />
<br />
The following command line directly runs vnc with a password:<br />
<br />
$ printf "change vnc password\n%s\n" MYPASSWORD | qemu-system-x86_64 -vnc :0,password -monitor stdio<br />
<br />
{{Note|The password is limited to 8 characters and can be guessed through brute force attack. More elaborated protection is strongly recommended for public network.}}<br />
<br />
== Audio ==<br />
<br />
=== Creating an audio backend ===<br />
<br />
The {{ic|-audiodev}} flag sets the audio backend driver on the host and its options.<br />
<br />
To list availabe audio backend drivers:<br />
<br />
$ qemu-system-x86_64 -audiodev help<br />
<br />
Their optional settings are detailed in the {{man|1|qemu}} man page.<br />
<br />
At the bare minimum, one need to choose an audio backend and set an id, for [[PulseAudio]] for example:<br />
<br />
-audiodev pa,id=snd0<br />
<br />
=== Using the audio backend ===<br />
<br />
==== Intel HD Audio ====<br />
<br />
For Intel HD Audio emulation, add both controller and codec devices. To list the available Intel HDA Audio devices:<br />
<br />
$ qemu-system-x86_64 -device help | grep hda<br />
<br />
Add the audio controller:<br />
<br />
-device ich9-intel-hda<br />
<br />
Also add the audio codec and map it to a host audio backend id:<br />
<br />
-device hda-output,audiodev=snd0<br />
<br />
==== Intel 82801AA AC97 ====<br />
<br />
For AC97 emulation just add the audio card device and map it to a host audio backend id<br />
<br />
-device AC97,audiodev=snd0<br />
<br />
{{Note|<br />
* If the audiodev backend is not provided, QEMU looks up for it and adds it automatically, this only works for a single audiodev. For example {{ic|-device intel-hda -device hda-duplex}} will emulate {{ic|intel-hda}} on the guest using the default audiodev backend.<br />
* Video graphic card emulated drivers for the guest machine may also cause a problem with the sound quality. Test one by one to make it work. You can list possible options with {{ic|<nowiki>qemu-system-x86_64 -h | grep vga</nowiki>}}.<br />
}}<br />
<br />
==== VirtIO-Sound ====<br />
<br />
From QEMU 8.2.0 onwards, there is support for VirtIO sound, which in theory should be more efficient than previous emulation approaches. Example usage:<br />
<br />
-device virtio-sound-pci,audiodev=my_audiodev \<br />
-audiodev alsa,id=my_audiodev<br />
<br />
More information can be found [https://qemu-project.gitlab.io/qemu/system/devices/virtio-snd.html here].<br />
<br />
== Installing virtio drivers ==<br />
<br />
QEMU offers guests the ability to use paravirtualized block and network devices using the [https://wiki.libvirt.org/page/Virtio virtio] drivers, which provide better performance and lower overhead.<br />
<br />
* A virtio block device requires the option {{ic|-drive}} for passing a disk image, with parameter {{ic|1=if=virtio}}:<br />
$ qemu-system-x86_64 -drive file=''disk_image'',if='''virtio'''<br />
<br />
* Almost the same goes for the network:<br />
$ qemu-system-x86_64 -nic user,model='''virtio-net-pci'''<br />
<br />
{{Note|This will only work if the guest machine has drivers for virtio devices. Linux does, and the required drivers are included in Arch Linux, but there is no guarantee that virtio devices will work with other operating systems.}}<br />
<br />
=== Preparing an Arch Linux guest ===<br />
<br />
To use virtio devices after an Arch Linux guest has been installed, the following modules must be loaded in the guest: {{ic|virtio}}, {{ic|virtio_pci}}, {{ic|virtio_blk}}, {{ic|virtio_net}}, and {{ic|virtio_ring}}. For 32-bit guests, the specific "virtio" module is not necessary.<br />
<br />
If you want to boot from a virtio disk, the initial ramdisk must contain the necessary modules. By default, this is handled by [[mkinitcpio]]'s {{ic|autodetect}} hook. Otherwise use the {{ic|MODULES}} array in {{ic|/etc/mkinitcpio.conf}} to include the necessary modules and rebuild the initial ramdisk.<br />
<br />
{{hc|/etc/mkinitcpio.conf|2=<br />
MODULES=(virtio virtio_blk virtio_pci virtio_net)}}<br />
<br />
Virtio disks are recognized with the prefix {{ic|'''v'''}} (e.g. {{ic|'''v'''da}}, {{ic|'''v'''db}}, etc.); therefore, changes must be made in at least {{ic|/etc/fstab}} and {{ic|/boot/grub/grub.cfg}} when booting from a virtio disk.<br />
<br />
{{Tip|When referencing disks by [[UUID]] in both {{ic|/etc/fstab}} and boot loader, nothing has to be done.}}<br />
<br />
Further information on paravirtualization with KVM can be found [https://www.linux-kvm.org/page/Boot_from_virtio_block_device here].<br />
<br />
You might also want to install {{Pkg|qemu-guest-agent}} to implement support for QMP commands that will enhance the hypervisor management capabilities.<br />
<br />
=== Preparing a Windows guest ===<br />
<br />
==== Virtio drivers for Windows ====<br />
<br />
Windows does not come with the virtio drivers. The latest and stable versions of the drivers are regularly built by Fedora, details on downloading the drivers are given on [https://github.com/virtio-win/virtio-win-pkg-scripts/blob/master/README.md virtio-win on GitHub]. In the following sections we will mostly use the stable ISO file provided here: [https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/stable-virtio/virtio-win.iso virtio-win.iso]. Alternatively, use {{AUR|virtio-win}}.<br />
<br />
==== Block device drivers ====<br />
<br />
===== New Install of Windows =====<br />
<br />
The drivers need to be loaded during installation, the procedure is to load the ISO image with the virtio drivers in a cdrom device along with the primary disk device and the Windows ISO install media:<br />
<br />
$ qemu-system-x86_64 ... \<br />
-drive file=''disk_image'',index=0,media=disk,if=virtio \<br />
-drive file=''windows.iso'',index=2,media=cdrom \<br />
-drive file=''virtio-win.iso'',index=3,media=cdrom \<br />
...<br />
<br />
During the installation, at some stage, the Windows installer will ask "Where do you want to install Windows?", it will give a warning that no disks are found. Follow the example instructions below (based on Windows Server 2012 R2 with Update).<br />
<br />
* Select the option ''Load Drivers''.<br />
* Uncheck the box for ''Hide drivers that are not compatible with this computer's hardware''.<br />
* Click the browse button and open the CDROM for the virtio iso, usually named "virtio-win-XX".<br />
* Now browse to {{ic|E:\viostor\[your-os]\amd64}}, select it, and confirm.<br />
<br />
You should now see your virtio disk(s) listed here, ready to be selected, formatted and installed to.<br />
<br />
===== Change existing Windows virtual machine to use virtio =====<br />
<br />
Modifying an existing Windows guest for booting from virtio disk requires that the virtio driver is loaded by the guest at boot time.<br />
We will therefore need to teach Windows to load the virtio driver at boot time before being able to boot a disk image in virtio mode.<br />
<br />
To achieve that, first create a new disk image that will be attached in virtio mode and trigger the search for the driver:<br />
<br />
$ qemu-img create -f qcow2 ''dummy.qcow2'' 1G<br />
<br />
Run the original Windows guest with the boot disk still in IDE mode, the fake disk in virtio mode and the driver ISO image.<br />
<br />
$ qemu-system-x86_64 -m 4G -drive file=''disk_image'',if=ide -drive file=''dummy.qcow2'',if=virtio -cdrom virtio-win.iso<br />
<br />
Windows will detect the fake disk and look for a suitable driver. If it fails, go to ''Device Manager'', locate the SCSI drive with an exclamation mark icon (should be open), click ''Update driver'' and select the virtual CD-ROM. Do not navigate to the driver folder within the CD-ROM, simply select the CD-ROM drive and Windows will find the appropriate driver automatically (tested for Windows 7 SP1).<br />
<br />
Request Windows to boot in safe mode next time it starts up. This can be done using the ''msconfig.exe'' tool in Windows. In safe mode all the drivers will be loaded at boot time including the new virtio driver. Once Windows knows that the virtio driver is required at boot it will memorize it for future boot.<br />
<br />
Once instructed to boot in safe mode, you can turn off the virtual machine and launch it again, now with the boot disk attached in virtio mode:<br />
<br />
$ qemu-system-x86_64 -m 4G -drive file=''disk_image'',if=virtio<br />
<br />
You should boot in safe mode with virtio driver loaded, you can now return to ''msconfig.exe'' disable safe mode boot and restart Windows.<br />
<br />
{{Note|If you encounter the blue screen of death using the {{ic|1=if=virtio}} parameter, it probably means the virtio disk driver is not installed or not loaded at boot time, reboot in safe mode and check your driver configuration.}}<br />
<br />
==== Network drivers ====<br />
<br />
Installing virtio network drivers is a bit easier, simply add the {{ic|-nic}} argument.<br />
<br />
$ qemu-system-x86_64 -m 4G -drive file=''windows_disk_image'',if=virtio -nic user,model=virtio-net-pci -cdrom virtio-win.iso<br />
<br />
Windows will detect the network adapter and try to find a driver for it. If it fails, go to the ''Device Manager'', locate the network adapter with an exclamation mark icon (should be open), click ''Update driver'' and select the virtual CD-ROM. Do not forget to select the checkbox which says to search for directories recursively.<br />
<br />
==== Balloon driver ====<br />
<br />
If you want to track you guest memory state (for example via {{ic|virsh}} command {{ic|dommemstat}}) or change guest's memory size in runtime (you still will not be able to change memory size, but can limit memory usage via inflating balloon driver) you will need to install guest balloon driver.<br />
<br />
For this you will need to go to ''Device Manager'', locate ''PCI standard RAM Controller'' in ''System devices'' (or unrecognized PCI controller from ''Other devices'') and choose ''Update driver''. In opened window you will need to choose ''Browse my computer...'' and select the CD-ROM (and do not forget the ''Include subdirectories'' checkbox). Reboot after installation. This will install the driver and you will be able to inflate the balloon (for example via hmp command {{ic|balloon ''memory_size''}}, which will cause balloon to take as much memory as possible in order to shrink the guest's available memory size to ''memory_size''). However, you still will not be able to track guest memory state. In order to do this you will need to install ''Balloon'' service properly. For that open command line as administrator, go to the CD-ROM, ''Balloon'' directory and deeper, depending on your system and architecture. Once you are in ''amd64'' (''x86'') directory, run {{ic|blnsrv.exe -i}} which will do the installation. After that {{ic|virsh}} command {{ic|dommemstat}} should be outputting all supported values.<br />
<br />
=== Preparing a FreeBSD guest ===<br />
<br />
Install the {{ic|emulators/virtio-kmod}} port if you are using FreeBSD 8.3 or later up until 10.0-CURRENT where they are included into the kernel. After installation, add the following to your {{ic|/boot/loader.conf}} file:<br />
<br />
{{bc|1=<br />
virtio_load="YES"<br />
virtio_pci_load="YES"<br />
virtio_blk_load="YES"<br />
if_vtnet_load="YES"<br />
virtio_balloon_load="YES"<br />
}}<br />
<br />
Then modify your {{ic|/etc/fstab}} by doing the following:<br />
<br />
# sed -ibak "s/ada/vtbd/g" /etc/fstab<br />
<br />
And verify that {{ic|/etc/fstab}} is consistent. If anything goes wrong, just boot into a rescue CD and copy {{ic|/etc/fstab.bak}} back to {{ic|/etc/fstab}}.<br />
<br />
== QEMU monitor ==<br />
<br />
While QEMU is running, a monitor console is provided in order to provide several ways to interact with the virtual machine running. The QEMU monitor offers interesting capabilities such as obtaining information about the current virtual machine, hotplugging devices, creating snapshots of the current state of the virtual machine, etc. To see the list of all commands, run {{ic|help}} or {{ic|?}} in the QEMU monitor console or review the relevant section of the [https://www.qemu.org/docs/master/system/monitor.html official QEMU documentation].<br />
<br />
=== Accessing the monitor console ===<br />
<br />
==== Graphical view ====<br />
<br />
When using the {{ic|std}} default graphics option, one can access the QEMU monitor by pressing {{ic|Ctrl+Alt+2}} or by clicking ''View > compatmonitor0'' in the QEMU window. To return to the virtual machine graphical view either press {{ic|Ctrl+Alt+1}} or click ''View > VGA''.<br />
<br />
However, the standard method of accessing the monitor is not always convenient and does not work in all graphic outputs QEMU supports.<br />
<br />
==== Telnet ====<br />
<br />
To enable [[telnet]], run QEMU with the {{ic|-monitor telnet:127.0.0.1:''port'',server,nowait}} parameter. When the virtual machine is started you will be able to access the monitor via telnet:<br />
<br />
$ telnet 127.0.0.1 ''port''<br />
<br />
{{Note|If {{ic|127.0.0.1}} is specified as the IP to listen it will be only possible to connect to the monitor from the same host QEMU is running on. If connecting from remote hosts is desired, QEMU must be told to listen {{ic|0.0.0.0}} as follows: {{ic|-monitor telnet:0.0.0.0:''port'',server,nowait}}. Keep in mind that it is recommended to have a [[firewall]] configured in this case or make sure your local network is completely trustworthy since this connection is completely unauthenticated and unencrypted.}}<br />
<br />
==== UNIX socket ====<br />
<br />
Run QEMU with the {{ic|-monitor unix:''socketfile'',server,nowait}} parameter. Then you can connect with either {{Pkg|socat}}, {{Pkg|nmap}} or {{Pkg|openbsd-netcat}}.<br />
<br />
For example, if QEMU is run via:<br />
<br />
$ qemu-system-x86_64 -monitor unix:/tmp/monitor.sock,server,nowait ''[...]''<br />
<br />
It is possible to connect to the monitor with:<br />
<br />
$ socat - UNIX-CONNECT:/tmp/monitor.sock<br />
<br />
Or with:<br />
<br />
$ nc -U /tmp/monitor.sock<br />
<br />
Alternatively with {{Pkg|nmap}}:<br />
<br />
$ ncat -U /tmp/monitor.sock<br />
<br />
==== TCP ====<br />
<br />
You can expose the monitor over TCP with the argument {{ic|-monitor tcp:127.0.0.1:''port'',server,nowait}}. Then connect with netcat, either {{Pkg|openbsd-netcat}} or {{Pkg|gnu-netcat}} by running:<br />
<br />
$ nc 127.0.0.1 ''port''<br />
<br />
{{Note|In order to be able to connect to the tcp socket from other devices other than the same host QEMU is being run on you need to listen to {{ic|0.0.0.0}} like explained in the telnet case. The same security warnings apply in this case as well.}}<br />
<br />
==== Standard I/O ====<br />
<br />
It is possible to access the monitor automatically from the same terminal QEMU is being run by running it with the argument {{ic|-monitor stdio}}.<br />
<br />
=== Sending keyboard presses to the virtual machine using the monitor console ===<br />
<br />
Some combinations of keys may be difficult to perform on virtual machines due to the host intercepting them instead in some configurations (a notable example is the {{ic|Ctrl+Alt+F*}} key combinations, which change the active tty). To avoid this problem, the problematic combination of keys may be sent via the monitor console instead. Switch to the monitor and use the {{ic|sendkey}} command to forward the necessary keypresses to the virtual machine. For example:<br />
<br />
(qemu) sendkey ctrl-alt-f2<br />
<br />
=== Creating and managing snapshots via the monitor console ===<br />
<br />
{{Note|This feature will '''only''' work when the virtual machine disk image is in ''qcow2'' format. It will not work with ''raw'' images.}}<br />
<br />
It is sometimes desirable to save the current state of a virtual machine and having the possibility of reverting the state of the virtual machine to that of a previously saved snapshot at any time. The QEMU monitor console provides the user with the necessary utilities to create snapshots, manage them, and revert the machine state to a saved snapshot.<br />
<br />
* Use {{ic|savevm ''name''}} in order to create a snapshot with the tag ''name''.<br />
* Use {{ic|loadvm ''name''}} to revert the virtual machine to the state of the snapshot ''name''.<br />
* Use {{ic|delvm ''name''}} to delete the snapshot tagged as ''name''.<br />
* Use {{ic|info snapshots}} to see a list of saved snapshots. Snapshots are identified by both an auto-incremented ID number and a text tag (set by the user on snapshot creation).<br />
<br />
=== Running the virtual machine in immutable mode ===<br />
<br />
It is possible to run a virtual machine in a frozen state so that all changes will be discarded when the virtual machine is powered off just by running QEMU with the {{ic|-snapshot}} parameter. When the disk image is written by the guest, changes will be saved in a temporary file in {{ic|/tmp}} and will be discarded when QEMU halts.<br />
<br />
However, if a machine is running in frozen mode it is still possible to save the changes to the disk image if it is afterwards desired by using the monitor console and running the following command:<br />
<br />
(qemu) commit all<br />
<br />
If snapshots are created when running in frozen mode they will be discarded as soon as QEMU is exited unless changes are explicitly commited to disk, as well.<br />
<br />
=== Pause and power options via the monitor console ===<br />
<br />
Some operations of a physical machine can be emulated by QEMU using some monitor commands:<br />
<br />
* {{ic|system_powerdown}} will send an ACPI shutdown request to the virtual machine. This effect is similar to the power button in a physical machine.<br />
* {{ic|system_reset}} will reset the virtual machine similarly to a reset button in a physical machine. This operation can cause data loss and file system corruption since the virtual machine is not cleanly restarted.<br />
* {{ic|stop}} will pause the virtual machine.<br />
* {{ic|cont}} will resume a virtual machine previously paused.<br />
<br />
=== Taking screenshots of the virtual machine ===<br />
<br />
Screenshots of the virtual machine graphic display can be obtained in the PPM format by running the following command in the monitor console:<br />
<br />
(qemu) screendump ''file.ppm''<br />
<br />
== QEMU machine protocol ==<br />
<br />
The QEMU machine protocol (QMP) is a JSON-based protocol which allows applications to control a QEMU instance. Similarly to the [[#QEMU monitor]] it offers ways to interact with a running machine and the JSON protocol allows to do it programmatically. The description of all the QMP commands can be found in [https://raw.githubusercontent.com/coreos/qemu/master/qmp-commands.hx qmp-commands].<br />
<br />
=== Start QMP ===<br />
<br />
The usual way to control the guest using the QMP protocol, is to open a TCP socket when launching the machine using the {{ic|-qmp}} option. Here it is using for example the TCP port 4444:<br />
<br />
$ qemu-system-x86_64 ''[...]'' -qmp tcp:localhost:4444,server,nowait<br />
<br />
Then one way to communicate with the QMP agent is to use [[netcat]]:<br />
<br />
{{hc|nc localhost 4444|{"QMP": {"version": {"qemu": {"micro": 0, "minor": 1, "major": 3}, "package": ""}, "capabilities": []} } }}<br />
<br />
At this stage, the only command that can be recognized is {{ic|qmp_capabilities}}, so that QMP enters into command mode. Type:<br />
<br />
{"execute": "qmp_capabilities"}<br />
<br />
Now, QMP is ready to receive commands, to retrieve the list of recognized commands, use:<br />
<br />
{"execute": "query-commands"}<br />
<br />
=== Live merging of child image into parent image ===<br />
<br />
It is possible to merge a running snapshot into its parent by issuing a {{ic|block-commit}} command. In its simplest form the following line will commit the child into its parent:<br />
<br />
{"execute": "block-commit", "arguments": {"device": "''devicename''"}}<br />
<br />
Upon reception of this command, the handler looks for the base image and converts it from read only to read write mode and then runs the commit job.<br />
<br />
Once the ''block-commit'' operation has completed, the event {{ic|BLOCK_JOB_READY}} will be emitted, signalling that the synchronization has finished. The job can then be gracefully completed by issuing the command {{ic|block-job-complete}}:<br />
<br />
{"execute": "block-job-complete", "arguments": {"device": "''devicename''"}}<br />
<br />
Until such a command is issued, the ''commit'' operation remains active.<br />
After successful completion, the base image remains in read write mode and becomes the new active layer. On the other hand, the child image becomes invalid and it is the responsibility of the user to clean it up.<br />
<br />
{{Tip|The list of device and their names can be retrieved by executing the command {{ic|query-block}} and parsing the results. The device name is in the {{ic|device}} field, for example {{ic|ide0-hd0}} for the hard disk in this example: {{hc|{"execute": "query-block"}|{"return": [{"io-status": "ok", "device": "'''ide0-hd0'''", "locked": false, "removable": false, "inserted": {"iops_rd": 0, "detect_zeroes": "off", "image": {"backing-image": {"virtual-size": 27074281472, "filename": "parent.qcow2", ... } }} }}<br />
<br />
=== Live creation of a new snapshot ===<br />
<br />
To create a new snapshot out of a running image, run the command:<br />
<br />
{"execute": "blockdev-snapshot-sync", "arguments": {"device": "''devicename''","snapshot-file": "''new_snapshot_name''.qcow2"}}<br />
<br />
This creates an overlay file named {{ic|''new_snapshot_name''.qcow2}} which then becomes the new active layer.<br />
<br />
== Tips and tricks ==<br />
<br />
=== Improve virtual machine performance ===<br />
<br />
There are a number of techniques that you can use to improve the performance of the virtual machine. For example:<br />
<br />
* Apply [[#Enabling KVM]] for full virtualization.<br />
* Use the {{ic|-cpu host}} option to make QEMU emulate the host's exact CPU rather than a more generic CPU.<br />
* Especially for Windows guests, enable [https://blog.wikichoon.com/2014/07/enabling-hyper-v-enlightenments-with-kvm.html Hyper-V enlightenments]: {{ic|1=-cpu host,hv_relaxed,hv_spinlocks=0x1fff,hv_vapic,hv_time}}. See the [https://www.qemu.org/docs/master/system/i386/hyperv.html QEMU documentation] for more information and flags.<br />
* multiple cores can be assigned to the guest using the {{ic|-smp cores{{=}}x,threads{{=}}y,sockets{{=}}1,maxcpus{{=}}z}} option. The threads parameter is used to assign [https://www.tomshardware.com/reviews/simultaneous-multithreading-definition,5762.html SMT cores]. Leaving a physical core for QEMU, the hypervisor and the host system to operate unimpeded is highly beneficial.<br />
* Make sure you have assigned the virtual machine enough memory. By default, QEMU only assigns 128 MiB of memory to each virtual machine. Use the {{ic|-m}} option to assign more memory. For example, {{ic|-m 1024}} runs a virtual machine with 1024 MiB of memory.<br />
* If supported by drivers in the guest operating system, use virtio for network and/or block devices, see [[#Installing virtio drivers]].<br />
* Use TAP devices instead of user-mode networking, see [[#Tap networking with QEMU]].<br />
* If the guest OS is doing heavy writing to its disk, you may benefit from certain mount options on the host's file system. For example, you can mount an [[Ext4|ext4 file system]] with the option {{ic|1=barrier=0}}. You should read the documentation for any options that you change because sometimes performance-enhancing options for file systems come at the cost of data integrity.<br />
* If you have a raw disk or partition, you may want to disable the cache: {{bc|1=$ qemu-system-x86_64 -drive file=/dev/''disk'',if=virtio,'''cache=none'''}}<br />
* Use the native Linux AIO: {{bc|1=$ qemu-system-x86_64 -drive file=''disk_image'',if=virtio''',aio=native,cache.direct=on'''}}<br />
* If you are running multiple virtual machines concurrently that all have the same operating system installed, you can save memory by enabling [[wikipedia:Kernel_SamePage_Merging_(KSM)|kernel same-page merging]]. See [[#Enabling KSM]].<br />
* In some cases, memory can be reclaimed from running virtual machines by running a memory ballooning driver in the guest operating system and launching QEMU using {{ic|-device virtio-balloon}}.<br />
* It is possible to use a emulation layer for an ICH-9 AHCI controller (although it may be unstable). The AHCI emulation supports [[Wikipedia:Native_Command_Queuing|NCQ]], so multiple read or write requests can be outstanding at the same time: {{bc|1=$ qemu-system-x86_64 -drive id=disk,file=''disk_image'',if=none -device ich9-ahci,id=ahci -device ide-drive,drive=disk,bus=ahci.0}}<br />
<br />
See https://www.linux-kvm.org/page/Tuning_KVM for more information.<br />
<br />
=== Starting QEMU virtual machines on boot ===<br />
<br />
==== With libvirt ====<br />
<br />
If a virtual machine is set up with [[libvirt]], it can be configured with {{ic|virsh autostart}} or through the ''virt-manager'' GUI to start at host boot by going to the Boot Options for the virtual machine and selecting "Start virtual machine on host boot up".<br />
<br />
==== With systemd service ====<br />
<br />
To run QEMU virtual machines on boot, you can use following systemd unit and config.<br />
<br />
{{hc|/etc/systemd/system/qemu@.service|2=<br />
[Unit]<br />
Description=QEMU virtual machine<br />
<br />
[Service]<br />
Environment="haltcmd=kill -INT $MAINPID"<br />
EnvironmentFile=/etc/conf.d/qemu.d/%i<br />
ExecStart=/usr/bin/qemu-system-x86_64 -name %i -enable-kvm -m 512 -nographic $args<br />
ExecStop=/usr/bin/bash -c ${haltcmd}<br />
ExecStop=/usr/bin/bash -c 'while nc localhost 7100; do sleep 1; done'<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
}}<br />
<br />
{{Note|This service will wait for the console port to be released, which means that the virtual machine has been shutdown, to graciously end.}}<br />
<br />
Then create per-VM configuration files, named {{ic|/etc/conf.d/qemu.d/''vm_name''}}, with the variables {{ic|args}} and {{ic|haltcmd}} set. Example configs:<br />
<br />
{{hc|/etc/conf.d/qemu.d/one|2=<br />
args="-hda /dev/vg0/vm1 -serial telnet:localhost:7000,server,nowait,nodelay \<br />
-monitor telnet:localhost:7100,server,nowait,nodelay -vnc :0"<br />
<br />
haltcmd="echo 'system_powerdown' {{!}} nc localhost 7100" # or netcat/ncat}}<br />
<br />
{{hc|/etc/conf.d/qemu.d/two|2=<br />
args="-hda /srv/kvm/vm2 -serial telnet:localhost:7001,server,nowait,nodelay -vnc :1"<br />
<br />
haltcmd="ssh powermanager@vm2 sudo poweroff"}}<br />
<br />
The description of the variables is the following:<br />
<br />
* {{ic|args}} - QEMU command line arguments to be used.<br />
* {{ic|haltcmd}} - Command to shut down a virtual machine safely. In the first example, the QEMU monitor is exposed via telnet using {{ic|-monitor telnet:..}} and the virtual machines are powered off via ACPI by sending {{ic|system_powerdown}} to monitor with the {{ic|nc}} command. In the other example, SSH is used.<br />
<br />
To set which virtual machines will start on boot-up, [[enable]] the {{ic|qemu@''vm_name''.service}} systemd unit.<br />
<br />
=== Mouse integration ===<br />
<br />
To prevent the mouse from being grabbed when clicking on the guest operating system's window, add the options {{ic|-usb -device usb-tablet}}. This means QEMU is able to report the mouse position without having to grab the mouse. This also overrides PS/2 mouse emulation when activated. For example:<br />
<br />
$ qemu-system-x86_64 -hda ''disk_image'' -m 512 -usb -device usb-tablet<br />
<br />
If that does not work, try using {{ic|-vga qxl}} parameter, also look at the instructions [[#Mouse cursor is jittery or erratic]].<br />
<br />
=== Pass-through host USB device ===<br />
<br />
It is possible to access the physical device connected to a USB port of the host from the guest. The first step is to identify where the device is connected, this can be found running the {{ic|lsusb}} command. For example:<br />
<br />
{{hc|$ lsusb|<br />
...<br />
Bus '''003''' Device '''007''': ID '''0781''':'''5406''' SanDisk Corp. Cruzer Micro U3<br />
}}<br />
<br />
The outputs in bold above will be useful to identify respectively the ''host_bus'' and ''host_addr'' or the ''vendor_id'' and ''product_id''.<br />
<br />
In qemu, the idea is to emulate an EHCI (USB 2) or XHCI (USB 1.1 USB 2 USB 3) controller with the option {{ic|1=-device usb-ehci,id=ehci}} or {{ic|1=-device qemu-xhci,id=xhci}} respectively and then attach the physical device to it with the option {{ic|1=-device usb-host,..}}. We will consider that ''controller_id'' is either {{ic|ehci}} or {{ic|xhci}} for the rest of this section.<br />
<br />
Then, there are two ways to connect to the USB of the host with qemu:<br />
<br />
# Identify the device and connect to it on any bus and address it is attached to on the host, the generic syntax is: {{bc|1=-device usb-host,bus=''controller_id''.0,vendorid=0x''vendor_id'',productid=0x''product_id''}}Applied to the device used in the example above, it becomes:{{bc|1=-device usb-ehci,id=ehci -device usb-host,bus=ehci.0,vendorid=0x'''0781''',productid=0x'''5406'''}}One can also add the {{ic|1=...,port=''port_number''}} setting to the previous option to specify in which physical port of the virtual controller the device should be attached, useful in the case one wants to add multiple USB devices to the virtual machine. Another option is to use the new {{ic|hostdevice}} property of {{ic|usb-host}} which is available since QEMU 5.1.0, the syntax is: {{bc|1=-device qemu-xhci,id=xhci -device usb-host,hostdevice=/dev/bus/usb/003/007}}<br />
# Attach whatever is connected to a given USB bus and address, the syntax is:{{bc|1=-device usb-host,bus=''controller_id''.0,hostbus=''host_bus'',host_addr=''host_addr''}}Applied to the bus and the address in the example above, it becomes:{{bc|1=-device usb-ehci,id=ehci -device usb-host,bus=ehci.0,hostbus='''3''',hostaddr='''7'''}}<br />
See [https://www.qemu.org/docs/master/system/devices/usb.html QEMU/USB emulation] for more information.<br />
{{Note|If you encounter permission errors when running QEMU, see [[udev#About udev rules]] for information on how to set permissions of the device.}}<br />
<br />
=== USB redirection with SPICE ===<br />
<br />
When using [[#SPICE]] it is possible to redirect USB devices from the client to the virtual machine without needing to specify them in the QEMU command. It is possible to configure the number of USB slots available for redirected devices (the number of slots will determine the maximum number of devices which can be redirected simultaneously). The main advantages of using SPICE for redirection compared to the previously-mentioned {{ic|-usbdevice}} method is the possibility of hot-swapping USB devices after the virtual machine has started, without needing to halt it in order to remove USB devices from the redirection or adding new ones. This method of USB redirection also allows us to redirect USB devices over the network, from the client to the server. In summary, it is the most flexible method of using USB devices in a QEMU virtual machine.<br />
<br />
We need to add one EHCI/UHCI controller per available USB redirection slot desired as well as one SPICE redirection channel per slot. For example, adding the following arguments to the QEMU command you use for starting the virtual machine in SPICE mode will start the virtual machine with three available USB slots for redirection:<br />
<br />
{{bc|1=<br />
-device ich9-usb-ehci1,id=usb \<br />
-device ich9-usb-uhci1,masterbus=usb.0,firstport=0,multifunction=on \<br />
-device ich9-usb-uhci2,masterbus=usb.0,firstport=2 \<br />
-device ich9-usb-uhci3,masterbus=usb.0,firstport=4 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev1 -device usb-redir,chardev=usbredirchardev1,id=usbredirdev1 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev2 -device usb-redir,chardev=usbredirchardev2,id=usbredirdev2 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev3 -device usb-redir,chardev=usbredirchardev3,id=usbredirdev3<br />
}}<br />
<br />
See [https://www.spice-space.org/usbredir.html SPICE/usbredir] for more information.<br />
<br />
Both {{ic|spicy}} from {{Pkg|spice-gtk}} (''Input > Select USB Devices for redirection'') and {{ic|remote-viewer}} from {{Pkg|virt-viewer}} (''File > USB device selection'') support this feature. Please make sure that you have installed the necessary SPICE Guest Tools on the virtual machine for this functionality to work as expected (see the [[#SPICE]] section for more information).<br />
<br />
{{Warning|Keep in mind that when a USB device is redirected from the client, it will not be usable from the client operating system itself until the redirection is stopped. It is specially important to never redirect the input devices (namely mouse and keyboard), since it will be then difficult to access the SPICE client menus to revert the situation, because the client will not respond to the input devices after being redirected to the virtual machine.}}<br />
<br />
==== Automatic USB forwarding with udev ====<br />
<br />
Normally, forwarded devices must be available at the boot time of the virtual machine to be forwarded. If that device is disconnected, it will not be forwarded anymore.<br />
<br />
You can use [[udev rule]]s to automatically attach a device when it comes online. Create a {{ic|hostdev}} entry somewhere on disk. [[chown]] it to root to prevent other users modifying it.<br />
<br />
{{hc|/usr/local/hostdev-mydevice.xml|2=<br />
<hostdev mode='subsystem' type='usb'><br />
<source><br />
<vendor id='0x03f0'/><br />
<product id='0x4217'/><br />
</source><br />
</hostdev><br />
}}<br />
<br />
Then create a ''udev'' rule which will attach/detach the device:<br />
<br />
{{hc|/usr/lib/udev/rules.d/90-libvirt-mydevice|2=<br />
ACTION=="add", \<br />
SUBSYSTEM=="usb", \<br />
ENV{ID_VENDOR_ID}=="03f0", \<br />
ENV{ID_MODEL_ID}=="4217", \<br />
RUN+="/usr/bin/virsh attach-device GUESTNAME /usr/local/hostdev-mydevice.xml"<br />
ACTION=="remove", \<br />
SUBSYSTEM=="usb", \<br />
ENV{ID_VENDOR_ID}=="03f0", \<br />
ENV{ID_MODEL_ID}=="4217", \<br />
RUN+="/usr/bin/virsh detach-device GUESTNAME /usr/local/hostdev-mydevice.xml"<br />
}}<br />
<br />
[https://rolandtapken.de/blog/2011-04/how-auto-hotplug-usb-devices-libvirt-vms-update-1 Source and further reading].<br />
<br />
=== Enabling KSM ===<br />
<br />
Kernel Samepage Merging (KSM) is a feature of the Linux kernel that allows for an application to register with the kernel to have its pages merged with other processes that also register to have their pages merged. The KSM mechanism allows for guest virtual machines to share pages with each other. In an environment where many of the guest operating systems are similar, this can result in significant memory savings.<br />
<br />
{{Note|Although KSM may reduce memory usage, it may increase CPU usage. Also note some security issues may occur, see [[Wikipedia:Kernel same-page merging]].}}<br />
<br />
To enable KSM:<br />
<br />
# echo 1 > /sys/kernel/mm/ksm/run<br />
<br />
To make it permanent, use [[systemd#systemd-tmpfiles - temporary files|systemd's temporary files]]:<br />
<br />
{{hc|/etc/tmpfiles.d/ksm.conf|<br />
w /sys/kernel/mm/ksm/run - - - - 1<br />
}}<br />
<br />
If KSM is running, and there are pages to be merged (i.e. at least two similar virtual machines are running), then {{ic|/sys/kernel/mm/ksm/pages_shared}} should be non-zero. See https://docs.kernel.org/admin-guide/mm/ksm.html for more information.<br />
<br />
{{Tip|An easy way to see how well KSM is performing is to simply print the contents of all the files in that directory:<br />
<br />
$ grep -r . /sys/kernel/mm/ksm/<br />
<br />
}}<br />
<br />
=== Multi-monitor support ===<br />
<br />
The Linux QXL driver supports four heads (virtual screens) by default. This can be changed via the {{ic|1=qxl.heads=N}} kernel parameter.<br />
<br />
The default VGA memory size for QXL devices is 16M (VRAM size is 64M). This is not sufficient if you would like to enable two 1920x1200 monitors since that requires 2 × 1920 × 4 (color depth) × 1200 = 17.6 MiB VGA memory. This can be changed by replacing {{ic|-vga qxl}} by {{ic|<nowiki>-vga none -device qxl-vga,vgamem_mb=32</nowiki>}}. If you ever increase vgamem_mb beyond 64M, then you also have to increase the {{ic|vram_size_mb}} option.<br />
<br />
=== Custom display resolution ===<br />
<br />
A custom display resolution can be set with {{ic|1=-device VGA,edid=on,xres=1280,yres=720}} (see [[wikipedia:Extended_Display_Identification_Data|EDID]] and [[wikipedia:Display_resolution|display resolution]]).<br />
<br />
=== Copy and paste ===<br />
<br />
==== SPICE ====<br />
<br />
One way to share the clipboard between the host and the guest is to enable the SPICE remote desktop protocol and access the client with a SPICE client.<br />
One needs to follow the steps described in [[#SPICE]]. A guest run this way will support copy paste with the host.<br />
<br />
==== qemu-vdagent ====<br />
<br />
QEMU provides its own implementation of the spice vdagent chardev called {{ic|qemu-vdagent}}. It interfaces with the spice-vdagent guest service and allows the guest and host share a clipboard.<br />
<br />
To access this shared clipboard with QEMU's GTK display, you will need to [[#Custom build|compile QEMU from source]] with the {{ic|--enable-gtk-clipboard}} configure parameter. It is sufficient to replace the installed {{ic|qemu-ui-gtk}} package.<br />
<br />
{{Note|<br />
* Feature request {{Bug|79716}} submitted to enable the functionality in the official package.<br />
* The shared clipboard in qemu-ui-gtk has been pushed back to experimental as it can [https://gitlab.com/qemu-project/qemu/-/issues/1150 freeze guests under certain circumstances]. A fix has been proposed to solve the issue upstream.<br />
}}<br />
<br />
Add the following QEMU command line arguments:<br />
<br />
-device virtio-serial,packed=on,ioeventfd=on<br />
-device virtserialport,name=com.redhat.spice.0,chardev=vdagent0<br />
-chardev qemu-vdagent,id=vdagent0,name=vdagent,clipboard=on,mouse=off<br />
<br />
These arguments are also valid if converted to [[Libvirt#QEMU command line arguments|libvirt form]].<br />
<br />
{{Note|While the spicevmc chardev will start the spice-vdagent service of the guest automatically, the qemu-vdagent chardev may not.}}<br />
<br />
On linux guests, you may [[start]] the {{ic|spice-vdagent.service}} [[user unit]] manually. On Windows guests, set the spice-agent startup type to automatic.<br />
<br />
=== Windows-specific notes ===<br />
<br />
QEMU can run any version of Windows from Windows 95 through Windows 11.<br />
<br />
It is possible to run [[Windows PE]] in QEMU.<br />
<br />
==== Fast startup ====<br />
<br />
{{Note|An administrator account is required to change power settings.}}<br />
<br />
For Windows 8 (or later) guests it is better to disable "Turn on fast startup (recommended)" from the Power Options of the Control Panel as explained in the following [https://www.tenforums.com/tutorials/4189-turn-off-fast-startup-windows-10-a.html forum page], as it causes the guest to hang during every other boot.<br />
<br />
Fast Startup may also need to be disabled for changes to the {{ic|-smp}} option to be properly applied.<br />
<br />
==== Remote Desktop Protocol ====<br />
<br />
If you use a MS Windows guest, you might want to use RDP to connect to your guest virtual machine. If you are using a VLAN or are not in the same network as the guest, use:<br />
<br />
$ qemu-system-x86_64 -nographic -nic user,hostfwd=tcp::5555-:3389<br />
<br />
Then connect with either {{Pkg|rdesktop}} or {{Pkg|freerdp}} to the guest. For example:<br />
<br />
$ xfreerdp -g 2048x1152 localhost:5555 -z -x lan<br />
<br />
=== Clone Linux system installed on physical equipment ===<br />
<br />
Linux system installed on physical equipment can be cloned for running on a QEMU virtual machine. See [https://coffeebirthday.wordpress.com/2018/09/14/clone-linux-system-for-qemu-virtual-machine/ Clone Linux system from hardware for QEMU virtual machine]<br />
<br />
=== Chrooting into arm/arm64 environment from x86_64 ===<br />
<br />
Sometimes it is easier to work directly on a disk image instead of the real ARM based device. This can be achieved by mounting an SD card/storage containing the ''root'' partition and chrooting into it.<br />
<br />
Another use case for an ARM chroot is building ARM packages on an x86_64 machine. Here, the chroot environment can be created from an image tarball from [https://archlinuxarm.org Arch Linux ARM] - see [https://nerdstuff.org/posts/2020/2020-003_simplest_way_to_create_an_arm_chroot/] for a detailed description of this approach.<br />
<br />
Either way, from the chroot it should be possible to run ''pacman'' and install more packages, compile large libraries etc. Since the executables are for the ARM architecture, the translation to x86 needs to be performed by [[QEMU]].<br />
<br />
Install {{Pkg|qemu-user-static}} on the x86_64 machine/host, and {{Pkg|qemu-user-static-binfmt}} to register the qemu binaries to binfmt service.<br />
<br />
''qemu-user-static'' is used to allow the execution of compiled programs from other architectures. This is similar to what is provided by {{Pkg|qemu-emulators-full}}, but the "static" variant is required for chroot. Examples:<br />
<br />
qemu-arm-static path_to_sdcard/usr/bin/ls<br />
qemu-aarch64-static path_to_sdcard/usr/bin/ls<br />
<br />
These two lines execute the {{ic|ls}} command compiled for 32-bit ARM and 64-bit ARM respectively. Note that this will not work without chrooting, because it will look for libraries not present in the host system.<br />
<br />
{{Pkg|qemu-user-static}} allows automatically prefixing the ARM exectuable with {{ic|qemu-arm-static}} or {{ic|qemu-aarch64-static}}.<br />
<br />
Make sure that the ARM executable support is active:<br />
<br />
{{hc|$ ls /proc/sys/fs/binfmt_misc|<br />
qemu-aarch64 qemu-arm qemu-cris qemu-microblaze qemu-mipsel qemu-ppc64 qemu-riscv64 qemu-sh4 qemu-sparc qemu-sparc64 status<br />
qemu-alpha qemu-armeb qemu-m68k qemu-mips qemu-ppc qemu-ppc64abi32 qemu-s390x qemu-sh4eb qemu-sparc32plus register<br />
}}<br />
<br />
Each executable must be listed.<br />
<br />
If it is not active, [[restart]] {{ic|systemd-binfmt.service}}.<br />
<br />
Mount the SD card to {{ic|/mnt/sdcard}} (the device name may be different).<br />
<br />
# mount --mkdir /dev/mmcblk0p2 /mnt/sdcard<br />
<br />
Mount boot partition if needed (again, use the suitable device name):<br />
<br />
# mount /dev/mmcblk0p1 /mnt/sdcard/boot<br />
<br />
Finally ''chroot'' into the SD card root as described in [[Change root#Using chroot]]:<br />
<br />
# chroot /mnt/sdcard /bin/bash<br />
<br />
Alternatively, you can use ''arch-chroot'' from {{Pkg|arch-install-scripts}}, as it will provide an easier way to get network support:<br />
<br />
# arch-chroot /mnt/sdcard /bin/bash<br />
<br />
You can also use [[systemd-nspawn]] to chroot into the ARM environment:<br />
<br />
# systemd-nspawn -D /mnt/sdcard -M myARMMachine --bind-ro=/etc/resolv.conf<br />
<br />
{{ic|1=--bind-ro=/etc/resolv.conf}} is optional and gives a working network DNS inside the chroot<br />
<br />
==== sudo in chroot ====<br />
<br />
If you install [[sudo]] in the chroot and receive the following error when trying to use it:<br />
<br />
sudo: effective uid is not 0, is /usr/bin/sudo on a file system with the 'nosuid' option set or an NFS file system without root privileges?<br />
<br />
then you may need to modify the binfmt flags, for example for {{ic|aarch64}}:<br />
<br />
# cp /usr/lib/binfmt.d/qemu-aarch64-static.conf /etc/binfmt.d/<br />
# vi /etc/binfmt.d/qemu-aarch64-static.conf<br />
<br />
and add a {{ic|C}} at the end of this file:<br />
<br />
:qemu-aarch64:M::\x7fELF\x02\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\xb7\x00:\xff\xff\xff\xff\xff\xff\xff\x00\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff\xff:/usr/bin/qemu-aarch64-static:FPC<br />
<br />
Then [[restart]] {{ic|systemd-binfmt.service}} and check that the changes have taken effect (note the {{ic|C}} on the {{ic|flags}} line):<br />
<br />
{{hc|# cat /proc/sys/fs/binfmt_misc/qemu-aarch64|<br />
enabled<br />
interpreter /usr/bin/qemu-aarch64-static<br />
flags: POCF<br />
offset 0<br />
magic 7f454c460201010000000000000000000200b700<br />
mask ffffffffffffff00fffffffffffffffffeffffff<br />
}}<br />
<br />
See the "flags" section of the [https://docs.kernel.org/admin-guide/binfmt-misc.html kernel binfmt documentation] for more information.<br />
<br />
=== Not grabbing mouse input ===<br />
<br />
{{Style|It is not explained what the option actually does. Is it causing or avoiding the side effect?}}<br />
<br />
Tablet mode has side effect of not grabbing mouse input in QEMU window:<br />
<br />
-usb -device usb-tablet<br />
<br />
It works with several {{ic|-vga}} backends one of which is virtio.<br />
<br />
== Troubleshooting ==<br />
<br />
{{Merge|QEMU/Troubleshooting|This section is long enough to be split into a dedicated subpage.}}<br />
<br />
=== Mouse cursor is jittery or erratic ===<br />
<br />
If the cursor jumps around the screen uncontrollably, entering this on the terminal before starting QEMU might help:<br />
<br />
$ export SDL_VIDEO_X11_DGAMOUSE=0<br />
<br />
If this helps, you can add this to your {{ic|~/.bashrc}} file.<br />
<br />
=== No visible Cursor ===<br />
<br />
Add {{ic|1=-display default,show-cursor=on}} to QEMU's options to see a mouse cursor.<br />
<br />
If that still does not work, make sure you have set your display device appropriately, for example: {{ic|-vga qxl}}.<br />
<br />
Another option to try is {{ic|-usb -device usb-tablet}} as mentioned in [[#Mouse integration]]. This overrides the default PS/2 mouse emulation and synchronizes pointer location between host and guest as an added bonus.<br />
<br />
=== Two different mouse cursors are visible ===<br />
<br />
Apply the tip [[#Mouse integration]].<br />
<br />
=== Keyboard issues when using VNC ===<br />
<br />
When using VNC, you might experience keyboard problems described (in gory details) [https://www.berrange.com/posts/2010/07/04/more-than-you-or-i-ever-wanted-to-know-about-virtual-keyboard-handling/ here]. The solution is ''not'' to use the {{ic|-k}} option on QEMU, and to use {{ic|gvncviewer}} from {{Pkg|gtk-vnc}}. See also [https://www.mail-archive.com/libvir-list@redhat.com/msg13340.html this] message posted on libvirt's mailing list.<br />
<br />
=== Keyboard seems broken or the arrow keys do not work ===<br />
<br />
Should you find that some of your keys do not work or "press" the wrong key (in particular, the arrow keys), you likely need to specify your keyboard layout as an option. The keyboard layouts can be found in {{ic|/usr/share/qemu/keymaps/}}.<br />
<br />
$ qemu-system-x86_64 -k ''keymap'' ''disk_image''<br />
<br />
=== Could not read keymap file ===<br />
<br />
qemu-system-x86_64: -display vnc=0.0.0.0:0: could not read keymap file: 'en'<br />
<br />
is caused by an invalid ''keymap'' passed to the {{ic|-k}} argument. For example, {{ic|en}} is invalid, but {{ic|en-us}} is valid - see {{ic|/usr/share/qemu/keymaps/}}.<br />
<br />
=== Guest display stretches on window resize ===<br />
<br />
To restore default window size, press {{ic|Ctrl+Alt+u}}.<br />
<br />
=== ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy ===<br />
<br />
If an error message like this is printed when starting QEMU with {{ic|-enable-kvm}} option:<br />
<br />
ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy<br />
failed to initialize KVM: Device or resource busy<br />
<br />
that means another [[hypervisor]] is currently running. It is not recommended or possible to run several hypervisors in parallel.<br />
<br />
=== libgfapi error message ===<br />
<br />
The error message displayed at startup:<br />
<br />
Failed to open module: libgfapi.so.0: cannot open shared object file: No such file or directory<br />
<br />
[[Install]] {{Pkg|glusterfs}} or ignore the error message as GlusterFS is a optional dependency.<br />
<br />
=== Kernel panic on LIVE-environments ===<br />
<br />
If you start a live-environment (or better: booting a system) you may encounter this:<br />
<br />
[ end Kernel panic - not syncing: VFS: Unable to mount root fs on unknown block(0,0)<br />
<br />
or some other boot hindering process (e.g. cannot unpack initramfs, cant start service foo).<br />
Try starting the virtual machine with the {{ic|-m VALUE}} switch and an appropriate amount of RAM, if the ram is to low you will probably encounter similar issues as above/without the memory-switch.<br />
<br />
=== Windows 7 guest suffers low-quality sound ===<br />
<br />
Using the {{ic|hda}} audio driver for Windows 7 guest may result in low-quality sound. Changing the audio driver to {{ic|ac97}} by passing the {{ic|-soundhw ac97}} arguments to QEMU and installing the AC97 driver from [https://www.realtek.com/en/component/zoo/category/pc-audio-codecs-ac-97-audio-codecs-software Realtek AC'97 Audio Codecs] in the guest may solve the problem. See [https://bugzilla.redhat.com/show_bug.cgi?id=1176761#c16 Red Hat Bugzilla – Bug 1176761] for more information.<br />
<br />
=== Could not access KVM kernel module: Permission denied ===<br />
<br />
If you encounter the following error:<br />
<br />
libvirtError: internal error: process exited while connecting to monitor: Could not access KVM kernel module: Permission denied failed to initialize KVM: Permission denied<br />
<br />
Systemd 234 assigns a dynamic ID for the {{ic|kvm}} group (see {{Bug|54943}}). To avoid this error, you need edit the file {{ic|/etc/libvirt/qemu.conf}} and change the line with {{ic|1=group = "78"}} to {{ic|1=group = "kvm"}}.<br />
<br />
=== "System Thread Exception Not Handled" when booting a Windows virtual machine ===<br />
<br />
Windows 8 or Windows 10 guests may raise a generic compatibility exception at boot, namely "System Thread Exception Not Handled", which tends to be caused by legacy drivers acting strangely on real machines. On KVM machines this issue can generally be solved by setting the CPU model to {{ic|core2duo}}.<br />
<br />
=== Certain Windows games/applications crashing/causing a bluescreen ===<br />
<br />
Occasionally, applications running in the virtual machine may crash unexpectedly, whereas they would run normally on a physical machine. If, while running {{ic|dmesg -wH}} as root, you encounter an error mentioning {{ic|MSR}}, the reason for those crashes is that KVM injects a [[wikipedia:General protection fault|General protection fault]] (GPF) when the guest tries to access unsupported [[wikipedia:Model-specific register|Model-specific registers]] (MSRs) - this often results in guest applications/OS crashing. A number of those issues can be solved by passing the {{ic|1=ignore_msrs=1}} option to the KVM module, which will ignore unimplemented MSRs.<br />
<br />
{{hc|/etc/modprobe.d/kvm.conf|2=<br />
...<br />
options kvm ignore_msrs=1<br />
...<br />
}}<br />
<br />
Cases where adding this option might help:<br />
<br />
* GeForce Experience complaining about an unsupported CPU being present.<br />
* StarCraft 2 and L.A. Noire reliably blue-screening Windows 10 with {{ic|KMODE_EXCEPTION_NOT_HANDLED}}. The blue screen information does not identify a driver file in these cases.<br />
<br />
{{Warning|While this is normally safe and some applications might not work without this, silently ignoring unknown MSR accesses could potentially break other software within the virtual machine or other virtual machine.}}<br />
<br />
=== Applications in the virtual machine experience long delays or take a long time to start ===<br />
<br />
{{Out of date|No longer true since kernel 5.6}}<br />
<br />
This may be caused by insufficient available entropy in the virtual machine. Consider allowing the guest to access the hosts's entropy pool by adding a [https://wiki.qemu.org/Features/VirtIORNG VirtIO RNG device] to the virtual machine, or by installing an entropy generating daemon such as [[Haveged]].<br />
<br />
Anecdotally, OpenSSH takes a while to start accepting connections under insufficient entropy, without the logs revealing why.<br />
<br />
=== High interrupt latency and microstuttering ===<br />
<br />
This problem manifests itself as small pauses (stutters) and is particularly noticeable in graphics-intensive applications, such as games.<br />
<br />
* One of the causes is CPU power saving features, which are controlled by [[CPU frequency scaling]]. Change this to {{ic|performance}} for all processor cores. <br />
* Another possible cause is PS/2 inputs. Switch from PS/2 to Virtio inputs, see [[PCI passthrough via OVMF#Passing keyboard/mouse via Evdev]].<br />
<br />
=== QXL video causes low resolution ===<br />
<br />
QEMU 4.1.0 introduced a regression where QXL video can fall back to low resolutions, when being displayed through spice. [https://bugs.launchpad.net/qemu/+bug/1843151] For example, when KMS starts, text resolution may become as low as 4x10 characters. When trying to increase GUI resolution, it may go to the lowest supported resolution.<br />
<br />
As a workaround, create your device in this form:<br />
<br />
-device qxl-vga,max_outputs=1...<br />
<br />
=== Virtual machine not booting when using a Secure Boot enabled OVMF ===<br />
<br />
{{ic|OVMF_CODE.secboot.4m.fd}} and {{ic|OVMF_CODE.secboot.fd}} files from {{Pkg|edk2-ovmf}} are built with [[Wikipedia:System Management Mode|SMM]] support. If S3 support is not disabled in the virtual machine, then the virtual machine might not boot at all.<br />
<br />
Add the {{ic|1=-global ICH9-LPC.disable_s3=1}} option to the ''qemu'' command.<br />
<br />
See {{Bug|59465}} and https://github.com/tianocore/edk2/blob/master/OvmfPkg/README for more details and the required options to use Secure Boot in QEMU.<br />
<br />
=== Virtual machine not booting into Arch ISO ===<br />
<br />
When trying to boot the virtual machine for the first time from an Arch ISO image, the boot process hangs. Adding {{ic|1=console=ttyS0}} to kernel boot options by pressing {{ic|e}} in the boot menu you will get more boot messages and the following error:<br />
<br />
:: Mounting '/dev/disk/by-label/ARCH_202204' to '/run/archiso/bootmnt'<br />
Waiting 30 seconds for device /dev/disk/by-label/ARCH_202204 ...<br />
ERROR: '/dev/disk/by-label/ARCH_202204' device did not show up after 30 seconds...<br />
Falling back to interactive prompt<br />
You can try to fix the problem manually, log out when you are finished<br />
sh: can't access tty; job control turned off<br />
<br />
The error message does not give a good clue as to what the real issue is. The problem is with the default 128MB of RAM that QEMU allocates to the virtual machine. Increasing the limit to 1024MB with {{ic|-m 1024}} solves the issue and lets the system boot. You can continue installing Arch Linux as usual after that. Once the installation is complete, the memory allocation for the virtual machine can be decreased. The need for 1024MB is due to RAM disk requirements and size of the installation media. See [https://lists.archlinux.org/archives/list/arch-releng@lists.archlinux.org/message/D5HSGOFTPGYI6IZUEB3ZNAX4D3F3ID37/ this message on the arch-releng mailing list] and [https://bbs.archlinux.org/viewtopic.php?id=204023 this forum thread].<br />
<br />
=== Guest CPU interrupts are not firing ===<br />
<br />
If you are writing your own operating system by following the [https://wiki.osdev.org/ OSDev wiki], or are simply getting stepping through the guest architecture assembly code using QEMU's {{ic|gdb}} interface using the {{ic|-s}} flag, it is useful to know that many emulators, QEMU included, usually implement some CPU interrupts leaving many hardware interrupts unimplemented. One way to know if your code is firing an interrupt, is by using:<br />
<br />
-d int<br />
<br />
to enable showing interrupts/exceptions on stdout.<br />
<br />
To see what other guest debugging features QEMU has to offer, see:<br />
<br />
qemu-system-x86_64 -d help<br />
<br />
or replace {{ic|x86_64}} for your chosen guest architecture.<br />
<br />
=== KDE with sddm does not start spice-vdagent at login automatically ===<br />
<br />
Remove or comment out {{ic|X-GNOME-Autostart-Phase{{=}}WindowManager}} from {{ic|/etc/xdg/autostart/spice-vdagent.desktop}}. [https://github.com/systemd/systemd/issues/18791]<br />
<br />
=== Error starting domain: Requested operation is not valid: network 'default' is not active ===<br />
<br />
If for any reason the default network is deactivated, you will not be able to start any guest virtual machines which are configured to use the network. Your first attempt can be simply trying to start the network with virsh.<br />
<br />
# virsh net-start default<br />
<br />
For additional troubleshooting steps, see [https://www.xmodulo.com/network-default-is-not-active.html].<br />
<br />
== See also ==<br />
<br />
* [https://qemu.org Official QEMU website]<br />
* [https://www.linux-kvm.org Official KVM website]<br />
* [https://qemu.weilnetz.de/doc/6.0/ QEMU Emulator User Documentation]<br />
* [[Wikibooks:QEMU|QEMU Wikibook]]<br />
* [http://alien.slackbook.org/dokuwiki/doku.php?id=slackware:qemu Hardware virtualization with QEMU] by AlienBOB (last updated in 2008)<br />
* [http://blog.falconindy.com/articles/build-a-virtual-army.html Building a Virtual Army] by Falconindy<br />
* [https://git.qemu.org/?p=qemu.git;a=tree;f=docs Lastest docs]<br />
* [https://qemu.weilnetz.de/ QEMU on Windows]<br />
* [[wikipedia:Qemu|Wikipedia]]<br />
* [[debian:QEMU|Debian Wiki - QEMU]]<br />
* [https://people.gnome.org/~markmc/qemu-networking.html QEMU Networking on gnome.org]{{Dead link|2022|09|22|status=404}}<br />
* [http://bsdwiki.reedmedia.net/wiki/networking_qemu_virtual_bsd_systems.html Networking QEMU Virtual BSD Systems]<br />
* [https://www.gnu.org/software/hurd/hurd/running/qemu.html QEMU on gnu.org]<br />
* [https://wiki.freebsd.org/qemu QEMU on FreeBSD as host]<br />
* [https://wiki.mikejung.biz/KVM_/_Xen KVM/QEMU Virtio Tuning and SSD VM Optimization Guide]{{Dead link|2022|09|22|status=404}}<br />
* [https://doc.opensuse.org/documentation/leap/virtualization/html/book-virt/part-virt-qemu.html Managing Virtual Machines with QEMU - openSUSE documentation]<br />
* [https://www.ibm.com/support/knowledgecenter/en/linuxonibm/liaat/liaatkvm.htm KVM on IBM Knowledge Center]</div>Malcontenthttps://wiki.archlinux.org/index.php?title=Talk:Arch_compared_to_other_distributions&diff=786433Talk:Arch compared to other distributions2023-08-29T11:12:40Z<p>Malcontent: NixOS: add more comparisons with Arch</p>
<hr />
<div>== Add Alpine, Void ==<br />
<br />
Void and Alpine are reasonably popular by now. One of their features is a focus on "minimal size", so a subsection could be added to the article accordingly. There's some ambiguity with the [[Arch compared to other distributions#General]] section - both distributions are general purpose, and Debian/Ubuntu also focuses on "minimal size" to some extent (package splitting). Therefore one could either propose a different section name, or alternatively include Void/Alpine in [[Arch compared to other distributions#General]].<br />
<br />
Either way we should think of a write-up and probably include these distributions in the article. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 14:22, 3 September 2021 (UTC)<br />
<br />
:I'll start working on this now. Will likely include Puppy Linux and Tiny Core Linux as well, due to their fit to this category and mix of prominence and endurance. See [https://entvibes.com/archwiki/Small%20Linux%20Distros%20-%20Google%20Trends%20-%202021-09-05%20134735.png here]. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 03:57, 5 September 2021 (UTC)<br />
<br />
Why was this moved to draft state? I was basically done with it. Feel free to add to it, but it's in a comparable state now to the other lists. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 07:40, 5 September 2021 (UTC)<br />
<br />
:We are not done reviewing it. — [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 07:42, 5 September 2021 (UTC)<br />
<br />
:: Can we nuke all this stuff? It screams of content that requires a lot of upkeep (package count, etc), general advertising and a tremendous amount of fluff. Arch ethos is to keep it simple. None of this is remotely simple.<br />
:: [[User:Grawlinson|Grawlinson]] ([[User talk:Grawlinson|talk]]) 01:42, 8 September 2021 (UTC)<br />
<br />
::: I included info about package coverage, in rough approximations, because there was some open consideration of what overlap these have with more general-purpose distributions. It's not essential, but has already been researched and is of relevance to defining the class. Simply removing the content if it proves out of date without a maintainer would be understandable. These are also just comparisons to Arch. LFS is arguably "simpler" than Arch and distributions which are considerably smaller than Arch are also, by necessity, simpler than Arch... Arch isn't all about simplicity. Even the decision to break away from CRUX was over the concern of added complexity created by the envisioned metadata-included creation of pacman. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 03:28, 8 September 2021 (UTC)<br />
<br />
::: Also, I agree and appreciate that simplicity is in the ethos of Arch. Not trying to contest that at all. Just pointing out that it does necessitate some definition. For instance, I suggested "lightweight" as an alternative name for what is now proposed as "minimal-size". This was criticized as, "meaningless." Arch is trademarked as "A simple, lightweight distribution." Certainly, we don't want to face the same criticism from the outside. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 04:29, 8 September 2021 (UTC)<br />
<br />
::: That, "defining what Arch means by simple and lightweight," is part of where I see the value in this page. It's a concrete comparison of the tradeoffs Arch makes vs other projects so that the casual outside observer can clearly see how Archers prioritize simplicity and lightness vs other goals. So minimal-size is a category that specifically helps to define how Arch compares to other projects which more highly priotize "minimalism" or "lightweightness" or whatever you want to call it (currently the idea is that "Minimal-size" is the most apt short description). [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 04:38, 8 September 2021 (UTC)<br />
<br />
::: As a specific example of defining what Archers mean by simple: An Archer might argue that the convenience and stability gained by having a package manager which is better at keeping track of all the moving components in the system and how they interrelate ultimately provides for a simpler overall experience which more than offsets the engineering complexity of it. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 04:46, 8 September 2021 (UTC)<br />
<br />
::: And a specific example of how that definition can help in shaping the future of the distro: I'm currently advocating for an automated install process which covers, at least, the most common use-cases outlined in the [[Installation_guide]]. The argument being around how the added complexity of having an automated process which better keeps track of all the moving components in the system and how they interrelate ultimately provides for a simpler overall experience which more than offsets the engineering complexity of it. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 05:10, 8 September 2021 (UTC)<br />
<br />
:::: I would like to see more actual ''comparisons'' to Arch, rather than merely listing features of other distributions. For example, Void Linux uses pull requests to accept packages into their repositories, while Arch has the AUR with user-submitted packages, which are then cherry-picked to the repositories. Alpine uses APKBUILD, which is very similar to PKGBUILD but is strictly limited to POSIX shell features, e.g. no arrays. And so on.<br />
<br />
:::::Those are great details to include! Please do. My draft only serves as a foundation. I'd like to see more detailed comparison too. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 22:55, 8 September 2021 (UTC)<br />
<br />
:::: Personally I would also skip Tiny Core Linux and Puppy Linux. You even admit to their limited relevance in the distro landscape. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 18:34, 8 September 2021 (UTC)<br />
<br />
::::: Yeah, I've noticed you feel strongly that distros included here should have broad relevance as basically being very general purpose or being generally ubiquitous to those familiar with Linux. I feel like there's some opportunity to cherry-pick a few less ubiquitous distros specifically for the purpose of highlighting implementations which stretch the boundaries of what people might typically do with Linux. For Arch, aiming to be incredibly versatile and fostering of regular tinkering and expansion of the idea of what you can achieve with your system, I feel like it's a worthwhile thing to point these out! For instance, Tiny Core I think gives a wow moment to a lot of people when they realize a whole functional graphical desktop can fit in 11MB, and that adding Wi-Fi and non-US keyboards adds a whole order of magnitude in size and complexity. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 23:02, 8 September 2021 (UTC)<br />
<br />
:::::: It's also a very poignant contrast! Arch is ''A simple, lightweight distribution'', but within the confines of being totally general-purpose. Tiny Core, by comparison, is '''''maximally''''' simple and lightweight as an absolute first priority. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 23:46, 8 September 2021 (UTC)<br />
<br />
=== Draft: Minimal-size ===<br />
<br />
These distributions range in capability from being focused on embedded systems deployment or niche purposes, to having overlap with the more typical general purpose distros listed above. The defining factor of this category is that one of the primary reasons for these distributions to exist is that they are made to have as small of a footprint, in terms of size and resource usage, as is possible for their intended purpose. This generally implies compromises which would not be seen with other, more general-purpose, distributions.<br />
<br />
These distributions can be as small as ~12 MiB on disk, and more typically the minimal install is between 100 MiB and 700 MiB. By contrast, Arch aims to be lightweight, but to serve as a more general purpose system has a base install closer to ~2 GiB, and needing ~512 MiB RAM.<br />
<br />
==== Alpine Linux ====<br />
<br />
* Is a security focused distribution first. Is developed with the expectation it will be deployed to embedded and network edge devices such as routers. The mix of embedded use and a desire to reduce the [https://www.cymune.com/blog-details/Attack-Surface-Reduction "attack surface"] (which comes from extraneous or overly-complex software) for high-value devices motivates making installations of Alpine very small.<br />
* A minimal install is ~130MiB on disk.<br />
* Userland binaries compiled with [[Wikipedia:Position-independent code|position-independent executables]], to limit available exploits.<br />
* Achieves very small size in part by foregoing the usual choice of [[GNU#Toolchain|glibc]], and instead uses [[C#Alternative_libc_implementations|musl libc]].<br />
* [[BusyBox]] based, also to reduce size and complexity.<br />
* Still strives to be a general purpose distribution, and covers a wide variety of potential uses. Lack of glibc can introduce [https://www.musl-libc.org/faq.html compatibility issues] for some applications.<br />
** Package coverage: Over [https://repology.org/repository/alpine_3_14 5000 core projects], and [https://repology.org/repository/alpine_edge over 7500] in edge.<br />
** Wide platform support: i686, x86_64, ARM (hf, v7, AArch64), ppc64le, s390x<br />
* [https://wiki.gentoo.org/wiki/Project:OpenRC OpenRC] for [[init]]<br />
* Started in 2005, with steadily growing adoption, particularly since about 2015. Is now the most prominent minimal-size distribution.<br />
<br />
==== Void Linux ====<br />
<br />
* Is a general-purpose distribution with a focus on being fast and as small as possible.<br />
* Minimal installs: 96MiB RAM, 600MiB disk (700 with glibc)<br />
* i686 and x86_64 support<br />
* Built around both musl and glibc.<br />
* [[Runit]] for [[init]] system (Arch uses [[systemd]] by default)<br />
* Using [https://github.com/void-linux/xbps xbps] package manager.<br />
** Over [https://repology.org/repository/void_x86_64 7000 packages], comparable size to OpenBSD Ports.<br />
<br />
==== Puppy Linux ====<br />
* Is an end-user, desktop-focused, portable-first distribution.<br />
** Boots into a [[ramdisk]], primary intent to boot quickly off a USB stick.<br />
* Small size to enable quick portable boot off USB<br />
** ~130MiB minimum on disk (Typical: i686 - 300MB, x86_64 - 600MB)<br />
* Maintains two main variants: One Ubuntu derived, the other Slackware (also Raspbian for [https://www.raspberrypi.org/ RasPi]/[[ARM]])<br />
* One of the oldest and most enduring of the minimalist distributions. Peak interest in 2008, has [https://entvibes.com/archwiki/Small%20Linux%20Distros%20-%20Google%20Trends%20-%202021-09-05%20134735.png faded in prominence since].<br />
<br />
==== Tiny Core Linux ====<br />
* Is an extremely small graphical Linux desktop<br />
** ~12 MiB on disk (with Wi-Fi and non-US keyboard support: ~106 MiB)<br />
* Achieves small size by cherry-picking some of the smallest tools available for each purpose:<br />
** [[BusyBox]], [https://www.irif.fr/~jch/software/kdrive.html Tiny X], [https://www.fltk.org/ Fltk], and [https://github.com/tinycorelinux/flwm Flwm]<br />
* Can be used as a portable OS, in similar manner to Puppy Linux<br />
* Is limited in scope. Monolithic package updated twice a year since 2009.<br />
** Repo browser not online. State of package repositories unclear.<br />
* Ports for: i686, x86_64, ARM, RasPi<br />
<br />
== Add NixOS Somewhere ==<br />
<br />
I think currently Arch and NixOS are the most interesting comparison out of everything. Arch has been known as, "Linux, with a nice package manager" NixOS is might be more, "A nice package manager, oh and Linux too; purely functional, btw." [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 14:07, 5 September 2021 (UTC)<br />
<br />
:[[Arch compared to other distributions#General]]? -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 14:48, 5 September 2021 (UTC)<br />
<br />
::Yep, sure. I'll start working up a draft. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 01:19, 6 September 2021 (UTC)<br />
<br />
:::This draft could still use some more direct comparisons to Arch.[[User:Einr|Einr]] ([[User talk:Einr|talk]]) 22:38, 8 September 2021 (UTC)<br />
<br />
::::"NixOS is unique in that it is a package manager first and only secondarily a Linux distribution." <-- this doesn't seem all that correct to me, NixOS is the distribution, Nix is the package manager. -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 10:26, 29 August 2023 (UTC)<br />
<br />
::::Agreed, the current NixOS description looks more like an ad in favor of NixOS, more comparison with Arch is needed. -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 11:12, 29 August 2023 (UTC)<br />
<br />
=== NixOS ===<br />
<br />
* While most distributions ''include'' a package manager, NixOS is unique in that it is a package manager first and only secondarily a Linux distribution. [https://nixos.org/manual/nix/stable/#ch-about-nix Nix], the package management system, aims to be a subsystem which can be installed on practically ''any'' Linux distribution. The aim being to be a universally applicable dependency management system for developers.<br />
** Allows use as a continuous-integration environment.<br />
** Allows replacement of language-specific package managers.<br />
** Allows use of a single tool for all project build, machine configuration, and cloud deployment management.<br />
** Is a developer-centric OS.<br />
* Uses a purely functional package language, to avoid side-effects. The ultimate goal from this is to enable [https://reproducible-builds.org/ Reproducible Builds].<br />
** Making [https://discourse.nixos.org/t/nixos-unstable-s-iso-minimal-x86-64-linux-is-100-reproducible/13723 progress] in this.<br />
** This is a major security consideration for any software available in binary form.<br />
** Allows truly atomic changes, which are easily rolled back, for most system management operations. The aim is both for stability and to encourage tinkering, similar to Archer mentality.<br />
*** Arch, comparatively, is not designed around this notion. However, it is versatile and with the right selection of filesystem and supporting software can approach a similar level of reversibility. The snapshotting functionality of [[Btrfs#Snapshots|btrfs]], along with judicious configuration of software like [[Synchronization_and_backup_programs#File-based_increments|TimeShift]] can allow most of this benefit.<br />
* Has one of the largest, most up to date, package ecosystems in the Linux world; comparable to Arch, if AUR is included.<br />
** A core strategic project focus is on increasing and improving the package coverage, functional status, and up-to-date-ness. Semi-annual [https://nixos.org/blog/announcements.html#21.05 releases] have a release manager who actively tracks this and doles out praise and recognition for contributing.</div>Malcontenthttps://wiki.archlinux.org/index.php?title=Talk:Arch_compared_to_other_distributions&diff=786429Talk:Arch compared to other distributions2023-08-29T10:26:17Z<p>Malcontent: Add NixOS feedback</p>
<hr />
<div>== Add Alpine, Void ==<br />
<br />
Void and Alpine are reasonably popular by now. One of their features is a focus on "minimal size", so a subsection could be added to the article accordingly. There's some ambiguity with the [[Arch compared to other distributions#General]] section - both distributions are general purpose, and Debian/Ubuntu also focuses on "minimal size" to some extent (package splitting). Therefore one could either propose a different section name, or alternatively include Void/Alpine in [[Arch compared to other distributions#General]].<br />
<br />
Either way we should think of a write-up and probably include these distributions in the article. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 14:22, 3 September 2021 (UTC)<br />
<br />
:I'll start working on this now. Will likely include Puppy Linux and Tiny Core Linux as well, due to their fit to this category and mix of prominence and endurance. See [https://entvibes.com/archwiki/Small%20Linux%20Distros%20-%20Google%20Trends%20-%202021-09-05%20134735.png here]. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 03:57, 5 September 2021 (UTC)<br />
<br />
Why was this moved to draft state? I was basically done with it. Feel free to add to it, but it's in a comparable state now to the other lists. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 07:40, 5 September 2021 (UTC)<br />
<br />
:We are not done reviewing it. — [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 07:42, 5 September 2021 (UTC)<br />
<br />
:: Can we nuke all this stuff? It screams of content that requires a lot of upkeep (package count, etc), general advertising and a tremendous amount of fluff. Arch ethos is to keep it simple. None of this is remotely simple.<br />
:: [[User:Grawlinson|Grawlinson]] ([[User talk:Grawlinson|talk]]) 01:42, 8 September 2021 (UTC)<br />
<br />
::: I included info about package coverage, in rough approximations, because there was some open consideration of what overlap these have with more general-purpose distributions. It's not essential, but has already been researched and is of relevance to defining the class. Simply removing the content if it proves out of date without a maintainer would be understandable. These are also just comparisons to Arch. LFS is arguably "simpler" than Arch and distributions which are considerably smaller than Arch are also, by necessity, simpler than Arch... Arch isn't all about simplicity. Even the decision to break away from CRUX was over the concern of added complexity created by the envisioned metadata-included creation of pacman. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 03:28, 8 September 2021 (UTC)<br />
<br />
::: Also, I agree and appreciate that simplicity is in the ethos of Arch. Not trying to contest that at all. Just pointing out that it does necessitate some definition. For instance, I suggested "lightweight" as an alternative name for what is now proposed as "minimal-size". This was criticized as, "meaningless." Arch is trademarked as "A simple, lightweight distribution." Certainly, we don't want to face the same criticism from the outside. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 04:29, 8 September 2021 (UTC)<br />
<br />
::: That, "defining what Arch means by simple and lightweight," is part of where I see the value in this page. It's a concrete comparison of the tradeoffs Arch makes vs other projects so that the casual outside observer can clearly see how Archers prioritize simplicity and lightness vs other goals. So minimal-size is a category that specifically helps to define how Arch compares to other projects which more highly priotize "minimalism" or "lightweightness" or whatever you want to call it (currently the idea is that "Minimal-size" is the most apt short description). [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 04:38, 8 September 2021 (UTC)<br />
<br />
::: As a specific example of defining what Archers mean by simple: An Archer might argue that the convenience and stability gained by having a package manager which is better at keeping track of all the moving components in the system and how they interrelate ultimately provides for a simpler overall experience which more than offsets the engineering complexity of it. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 04:46, 8 September 2021 (UTC)<br />
<br />
::: And a specific example of how that definition can help in shaping the future of the distro: I'm currently advocating for an automated install process which covers, at least, the most common use-cases outlined in the [[Installation_guide]]. The argument being around how the added complexity of having an automated process which better keeps track of all the moving components in the system and how they interrelate ultimately provides for a simpler overall experience which more than offsets the engineering complexity of it. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 05:10, 8 September 2021 (UTC)<br />
<br />
:::: I would like to see more actual ''comparisons'' to Arch, rather than merely listing features of other distributions. For example, Void Linux uses pull requests to accept packages into their repositories, while Arch has the AUR with user-submitted packages, which are then cherry-picked to the repositories. Alpine uses APKBUILD, which is very similar to PKGBUILD but is strictly limited to POSIX shell features, e.g. no arrays. And so on.<br />
<br />
:::::Those are great details to include! Please do. My draft only serves as a foundation. I'd like to see more detailed comparison too. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 22:55, 8 September 2021 (UTC)<br />
<br />
:::: Personally I would also skip Tiny Core Linux and Puppy Linux. You even admit to their limited relevance in the distro landscape. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 18:34, 8 September 2021 (UTC)<br />
<br />
::::: Yeah, I've noticed you feel strongly that distros included here should have broad relevance as basically being very general purpose or being generally ubiquitous to those familiar with Linux. I feel like there's some opportunity to cherry-pick a few less ubiquitous distros specifically for the purpose of highlighting implementations which stretch the boundaries of what people might typically do with Linux. For Arch, aiming to be incredibly versatile and fostering of regular tinkering and expansion of the idea of what you can achieve with your system, I feel like it's a worthwhile thing to point these out! For instance, Tiny Core I think gives a wow moment to a lot of people when they realize a whole functional graphical desktop can fit in 11MB, and that adding Wi-Fi and non-US keyboards adds a whole order of magnitude in size and complexity. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 23:02, 8 September 2021 (UTC)<br />
<br />
:::::: It's also a very poignant contrast! Arch is ''A simple, lightweight distribution'', but within the confines of being totally general-purpose. Tiny Core, by comparison, is '''''maximally''''' simple and lightweight as an absolute first priority. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 23:46, 8 September 2021 (UTC)<br />
<br />
=== Draft: Minimal-size ===<br />
<br />
These distributions range in capability from being focused on embedded systems deployment or niche purposes, to having overlap with the more typical general purpose distros listed above. The defining factor of this category is that one of the primary reasons for these distributions to exist is that they are made to have as small of a footprint, in terms of size and resource usage, as is possible for their intended purpose. This generally implies compromises which would not be seen with other, more general-purpose, distributions.<br />
<br />
These distributions can be as small as ~12 MiB on disk, and more typically the minimal install is between 100 MiB and 700 MiB. By contrast, Arch aims to be lightweight, but to serve as a more general purpose system has a base install closer to ~2 GiB, and needing ~512 MiB RAM.<br />
<br />
==== Alpine Linux ====<br />
<br />
* Is a security focused distribution first. Is developed with the expectation it will be deployed to embedded and network edge devices such as routers. The mix of embedded use and a desire to reduce the [https://www.cymune.com/blog-details/Attack-Surface-Reduction "attack surface"] (which comes from extraneous or overly-complex software) for high-value devices motivates making installations of Alpine very small.<br />
* A minimal install is ~130MiB on disk.<br />
* Userland binaries compiled with [[Wikipedia:Position-independent code|position-independent executables]], to limit available exploits.<br />
* Achieves very small size in part by foregoing the usual choice of [[GNU#Toolchain|glibc]], and instead uses [[C#Alternative_libc_implementations|musl libc]].<br />
* [[BusyBox]] based, also to reduce size and complexity.<br />
* Still strives to be a general purpose distribution, and covers a wide variety of potential uses. Lack of glibc can introduce [https://www.musl-libc.org/faq.html compatibility issues] for some applications.<br />
** Package coverage: Over [https://repology.org/repository/alpine_3_14 5000 core projects], and [https://repology.org/repository/alpine_edge over 7500] in edge.<br />
** Wide platform support: i686, x86_64, ARM (hf, v7, AArch64), ppc64le, s390x<br />
* [https://wiki.gentoo.org/wiki/Project:OpenRC OpenRC] for [[init]]<br />
* Started in 2005, with steadily growing adoption, particularly since about 2015. Is now the most prominent minimal-size distribution.<br />
<br />
==== Void Linux ====<br />
<br />
* Is a general-purpose distribution with a focus on being fast and as small as possible.<br />
* Minimal installs: 96MiB RAM, 600MiB disk (700 with glibc)<br />
* i686 and x86_64 support<br />
* Built around both musl and glibc.<br />
* [[Runit]] for [[init]] system (Arch uses [[systemd]] by default)<br />
* Using [https://github.com/void-linux/xbps xbps] package manager.<br />
** Over [https://repology.org/repository/void_x86_64 7000 packages], comparable size to OpenBSD Ports.<br />
<br />
==== Puppy Linux ====<br />
* Is an end-user, desktop-focused, portable-first distribution.<br />
** Boots into a [[ramdisk]], primary intent to boot quickly off a USB stick.<br />
* Small size to enable quick portable boot off USB<br />
** ~130MiB minimum on disk (Typical: i686 - 300MB, x86_64 - 600MB)<br />
* Maintains two main variants: One Ubuntu derived, the other Slackware (also Raspbian for [https://www.raspberrypi.org/ RasPi]/[[ARM]])<br />
* One of the oldest and most enduring of the minimalist distributions. Peak interest in 2008, has [https://entvibes.com/archwiki/Small%20Linux%20Distros%20-%20Google%20Trends%20-%202021-09-05%20134735.png faded in prominence since].<br />
<br />
==== Tiny Core Linux ====<br />
* Is an extremely small graphical Linux desktop<br />
** ~12 MiB on disk (with Wi-Fi and non-US keyboard support: ~106 MiB)<br />
* Achieves small size by cherry-picking some of the smallest tools available for each purpose:<br />
** [[BusyBox]], [https://www.irif.fr/~jch/software/kdrive.html Tiny X], [https://www.fltk.org/ Fltk], and [https://github.com/tinycorelinux/flwm Flwm]<br />
* Can be used as a portable OS, in similar manner to Puppy Linux<br />
* Is limited in scope. Monolithic package updated twice a year since 2009.<br />
** Repo browser not online. State of package repositories unclear.<br />
* Ports for: i686, x86_64, ARM, RasPi<br />
<br />
== Add NixOS Somewhere ==<br />
<br />
I think currently Arch and NixOS are the most interesting comparison out of everything. Arch has been known as, "Linux, with a nice package manager" NixOS is might be more, "A nice package manager, oh and Linux too; purely functional, btw." [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 14:07, 5 September 2021 (UTC)<br />
<br />
:[[Arch compared to other distributions#General]]? -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 14:48, 5 September 2021 (UTC)<br />
<br />
::Yep, sure. I'll start working up a draft. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 01:19, 6 September 2021 (UTC)<br />
<br />
:::This draft could still use some more direct comparisons to Arch.[[User:Einr|Einr]] ([[User talk:Einr|talk]]) 22:38, 8 September 2021 (UTC)<br />
<br />
::::"NixOS is unique in that it is a package manager first and only secondarily a Linux distribution." <-- this doesn't seem all that correct to me, NixOS is the distribution, Nix is the package manager. -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 10:26, 29 August 2023 (UTC)<br />
<br />
=== NixOS ===<br />
<br />
* While most distributions ''include'' a package manager, NixOS is unique in that it is a package manager first and only secondarily a Linux distribution. [https://nixos.org/manual/nix/stable/#ch-about-nix Nix], the package management system, aims to be a subsystem which can be installed on practically ''any'' Linux distribution. The aim being to be a universally applicable dependency management system for developers.<br />
** Allows use as a continuous-integration environment.<br />
** Allows replacement of language-specific package managers.<br />
** Allows use of a single tool for all project build, machine configuration, and cloud deployment management.<br />
** Is a developer-centric OS.<br />
* Uses a purely functional package language, to avoid side-effects. The ultimate goal from this is to enable [https://reproducible-builds.org/ Reproducible Builds].<br />
** Making [https://discourse.nixos.org/t/nixos-unstable-s-iso-minimal-x86-64-linux-is-100-reproducible/13723 progress] in this.<br />
** This is a major security consideration for any software available in binary form.<br />
** Allows truly atomic changes, which are easily rolled back, for most system management operations. The aim is both for stability and to encourage tinkering, similar to Archer mentality.<br />
*** Arch, comparatively, is not designed around this notion. However, it is versatile and with the right selection of filesystem and supporting software can approach a similar level of reversibility. The snapshotting functionality of [[Btrfs#Snapshots|btrfs]], along with judicious configuration of software like [[Synchronization_and_backup_programs#File-based_increments|TimeShift]] can allow most of this benefit.<br />
* Has one of the largest, most up to date, package ecosystems in the Linux world; comparable to Arch, if AUR is included.<br />
** A core strategic project focus is on increasing and improving the package coverage, functional status, and up-to-date-ness. Semi-annual [https://nixos.org/blog/announcements.html#21.05 releases] have a release manager who actively tracks this and doles out praise and recognition for contributing.</div>Malcontenthttps://wiki.archlinux.org/index.php?title=Unofficial_user_repositories&diff=786238Unofficial user repositories2023-08-26T16:30:04Z<p>Malcontent: Remove some empty lines in order to preserve consistency</p>
<hr />
<div>[[Category:Package management]]<br />
[[Category:Lists]]<br />
[[es:Unofficial user repositories]]<br />
[[ja:非公式ユーザーリポジトリ]]<br />
[[zh-hans:Unofficial user repositories]]<br />
{{Related articles start}}<br />
{{Related|pacman-key}}<br />
{{Related|Official repositories}}<br />
{{Related articles end}}<br />
<br />
This article lists binary repositories freely created and shared by the community, often providing pre-built versions of PKGBUILDS found in the [[AUR]].<br />
<br />
In order to use these repositories, add them to {{ic|/etc/pacman.conf}}, as explained in [[pacman#Repositories and mirrors]]. If a repository is signed, you must obtain and locally sign the associated key, as explained in [[pacman/Package signing#Adding unofficial keys]].<br />
<br />
If you want to create your own custom repository, follow [[pacman/Tips and tricks#Custom local repository]].<br />
<br />
{{Warning|The official Arch Linux Developers and the Trusted Users do not perform tests of any sort to verify the contents of these repositories. It is your decision whether to trust their maintainers, and you take full responsibility for any consequences of using any unofficial repository.}}<br />
<br />
== Adding your repository to this page ==<br />
<br />
If you have your own repository, please add it to this page so that all the other users will know where to find your packages. Please keep the following rules when adding new repositories:<br />
<br />
* Keep the lists in alphabetical order.<br />
* Include some information about the maintainer: include at least a (nick)name and some form of contact information (website, email address, user page on ArchWiki or the forums, etc.).<br />
* If the repository is of the ''signed'' variety, please include a key-id, possibly using it as the anchor for a link to its keyserver; if the key is not on a keyserver, include a link to the key file.<br />
* Include some short description (e.g., the category of packages provided in the repository).<br />
* If there is a page (either on ArchWiki or external) containing more information about the repository, include a link to it.<br />
* If possible, avoid using comments in code blocks. The formatted description is much more readable. Users who want some comments in their {{ic|pacman.conf}} can easily create it on their own.<br />
<br />
Some repositories may also have packages for architectures besides x86_64. The {{ic|$arch}} variable will be set automatically by pacman.<br />
<br />
== Signed ==<br />
<br />
=== ada ===<br />
<br />
* '''Maintainer:''' Rod Kay <rodakay5 at gmail dot com><br />
* '''Description:''' Arch Ada Repository ~ all packages relating to the [[Ada]] and SPARK programming languages.<br />
* '''Key-ID:''' [https://keyserver.ubuntu.com/pks/lookup?op=vindex&fingerprint=on&exact=on&search=0xED55AF75B0330A2A3BAA9986B6120CD888A0DFD2 b6120cd888a0dfd2]<br />
<br />
{{bc|<nowiki><br />
[ada]<br />
Server = http://www.orthanc.site:8080/assets/arch_ada_repo<br />
</nowiki>}}<br />
<br />
=== alerque ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/alerque Caleb Maclennan]<br />
* '''Description:''' Typesetting, publishing, and font development related tools such as SILE, CaSILE, Fontship, and their related dependencies including many fonts, Lua rocks, and Python modules. Also Asterisk, most of the [https://aur.archlinux.org/packages/?O=0&SeB=M&K=alerque&outdated=&SB=n&SO=a&PP=250&do_Search=Go AUR packages I (co-)maintain], and many of the AUR builds I use personally.<br />
* '''Git Repository:''' https://github.com/alerque/aur<br />
* '''Issue Tracker:''' https://github.com/alerque/aur/issues<br />
* '''Key-ID:''' [https://keyserver.ubuntu.com/pks/lookup?op=vindex&fingerprint=on&exact=on&search=0x9F377DDB6D3153A48EB3EB1E63CC496475267693 63CC496475267693]<br />
<br />
{{bc|<nowiki><br />
[alerque]<br />
Server = https://arch.alerque.com/$arch<br />
</nowiki>}}<br />
<br />
=== ALHP ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/anonfunc Giovanni Harting]<br />
* '''Description:''' [[official repositories]] compiled with [[Wikipedia:Interprocedural_optimization|LTO]], -march=x86-64-vN and -O3.<br />
* '''Issue Tracker:''' https://somegit.dev/ALHP/ALHP.GO/issues<br />
* '''Keyring:''' {{AUR|alhp-keyring}}<br />
* '''Mirrorlist:''' {{AUR|alhp-mirrorlist}}<br />
* '''Upstream page:''' https://somegit.dev/ALHP/ALHP.GO<br />
* '''Debuginfod:''' https://debuginfod.alhp.dev<br />
<br />
{{bc|<nowiki><br />
[core-x86-64-v3]<br />
Include = /etc/pacman.d/alhp-mirrorlist<br />
<br />
[extra-x86-64-v3]<br />
Include = /etc/pacman.d/alhp-mirrorlist<br />
</nowiki>}}<br />
<br />
=== andontie-aur ===<br />
<br />
* '''Maintainer:''' Holly M.<br />
* '''Description:''' A repository containing the most popular AUR packages, as well as some I use all the time. New packages can be requested on the upstream website.<br />
* '''Key-ID:''' B545E9B7CD906FE3<br />
* '''Upstream page:''' https://aur.andontie.net<br />
<br />
{{bc|<nowiki><br />
[andontie-aur]<br />
Server = https://aur.andontie.net/$arch<br />
</nowiki>}}<br />
<br />
=== arcanisrepo ===<br />
<br />
* '''Maintainer:''' [https://arcanis.me/ arcanis]<br />
* '''Description:''' AUR packages (including some VCS packages), mostly development and scientific tools. Updated daily.<br />
* '''Key-ID:''' [https://pgp.mit.edu/pks/lookup?op=get&search=0xBD2AC8C5E989490C 0xBD2AC8C5E989490C]<br />
* '''Upstream page:''' http://repo.arcanis.me/x86_64/index.html<br />
<br />
{{bc|<nowiki><br />
[arcanisrepo]<br />
Server = http://repo.arcanis.me/$arch<br />
</nowiki>}}<br />
<br />
=== arch4edu ===<br />
<br />
* '''Maintainers:''' [https://github.com/petronny Jingbei Li (petronny)], and [https://github.com/arch4edu/arch4edu/graphs/contributors others]<br />
* '''Description:''' arch4edu is a community repository for Arch Linux and Arch Linux ARM that strives to provide the latest versions of most software used by college students.<br />
* '''Git Repo:''' https://github.com/arch4edu/arch4edu<br />
* '''Issue tracking:''' https://github.com/arch4edu/arch4edu/issues for packaging issues, out-of-date notifications, package requests, and related questions<br />
* '''Mirrors:''' https://github.com/arch4edu/mirrorlist/blob/master/mirrorlist.arch4edu<br />
* '''Key-ID:''' 7931B6D628C8D3BA<br />
<br />
{{bc|<nowiki><br />
[arch4edu]<br />
Server = https://mirrors.tuna.tsinghua.edu.cn/arch4edu/$arch<br />
## or other mirrors in https://github.com/arch4edu/mirrorlist/blob/master/mirrorlist.arch4edu<br />
</nowiki>}}<br />
<br />
=== archlinuxcn ===<br />
<br />
* '''Maintainers:''' [https://blog.phoenixlzx.com/ phoenixlzx], [https://archlinux.org/people/developers/#felixonmars Felix Yan (felixonmars, dev)], [https://github.com/lilydjwg lilydjwg], [https://archlinux.org/people/trusted-users/#farseerfc farseerfc (TU)], and [https://github.com/archlinuxcn/repo/graphs/contributors others]<br />
* '''Description:''' Packages by the Chinese Arch Linux community, all signed. Be aware that non-x86_64 packages are not fully maintained and tested. Create an issue if you find some problems.<br />
* '''Git Repo:''' https://github.com/archlinuxcn/repo<br />
* '''Issue tracking:''' https://github.com/archlinuxcn/repo/issues for packaging issues, out-of-date notifications, package requests, and related questions<br />
* '''Mirrors:''' https://github.com/archlinuxcn/mirrorlist-repo (Mostly for users in mainland China), or install ''archlinuxcn-mirrorlist-git'' from the repository.<br />
* '''Key-ID:''' Once the repository is added, ''archlinuxcn-keyring'' package must be installed before any other, so you do not get errors about PGP signatures. ''archlinuxcn-keyring'' package itself is signed by TU.<br />
* '''Debuginfod:''' https://repo.archlinuxcn.org<br />
<br />
{{bc|<nowiki><br />
[archlinuxcn]<br />
Server = http://repo.archlinuxcn.org/$arch<br />
## or install archlinuxcn-mirrorlist-git and use the mirrorlist<br />
#Include = /etc/pacman.d/archlinuxcn-mirrorlist<br />
</nowiki>}}<br />
<br />
=== archlinux-t2-packages ===<br />
<br />
* '''Maintainer:''' [https://github.com/Redecorating Redecorating]<br />
* '''Description:''' Basic kernel and utilities for use on Macs with T2 security chip. Should be used in conjunction with [[#arch-mact2|arch-mact2]] repository.<br />
* '''Key-ID:''' DEB7F121BAAA6F4E<br />
* '''Upstream page:''' https://github.com/Redecorating/archlinux-t2-packages<br />
<br />
{{bc|<nowiki><br />
[archlinux-t2-packages]<br />
Server = https://github.com/Redecorating/archlinux-t2-packages/releases/download/packages<br />
</nowiki>}}<br />
<br />
=== archzfs ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/minextu Jan Houben (minextu)]<br />
* '''Description:''' Packages for ZFS on Arch Linux.<br />
* '''Upstream page:''' https://github.com/archzfs/archzfs<br />
* '''Key-ID:''' [https://archzfs.com/archzfs.gpg DDF7DB817396A49B2A2723F7403BD972F75D9D76]<br />
<br />
{{bc|<nowiki><br />
[archzfs]<br />
# Origin Server - France<br />
Server = http://archzfs.com/$repo/x86_64<br />
# Mirror - Germany<br />
Server = http://mirror.sum7.eu/archlinux/archzfs/$repo/x86_64<br />
# Mirror - Germany<br />
Server = https://mirror.biocrafting.net/archlinux/archzfs/$repo/x86_64<br />
# Mirror - India<br />
Server = https://mirror.in.themindsmaze.com/archzfs/$repo/x86_64<br />
# Mirror - US<br />
Server = https://zxcvfdsa.com/archzfs/$repo/$arch<br />
</nowiki>}}<br />
<br />
=== artafinde ===<br />
<br />
* '''Maintainer:''' [https://archlinux.org/people/trusted-users/#artafinde Leonidas Spyropoulos]<br />
* '''Description:''' Personal repository with AUR and custom packages.<br />
* '''Key-ID:''' Not needed, as the maintainer is a TU<br />
<br />
{{bc|<nowiki><br />
[artafinde]<br />
Server = https://pkgbuild.com/~artafinde/repo<br />
</nowiki>}}<br />
<br />
=== aviallon ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/aviallon/ aviallon]<br />
* '''Description:''' Prebuilt packages from AUR, plus some of my personal packages. For now, only x86_64 is supported.<br />
* '''Upstream page:''' https://mirror.lesviallon.fr/<br />
* '''Key-ID:''' [https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x4d5557ab89e5fe11 883918BAF0EE4170241579794D5557AB89E5FE11]<br />
<br />
{{bc|<nowiki><br />
[aviallon]<br />
Server = https://mirror.lesviallon.fr/$repo/os/$arch<br />
</nowiki>}}<br />
<br />
=== avr ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/vianney Vianney Bouchaud]<br />
* '''Description:''' Some of the AUR builds I use personally, packages mainly related to kubernetes that I used to build for my own use as well as some of my own software that I also package.<br />
* '''Git Repository:''' https://github.com/vbouchaud/aur<br />
* '''Issue Tracker:''' https://github.com/vbouchaud/aur/issues<br />
* '''Key-ID:''' [https://keyserver.ubuntu.com/pks/lookup?op=vindex&fingerprint=on&exact=on&search=0xAD53F33B1AB4C51802F25068157B08346330029C 157B08346330029C]<br />
* '''Upstream page:''' https://bouchaud.org/packages/avr<br />
<br />
{{bc|<nowiki><br />
[avr]<br />
Server = https://bouchaud.org/packages/$repo/$arch<br />
</nowiki>}}<br />
<br />
=== berberman ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/berberman berberman]<br />
* '''Description:''' Some packages make no sense.<br />
* '''Upstream page:''' https://github.com/berberman/myrepo<br />
* '''Key-ID:''' C4F93F1ED397E8CF<br />
<br />
{{bc|<nowiki><br />
[berberman]<br />
Server = https://repo.typed.icu/$arch<br />
</nowiki>}}<br />
<br />
=== bioarchlinux ===<br />
<br />
* '''Maintainer:''' BioArchLinux Team<br />
* '''Description:''' Biological Software Repository for Arch Linux<br />
* '''Upstream page:''' https://github.com/BioArchLinux/Packages<br />
* '''Key-ID:''' B1F96021DB62254D<br />
<br />
{{bc|<nowiki><br />
[bioarchlinux]<br />
Server = https://repo.bioarchlinux.org/$arch<br />
</nowiki>}}<br />
<br />
=== blackeagle-pre-community ===<br />
<br />
* '''Maintainer:''' [https://archlinux.org/people/trusted-users/#idevolder Ike Devolder]<br />
* '''Description:''' testing of the by me maintained packages before moving to ''extra'' repository<br />
* '''Key-ID:''' Not required, as maintainer is a TU<br />
<br />
{{bc|<nowiki><br />
[blackeagle-pre-community]<br />
Server = https://repo.herecura.eu/$repo/$arch<br />
</nowiki>}}<br />
<br />
=== build.kilabit.info ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/shulhan shulhan]<br />
* '''Description:''' x86-64 packages: asdf-vm-git, aws-cli-v2-bin, clipman-git, easyconnect, google-cloud-ops-agent-git, google-java-format-git, jackett-bin, j4-dmenu-desktop-git, php-cs-fixer-git, php-humbug-box-bin, rescached-git, and volta-bin.<br />
* '''Key-ID:''' [https://keys.openpgp.org/vks/v1/by-fingerprint/CEF1AA87E337A6C390DE5550F8507EE9148A4CE3 4A5360B500C9C4F0]<br />
* '''Website:''' https://build.kilabit.info<br />
<br />
{{bc|<nowiki><br />
[build.kilabit.info]<br />
Server = https://build.kilabit.info/aur<br />
</nowiki>}}<br />
<br />
=== built ===<br />
<br />
* '''Maintainer:''' [https://github.com/MedzikUser MedzikUser]<br />
* '''Description:''' Compiled packages with AUR for x86-64 and x86-64-v3 architectures<br />
* '''Upstream GitHub:''' https://github.com/built-aur<br />
* '''Key-ID:''' 02213A0493457E96<br />
* '''Keyfile:''' https://built-aur.medzik.workers.dev/built.key<br />
* '''Instructions on how to add a repository:''' https://github.com/built-aur/packages/wiki<br />
<br />
{{bc|<nowiki><br />
[built]<br />
Server = https://built-aur.medzik.workers.dev/$arch<br />
</nowiki>}}<br />
<br />
=== chaotic-aur ===<br />
<br />
* '''Maintainer:''' [https://github.com/dr460nf1r3 dr460nf1r3], [https://github.com/pedrohlc PedroHLC], [https://github.com/lordkitsuna LordKitsuna], [https://github.com/librewish Librewish]{{Dead link|2023|05|06|status=404}}, [https://github.com/SolarAquarion SolarAquarion], [https://github.com/thotypous thotypous] (former [[TU]]), and [https://github.com/RustemB RustemB] (in memoriam).<br />
* '''Description:''' Auto builds AUR packages the maintainers use, update them hourly (a few are updated daily). It has several mirrors worldwide. Its main builder is hosted at the Federal University of Sao Carlos, Brazil. It's x86_64 only.<br />
* '''Key-ID:''' [https://pgp.mit.edu/pks/lookup?search=0xFBA220DFC880C036&op=index FBA220DFC880C036], with some subkeys. To help, keyring and mirrorlist are available at the repository's homepage.<br />
* '''Note:''' See [https://aur.chaotic.cx repository's homepage].<br />
<br />
{{bc|<nowiki><br />
[chaotic-aur]<br />
Server = https://geo-mirror.chaotic.cx/$repo/$arch<br />
</nowiki>}}<br />
<br />
=== coderkun-aur ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/coderkun/ coderkun]<br />
* '''Description:''' AUR packages with random software. Supporting package deltas and package and database signing.<br />
* '''Upstream page:''' https://www.suruatoel.xyz/arch<br />
* '''Key-ID:''' 39E27199A6BEE374<br />
* '''Keyfile:''' https://www.suruatoel.xyz/coderkun.key<br />
<br />
{{bc|<nowiki><br />
[coderkun-aur]<br />
Server = https://arch.suruatoel.xyz/$repo/$arch/<br />
</nowiki>}}<br />
<br />
=== copypaste ===<br />
<br />
* '''Maintainer:''' [https://copypaste.wtf Fredrick R. Brennan <copypaste@kittens.ph>]<br />
* '''Description:''' AUR packages with random software. {{aur|blender-git}} and fonts related stuff mostly.<br />
* '''Upstream page:''' http://aur.copypaste.wtf/<br />
* '''Key-ID:''' 98F28F767470129FBE3B054CE2154DD1A1C77B8B<br />
* '''Keyfile:''' http://aur.copypaste.wtf/copypaste.pub.key.asc<br />
<br />
{{bc|<nowiki><br />
[copypaste]<br />
Server = http://aur.copypaste.wtf/<br />
</nowiki>}}<br />
<br />
=== dasbaumwolltier ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/dasbaumwolltier/ dasbaumwolltier]<br />
* '''Description:''' Contains (nearly) all of my AUR packages and some random AUR packages I use myself. (A full list of packages can be found [https://github.com/dasbaumwolltier/aur-building/blob/master/package-list here]. Feel free to open issues.) They are usually not evicted from the build after I stop using them. Builds are at least weekly.<br />
* '''Git Repository:''' https://github.com/dasbaumwolltier/aur-building<br />
* '''Key-ID:''' [https://repo.guldner.eu/repository/archlinux/dasbaumwolltier.gpg 746BC93D5F08C5A4369F4DDB10BF99E6998249B6]{{Dead link|2022|09|23|status=404}}<br />
<br />
{{bc|<nowiki><br />
[dasbaumwolltier]<br />
Server = https://repo.guldner.eu/repository/archlinux/$arch/<br />
</nowiki>}}<br />
<br />
=== desolve ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/dviktor/ desolve]<br />
* '''Description:''' Collection of R packages plus some extra stuff.<br />
* '''Git repository for R packages:''' https://github.com/dvdesolve/ArchRPkgs<br />
* '''Git repository for other AUR packages:''' https://github.com/dvdesolve/pkgbuilds<br />
* '''Key-ID:''' [https://keyserver.ubuntu.com/pks/lookup?op=get&search=0xdd3bf75dcd96541ac723b7cd6a4cd3276ca8ebbd DD3BF75DCD96541AC723B7CD6A4CD3276CA8EBBD]<br />
<br />
{{bc|<nowiki><br />
[desolve]<br />
Server = https://desolve.ru/archrepo/$arch<br />
</nowiki>}}<br />
<br />
=== devkitpro ===<br />
<br />
* '''Maintainer:''' [https://devkitpro.org/ wintermute]<br />
* '''Description:''' Provides Homebrew toolchains for the Nintendo Wii, Gamecube, DS, GBA, Gamepark gp32, and Nintendo Switch<br />
* '''Upstream page:''' https://devkitpro.org/wiki/devkitPro_pacman<br />
* '''Key-ID:''' F7FD5492264BB9D0<br />
<br />
{{Note|Repository has its own additional keyring at https://pkg.devkitpro.org/devkitpro-keyring.pkg.tar.xz}}<br />
<br />
{{bc|<nowiki><br />
[dkp-libs]<br />
Server = https://downloads.devkitpro.org/packages<br />
<br />
[dkp-linux]<br />
Server = https://downloads.devkitpro.org/packages/linux<br />
</nowiki>}}<br />
<br />
=== doom2df-repo ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/TerminalHash Dmitry Lyashuk]<br />
* '''Description:''' Pre-built packages for game Doom 2D: Forever, a modern port of Doom 2D by Prikol Software with network play, powerful map editor, etc.<br />
* '''Git Repository:''' https://github.com/Doom2D/Doom2D-ForeverAUR<br />
* '''Issue Tracker:''' https://github.com/Doom2D/Doom2D-ForeverAUR/issues<br />
* '''Key-ID:''' [https://keyserver.ubuntu.com/pks/lookup?search=E0DBB3D1D7AA8E6B&fingerprint=on&op=index E0DBB3D1D7AA8E6B]<br />
<br />
{{bc|<nowiki><br />
[doom2df-repo]<br />
Server = https://terminalhash.ru/$repo<br />
</nowiki>}}<br />
<br />
=== fcgu ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/fabiscafe Fabian Bornschein]<br />
* '''Description:''' Overlay repository, mostly for unstable (Beta, RC) releases of GNOME- and related software.<br />
* '''Homepage:''' https://codeberg.org/fabiscafe/fcgu<br />
* '''Keyfile:''' https://keys.openpgp.org/vks/v1/by-fingerprint/6E58E886A8E07538A2485FAED6A4F386B4881229<br />
* '''Key-ID:''' D6A4F386B4881229<br />
{{Note|Instructions can be found at [https://codeberg.org/fabiscafe/fcgu#fcgu-repo-for-gnome-pre-releases https://codeberg.org/fabiscafe/fcgu]}}<br />
<br />
=== ffy00 ===<br />
<br />
* '''Maintainer:''' [https://archlinux.org/people/trusted-users/#FFY00 Filipe Laíns]<br />
* '''Description:''' Personal repository. Contains misc packages related to hardware, cross-compilation, the D language, etc.<br />
* '''Key-ID:''' Not needed, as maintainer is a TU<br />
<br />
{{bc|<nowiki><br />
[ffy00]<br />
Server = https://pkgbuild.com/~ffy00/repo<br />
</nowiki>}}<br />
<br />
=== fusion809 ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/fusion809 Brenton Horne] (brentonhorne77 at gmail dot com).<br />
* '''Description:''' Provides a few AUR and other packages I like. Like CodeLite and bleeding-edge (latest release within 1 day of its release) GVim (GTK 2 interface).<br />
* '''Package list:''' http://download.opensuse.org/repositories/home:/fusion809/Arch_Extra/x86_64/{{Dead link|2023|05|06|status=404}}<br />
* '''Key-ID:''' 03264DDCD606DC98<br />
* '''Keyfile:''' https://download.opensuse.org/repositories/home:/fusion809/Arch_Extra/x86_64/home_fusion809_Arch_Extra.key{{Dead link|2023|05|06|status=404}}<br />
<br />
{{bc|<nowiki><br />
[home_fusion809_Arch_Extra]<br />
Server = https://download.opensuse.org/repositories/home:/fusion809/Arch_Extra/$arch<br />
</nowiki>}}<br />
<br />
=== g14 ===<br />
<br />
* '''Maintainer:''' [https://gitlab.com/flukejones Luke Jones]<br />
* '''Description:''' A custom repository for [[ASUS Linux]], it contains prebuilt binaries for all of the software they offer.<br />
* '''Upstream page:''' https://asus-linux.org/<br />
* '''Package list:''' https://arch.asus-linux.org/<br />
* '''Key-ID:''' 8F654886F17D497FEFE3DB448B15A6B0E9A3FA35<br />
<br />
{{bc|<nowiki><br />
[g14]<br />
# Germany, origin<br />
Server = https://arch.asus-linux.org<br />
# Republic of Korea<br />
Server = https://naru.jhyub.dev/$repo<br />
</nowiki>}}<br />
<br />
=== grawlinson ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/grawlinson George Rawlinson]<br />
* '''Description:''' AUR packages maintained by the user as well as some experimental packages.<br />
* '''Package list:''' https://mirror.little.kiwi<br />
* '''Key-ID:''' 9D120F4AAF400B8313A87EF2369552B2069123EE<br />
* '''Keyfile:''' https://mirror.little.kiwi/grawlinson.asc<br />
* '''Source:''' https://git.little.kiwi/grawlinson/arch-pkgs<br />
<br />
{{bc|<nowiki><br />
[grawlinson]<br />
Server = https://mirror.little.kiwi<br />
Server = https://pkgbuild.com/~grawlinson/repo/$repo<br />
</nowiki>}}<br />
<br />
=== herecura ===<br />
<br />
* '''Maintainer:''' [https://archlinux.org/people/trusted-users/#idevolder Ike Devolder]<br />
* '''Description:''' additional packages not found in the ''community'' repository<br />
* '''Key-ID:''' Not required, as maintainer is a TU<br />
* '''Git Repo:''' https://gitlab.com/herecura/packages<br />
<br />
{{bc|<nowiki><br />
[herecura]<br />
Server = https://repo.herecura.eu/$repo/$arch<br />
</nowiki>}}<br />
<br />
=== holo ===<br />
<br />
* '''Maintainer:''' Stefan Majewsky <holo-pacman@posteo.de> (please prefer to report issues at [https://github.com/majewsky/holo-pacman-repo/issues Github])<br />
* '''Description:''' Packages for [https://holocm.org Holo configuration management], including compatible plugins and tools.<br />
* '''Upstream page:''' https://github.com/majewsky/holo-pacman-repo<br />
* '''Package list:''' https://repo.holocm.org/archlinux/x86_64<br />
* '''Key-ID:''' 0xF7A9C9DC4631BD1A<br />
<br />
{{bc|<nowiki><br />
[holo]<br />
Server = https://repo.holocm.org/archlinux/x86_64<br />
</nowiki>}}<br />
<br />
=== home-thaodan ===<br />
<br />
* '''Maintainer''': [https://aur.archlinux.org/account/Thaodan Thaodan]<br />
* '''Upstream page''': https://gitlab.com/Thaodans-ArchLinux-Packages/repo-home-thaodan<br />
* '''Description''': [[Kernel#Unofficial kernels|pf-kernel]] and other packages by Thaodan<br />
* '''Key-ID:''': BBFE2FD421597395E4FC8C8DF6C85FEE79D661A4<br />
<br />
{{bc|<nowiki><br />
[home-thaodan]<br />
Server = https://repo.thaodan.de/archlinux/home-thaodan/$arch<br />
</nowiki>}}<br />
<br />
=== ivasilev ===<br />
<br />
* '''Maintainer:''' [https://ivasilev.net Ianis G. Vasilev]<br />
* '''Description:''' A variety of packages, mostly my own software and AUR builds.<br />
* '''Upstream page:''' https://ivasilev.net/pacman<br />
* '''Key-ID:''' [https://pgp.mit.edu/pks/lookup?op=vindex&search=0xB77A3C8832838F1F80ADFD7E1D0507B417DAB671 17DAB671]<br />
<br />
{{bc|<nowiki><br />
[ivasilev]<br />
Server = https://ivasilev.net/pacman/$arch<br />
</nowiki>}}<br />
<br />
=== jk-aur ===<br />
<br />
* '''Maintainer:''' [https://github.com/jstkdng JustKidding]<br />
* '''Description:''' Packages from the AUR I maintain and co-maintain.<br />
* '''Upstream page:''' https://github.com/jstkdng/aur<br />
* '''Key-ID:''' [https://build.opensuse.org/project/keys_and_certificates/home:justkidding:arch 7627D0F8F60FBA35371A29E1AA6B2752759F9361]<br />
<br />
{{bc|<nowiki><br />
[home_justkidding_arch_Arch]<br />
Server = https://download.opensuse.org/repositories/home:/justkidding:/arch/Arch/$arch<br />
</nowiki>}}<br />
<br />
=== jlk ===<br />
<br />
* '''Maintainer:''' [[User:Lahwaacz|Jakub Klinkovský]]<br />
* '''Description:''' Various packages from the ABS and AUR. Modified packages are in the {{ic|modified}} group.<br />
* '''Upstream page:''' https://jlk.fjfi.cvut.cz/arch/repo/README.html<br />
* '''Key-ID:''' 932BA3FA0C86812A32D1F54DAB5964AEB9FEDDDC<br />
<br />
{{bc|<nowiki><br />
[jlk]<br />
Server = https://jlk.fjfi.cvut.cz/arch/repo<br />
</nowiki>}}<br />
<br />
=== kawaii ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/LeonidPilyugin Leonid Pilyugin]<br />
* '''Description:''' Kawaii modified packages from AUR and myself.<br />
* '''Upstream page:''' https://github.com/LeonidPilyugin/kawaii-repo<br />
* '''Key-ID:''' A308BDBE10D7C9C168AA2E055F2E4806FFE6B2CD<br />
<br />
{{bc|<nowiki><br />
[kawaii]<br />
Server = https://raw.githubusercontent.com/LeonidPilyugin/kawaii-repo/main/x86_64/<br />
</nowiki>}}<br />
<br />
=== levitating ===<br />
<br />
* '''Maintainer''' [https://levitati.ng levitating]<br />
* '''Description''' An automatically build collection of my own hobby projects.<br />
*'''Key-ID''' [https://keyserver.ubuntu.com/pks/lookup?search=6DF9D13B4F64C91B&fingerprint=on&op=index 6DF9D13B4F64C91B]<br />
<br />
{{bc|<nowiki><br />
[levitating]<br />
Server = https://levitati.ng/archlinux/$repo/os/$arch<br />
</nowiki>}}<br />
<br />
=== linux-nitrous ===<br />
<br />
* '''Maintainer:''' [https://superboring.dev Simao Gomes Viana (superboringdev or xdevs23)]<br />
* '''Description:''' linux-nitrous is a repository with prebuilt packages of the [https://gitlab.com/xdevs23/linux-nitrous linux-nitrous kernel]<br />
* '''Git Repo:''' https://gitlab.com/xdevs23/linux-nitrous<br />
* '''Issue tracking:''' https://github.com/xdevs23/linux-nitrous/issues for packaging issues and questions<br />
* '''Key-ID:''' [https://keyserver.ubuntu.com/pks/lookup?op=get&search=0xE9C2DECAC962CB3AF1376D44148A9E3C9C3E3BF0 9C3E3BF0] (keyserver.ubuntu.com) | [https://pgp.mit.edu/pks/lookup?op=get&search=0x148A9E3C9C3E3BF0 9C3E3BF0] (pgp.mit.edu) | [http://pgp.net.nz:11371/pks/lookup?op=get&fingerprint=on&search=0x148A9E3C9C3E3BF0 9C3E3BF0] (pgp.net.nz)<br />
<br />
{{bc|<nowiki><br />
[linux-nitrous]<br />
Server = https://github.com/xdevs23/linux-nitrous/releases/latest/download<br />
</nowiki>}}<br />
<br />
=== linuxrepos ===<br />
<br />
* '''Maintainer:''' [[User:TheRepoClub|TheRepoClub]]<br />
* '''Description:''' A repository with some of the AUR packages that TheRepoClub use<br />
* '''Upstream page:''' https://arch.linuxrepos.org<br />
* '''Key-ID:''' [http://pgp.net.nz:11371/pks/lookup?op=vindex&fingerprint=on&search=0xE30EC2FBFB05C44F 75A38DC684F1A0B808918BCEE30EC2FBFB05C44F]<br />
<br />
{{bc|<nowiki><br />
[linuxrepos]<br />
Server = https://arch.linuxrepos.org/$arch/<br />
</nowiki>}}<br />
<br />
=== liquorix ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/damentz Steven Barrett (damentz)]<br />
* '''Description:''' Repository containing automated builds of {{AUR|linux-lqx}}, {{AUR|linux-lqx-headers}}, and {{AUR|linux-lqx-docs}}<br />
* '''Upstream page:''' https://liquorix.net<br />
* '''Git Repo:''' https://github.com/damentz/liquorix-package, https://aur.archlinux.org/cgit/aur.git/log/?h=linux-lqx<br />
* '''Issue tracking:''' https://github.com/damentz/liquorix-package/issues<br />
* '''Key-ID: ''' [https://keys.openpgp.org/vks/v1/by-fingerprint/C5ADB4F3FEBBCE27A3E54D7D9AE4078033F8024D 9AE4078033F8024D] (keys.openpgp.org)<br />
<br />
{{bc|<nowiki><br />
[liquorix]<br />
Server = https://liquorix.net/archlinux/$repo/$arch<br />
</nowiki>}}<br />
<br />
=== markzz ===<br />
<br />
* '''Maintainer:''' [[User:Markzz|Mark Weiman (markzz)]]<br />
* '''Description:''' Packages that markzz maintains or uses on the AUR; this includes Linux with the vfio patchset ({{AUR|linux-vfio}} and {{AUR|linux-vfio-lts}}), and packages for analysis of network data.<br />
* '''Key ID:''' DEBB9EE4<br />
<br />
{{Note|If you want to add the key by installing the ''markzz-keyring'' package, temporarily add {{ic|1=SigLevel = Never}} into the repository section.}}<br />
<br />
{{bc|<nowiki><br />
[markzz]<br />
Server = https://repo.markzz.com/arch/$repo/$arch<br />
</nowiki>}}<br />
<br />
=== miffe ===<br />
<br />
* '''Maintainer:''' [https://bbs.archlinux.org/profile.php?id=4059 miffe]{{Dead link|2023|05|06|status=403}}<br />
* '''Description:''' AUR packages maintained by miffe, e.g. linux-mainline<br />
* '''Key ID:''' 313F5ABD<br />
<br />
{{bc|<nowiki><br />
[miffe]<br />
Server = https://arch.miffe.org/$arch/<br />
</nowiki>}}<br />
<br />
=== mikelpint ===<br />
<br />
* '''Maintainer:''' [[User:Mikelpint|Mikel Pintado (Mikelpint)]]<br />
* '''Description:''' Packages that mikelpint maintains in the AUR.<br />
* '''Key ID:''' 5CA78FC65B189E2B<br />
<br />
{{bc|<nowiki><br />
[mikelpint]<br />
Server = https://mikelpint.github.io/repository/archlinux/repo<br />
</nowiki>}}<br />
<br />
=== Minerva W Science ===<br />
<br />
* '''Maintainer:''' Minerva W<br />
* '''Description:''' [[OpenFOAM]] packages.<br />
* '''Key-ID:''' 3FF21B78117507DA<br />
* '''Keyfile:''' https://download.opensuse.org/repositories/home:/Minerva_W:/Science/Arch_Extra/x86_64/home_Minerva_W_Science_Arch_Extra.key{{Dead link|2023|05|06|status=404}}<br />
<br />
{{bc|<nowiki><br />
[home_Minerva_W_Science_Arch_Extra]<br />
Server = https://download.opensuse.org/repositories/home:/Minerva_W:/Science/Arch_Extra/$arch <br />
</nowiki>}}<br />
<br />
=== mxmeinhold ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/mxmeinhold mxmeinhold]<br />
* '''Description:''' Packages I maintain in the AUR, currently just factorio-headless<br />
* '''Key ID:''' B77D730E8D444707FA93320D72E05836F8252405<br />
* '''Keyfile:''' https://gpg.mxmeinhold.com<br />
<br />
{{bc|<nowiki><br />
[mxmeinhold]<br />
Server = https://arch.mxmeinhold.com/$arch<br />
</nowiki>}}<br />
<br />
=== orhun ===<br />
<br />
* '''Maintainer:''' [https://archlinux.org/people/trusted-users/#orhun Orhun Parmaksiz]<br />
* '''Description:''' Personal repository with AUR and custom packages.<br />
* '''Key-ID:''' Not needed, as the maintainer is a TU<br />
<br />
{{bc|<nowiki><br />
[orhun]<br />
Server = https://pkgbuild.com/~orhun/repo<br />
</nowiki>}}<br />
<br />
=== origincode ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/OriginCode OriginCode]<br />
* '''Description:''' A few staging or testing packages from [[#archlinuxcn]], and some daily use packages.<br />
* '''Key-ID:''' 0A5BAD445D80C1CC & 62BF97502AE10D22<br />
<br />
{{bc|<nowiki><br />
[origincode]<br />
Server = https://repo.origincode.me/repo/$arch<br />
</nowiki>}}<br />
<br />
=== oscloud ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/bionade24 bionade24]<br />
* '''Description:''' <s>ROS melodic packages and necessary dependencies,</s> various cmd-line tools, and other packages from the AUR.<br />
* '''CI/CD status:''' https://abs-cd.oscloud.info<br />
* '''Key-ID:''' A4A0D73114FDE6FC<br />
<br />
{{bc|<nowiki><br />
[oscloud]<br />
Server = http://repo.oscloud.info/<br />
</nowiki>}}<br />
<br />
=== ownstuff ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/Martchus Martchus]<br />
* '''Description:''' A lot of packages from the AUR, e.g. a great number packages for mingw-w64 and Android cross compilation, fonts, Perl modules, tools like {{AUR|tageditor}}, {{AUR|syncthingtray}}, {{AUR|subtitlecomposer}} and {{AUR|qmplay2}}<br />
* '''Upstream page''': https://github.com/Martchus/PKGBUILDs (sources beside the AUR) and https://martchus.no-ip.biz/buildservice/#package-search-section (package browser/search)<br />
* '''Key-ID:''' B9E36A7275FC61B464B67907E06FE8F53CDC6A4C<br />
<br />
{{bc|<nowiki><br />
[ownstuff-testing]<br />
Server = https://ftp.f3l.de/~martchus/$repo/os/$arch<br />
Server = https://martchus.no-ip.biz/repo/arch/$repo/os/$arch<br />
<br />
[ownstuff]<br />
Server = https://ftp.f3l.de/~martchus/$repo/os/$arch<br />
Server = https://martchus.no-ip.biz/repo/arch/$repo/os/$arch<br />
</nowiki>}}<br />
<br />
{{Note|The testing repository is supposed to be used together with the official testing repositories.}}<br />
<br />
=== phillid-custom ===<br />
<br />
* '''Maintainer:''' [https://yeah.nah.nz phillid]<br />
* '''Description:''' Pre-built versions of the (slow-to-build) graph-tool python libraries, mingw-w64<br />
* '''Key ID:''' 7BF3D17D0884BF5B<br />
{{bc|<nowiki><br />
[phillid-custom]<br />
Server = https://repo.nah.nz/$repo<br />
</nowiki>}}<br />
<br />
=== pkgbuilder ===<br />
<br />
* '''Maintainer:''' [https://chriswarrick.com/ Chris Warrick]<br />
* '''Description:''' A repository for PKGBUILDer, a Python AUR helper.<br />
* '''Upstream page:''' https://github.com/Kwpolska/pkgbuilder<br />
* '''Key-ID:''' 5EAAEA16<br />
<br />
{{bc|<nowiki><br />
[pkgbuilder]<br />
Server = https://pkgbuilder-repo.chriswarrick.com/<br />
</nowiki>}}<br />
<br />
=== PolarRepo ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/PolarianDev PolarianDev] ([[User:PolarianDev]])<br />
* '''Maintainer Email:''' polarian@polarian.dev<br />
*'''Description:''' Packages which are maintained by PolarianDev within the AUR<br />
* '''Key-ID:''' D7E35661EB1A280A (old: {{ic|0770E5312238C760}}) ([https://git.polarian.dev/AUR/polarrepo/src/branch/master/pkg/keys/polarian.asc Direct Link] [https://keys.openpgp.org Keyserver])<br />
* '''Website:''' https://git.polarian.dev/AUR/polarrepo<br />
* '''Issues:''' https://git.polarian.dev/AUR/polarrepo/issues<br />
<br />
{{bc|<nowiki><br />
[polarrepo]<br />
Server = https://polarrepo.polarian.dev/<br />
</nowiki>}}<br />
<br />
=== post-factum kernels ===<br />
<br />
* '''Maintainer''': [https://aur.archlinux.org/account/post-factum Oleksandr Natalenko aka post-factum]<br />
* '''Upstream page''': https://pfkernel.natalenko.name<br />
* '''Description''': [[linux-pf|pf-kernel]] packages by its developer, post-factum<br />
* '''Key-ID:''': 95C357D2AF5DA89D<br />
* '''Keyfile''': https://download.opensuse.org/repositories/home:/post-factum:/kernels/Arch/x86_64/home_post-factum_kernels_Arch.key<br />
<br />
{{bc|<nowiki><br />
[home_post-factum_kernels_Arch]<br />
Server = https://download.opensuse.org/repositories/home:/post-factum:/kernels/Arch/$arch<br />
</nowiki>}}<br />
<br />
=== pro-audio-legacy ===<br />
<br />
* '''Maintainer:''' [https://archlinux.org/people/developers/#dvzrv David Runge]<br />
* '''Description:''' Legacy tooling for [[pro-audio]] (e.g. {{AUR|jack}}), mainly useful for old setups or CI<br />
* '''Key-ID:''' Not needed, as maintainer is a developer/TU<br />
<br />
{{bc|<nowiki><br />
[pro-audio-legacy]<br />
Server = https://pkgbuild.com/~dvzrv/repos/pro-audio-legacy/$arch<br />
</nowiki>}}<br />
<br />
=== proaudio ===<br />
<br />
* '''Maintainer:''' [https://github.com/osam-cologne/ OSAMC] members ([https://aur.archlinux.org/account/SpotlightKid SpotlightKid], [https://aur.archlinux.org/account/cbix cbix], [https://aur.archlinux.org/account/daniel.appelt daniel.appelt] et al.)<br />
* '''Description:''' [[Pro Audio]] packages not (yet) in the official repos, built for x86_64 and aarch64<br />
* '''Upstream page:''' https://arch.osamc.de/<br />
* '''GitHub repo:''' https://github.com/osam-cologne/archlinux-proaudio (PRs welcome)<br />
* '''Key-ID:''' 762AE5DB2B38786364BD81C4B9141BCC62D38EE5<br />
* '''Keyfile:''' https://arch.osamc.de/proaudio/osamc.gpg<br />
<br />
{{bc|<nowiki><br />
[proaudio]<br />
Server = https://arch.osamc.de/$repo/$arch<br />
</nowiki>}}<br />
<br />
=== QOwnNotes ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/pbek Patrizio Bekerle] (pbek), QOwnNotes author<br />
* '''Description:''' QOwnNotes is an open-source notepad and todo list manager with markdown support and [[ownCloud]] integration.<br />
* '''Key-ID:''' FFC43FC94539B8B0<br />
* '''Keyfile:''' https://download.opensuse.org/repositories/home:/pbek:/QOwnNotes/Arch_Extra/x86_64/home_pbek_QOwnNotes_Arch_Extra.key<br />
<br />
{{bc|<nowiki><br />
[home_pbek_QOwnNotes_Arch_Extra]<br />
Server = https://download.opensuse.org/repositories/home:/pbek:/QOwnNotes/Arch_Extra/$arch<br />
</nowiki>}}<br />
<br />
=== quarry ===<br />
<br />
* '''Maintainer:''' [https://archlinux.org/people/developers/#anatolik anatolik]<br />
* '''Description:''' Arch binary repository for [https://rubygems.org/ Rubygems] packages. See [https://bbs.archlinux.org/viewtopic.php?id=182729 forum announcement] for more information.<br />
* '''Sources:''' https://github.com/anatol/quarry<br />
* '''Key-ID:''' Not needed, as the maintainer is a developer<br />
<br />
{{bc|<nowiki><br />
[quarry]<br />
Server = https://pkgbuild.com/~anatolik/quarry/x86_64/<br />
</nowiki>}}<br />
<br />
=== realtime ===<br />
<br />
{{warning| This repository is phased out and only available until 2023-01-01 (for compatibility). The packages have been moved to the official repositories ({{pkg|linux-rt}} and {{pkg|linux-rt-lts}}).}}<br />
<br />
* '''Maintainer:''' [https://archlinux.org/people/developers/#dvzrv David Runge]<br />
* '''Description:''' [[Realtime kernel patchset]] (aka. {{Pkg|linux-rt}} and {{Pkg|linux-rt-lts}})<br />
* '''Key-ID:''' Not needed, as maintainer is a developer/TU<br />
<br />
{{bc|<nowiki><br />
[realtime]<br />
Server = https://pkgbuild.com/~dvzrv/repos/realtime/$arch<br />
</nowiki>}}<br />
<br />
=== repo-ck ===<br />
<br />
Kernel and modules with Brain Fuck Scheduler and all the goodies in the ck1 patch set.<br />
<br />
See [[/Repo-ck]].<br />
<br />
=== repo.mksscryertower.quest ===<br />
<br />
* '''Maintainer:''' [[User:Scry3r|Klimenko Maxim Sergievich]]<br />
* '''Description:''' Collection of AUR packages that I personally use: Opensnitch-ebpf, libraries and etc. Repo has backups and some old version of the packages for backward compatibility in index of /repo/ .<br />
* '''Key-ID:''' [https://keyserver.ubuntu.com/pks/lookup?search=8A36037D80912162&fingerprint=on&op=index 8A36037D80912162]<br />
<br />
{{bc|<nowiki><br />
[repo.mksscryertower.quest]<br />
Server = https://repo.mksscryertower.quest/repo/x86_64/<br />
</nowiki>}}<br />
<br />
=== rne ===<br />
<br />
* '''Maintainer:''' [[User:Schard|Richard Neumann]]<br />
* '''Description:''' Collection of AUR packages that I personally use.<br />
* '''Key-ID:''' [https://keyserver.ubuntu.com/pks/lookup?search=4CA8D523BD386AF7&fingerprint=on&op=index 4CA8D523BD386AF7]<br />
<br />
{{bc|<nowiki><br />
[rne]<br />
Server = https://srv.richard-neumann.de/pub/repo/<br />
</nowiki>}}<br />
<br />
=== seblu ===<br />
<br />
* '''Maintainer:''' [https://archlinux.org/people/developers/#seblu Sébastien Luttringer]<br />
* '''Description:''' All seblu useful pre-built packages, some homemade (linux-seblu-meta, zfs-dkms, spotify, masterpdfeditor, etc).<br />
* '''Key-ID:''' Not required, as the maintainer is a Developer<br />
<br />
{{bc|<nowiki><br />
[seblu]<br />
Server = https://al1.seblu.net/$repo/$arch<br />
Server = https://al2.seblu.net/$repo/$arch<br />
</nowiki>}}<br />
<br />
=== seiichiro ===<br />
<br />
* '''Maintainer:''' [https://www.seiichiro0185.org Stefan Brand (seiichiro0185)]<br />
* '''Description:''' AUR-packages I use frequently<br />
* '''Key-ID:''' 805517CC<br />
<br />
{{bc|<nowiki><br />
[seiichiro]<br />
Server = https://www.seiichiro0185.org/repo/$arch<br />
</nowiki>}}<br />
<br />
=== sergej-repo ===<br />
<br />
* '''Maintainer:''' [https://archlinux.org/people/trusted-users/#spupykin Sergej Pupykin]<br />
* '''Description:''' nextcloud, prosody, and some other stuff.<br />
* '''Key-ID:''' Not required, as the maintainer is a TU<br />
<br />
{{bc|<nowiki><br />
[sergej-repo]<br />
Server = http://repo.p5n.pp.ru/$repo/os/$arch<br />
</nowiki>}}<br />
<br />
=== slowbro ===<br />
<br />
* '''Maintainer:''' Katelyn Schiesser (slowbro)<br />
* '''Description:''' binary packages for {{AUR|linux-vfio}}<br />
* '''Key-ID:''' [https://pgp.mit.edu/pks/lookup?search=0xAB3139C285186206 85186206]<br />
<br />
{{bc|<nowiki><br />
[slowbro]<br />
Server = http://www.slowbro.org/arch/$arch/<br />
</nowiki>}}<br />
<br />
=== sublime-text ===<br />
<br />
* '''Maintainer:''' Sublime Text developer<br />
* '''Description:''' Sublime Text editor packages from developer's repository<br />
* '''Upstream page:''' https://www.sublimetext.com/docs/3/linux_repositories.html#pacman<br />
* '''Key-ID:''' 8A8F901A<br />
<br />
{{bc|<nowiki><br />
[sublime-text]<br />
Server = https://download.sublimetext.com/arch/stable/x86_64<br />
</nowiki>}}<br />
<br />
=== subtitlecomposer ===<br />
<br />
* '''Maintainer:''' Mladen Milinkovic (maxrd2)<br />
* '''Description:''' Subtitle Composer stable and nightly builds<br />
* '''Upstream page:''' https://github.com/maxrd2/subtitlecomposer<br />
* '''Key-ID:''' 4E8D5DBD<br />
<br />
{{bc|<nowiki><br />
[subtitlecomposer]<br />
Server = https://smoothware.net/$repo/$arch<br />
</nowiki>}}<br />
<br />
=== speedie-aur ===<br />
<br />
* '''Maintainer:''' [https://speedie.site speedie]<br />
* '''Description:''' Repository of packages for software I use.<br />
* '''Git Repository:''' https://git.speedie.site/speedie/speedie-aur<br />
* '''Key-ID:''' CEB863B830D1318A<br />
<br />
{{bc|<nowiki><br />
[speedie-aur]<br />
Server = https://git.speedie.site/speedie/speedie-aur/raw/branch/master/$arch<br />
</nowiki>}}<br />
<br />
=== supermario ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/supermario Mario Finelli (supermario)]<br />
* '''Description:''' AUR packages that I use or maintain<br />
* '''Git Repository:''' https://github.com/mfinelli/pkgs, https://github.com/mfinelli/aur-packages<br />
* '''Key-ID:''' C3CD75B002978A8468CA7B1F6C3ADDDE36FDA306<br />
* '''Keyfile:''' https://finelli.pub/36FDA306.asc<br />
<br />
{{bc|<nowiki><br />
[supermario]<br />
Server = https://pkgs.finelli.dev/arch/$arch<br />
</nowiki>}}<br />
<br />
=== trinity ===<br />
<br />
* '''Maintainer:''' [https://trinitydesktop.org/ Trinity Desktop Environment Developers]<br />
* '''Description:''' [[Trinity]] Desktop Environment<br />
* '''Key-ID:''' 8685AD8B<br />
<br />
{{bc|<nowiki><br />
[trinity]<br />
Server = https://mirror.ppa.trinitydesktop.org/trinity/archlinux/$arch<br />
</nowiki>}}<br />
<br />
=== valveaur ===<br />
<br />
* '''Maintainer:''' John Schoenick <johns@valvesoftware.com> (https://valvesoftware.com)<br />
* '''Description:''' A repository by Valve Software Providing The Linux-fsync kernel and modules, including the futex-wait-multiple patchset for testing with Proton fsync & Mesa with the ACO compiler patchset. <br />
* '''Upstream page:''' https://steamcommunity.com/linux<br />
* '''Key-ID:''' 8DC2CE3A3D245E64<br />
<br />
{{bc|<nowiki><br />
[valveaur]<br />
Server = http://repo.steampowered.com/arch/valveaur<br />
</nowiki>}}<br />
<br />
=== wsdm ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/WSDMatty Matthew Sexton]<br />
* '''Description:''' AUR packages I maintain/comaintain plus their AUR dependencies.<br />
* '''Git Repository:''' https://github.com/wsdmatty/wsdm<br />
* '''Key-ID:''' [https://keyserver.ubuntu.com/pks/lookup?search=97928FA059F8050487930EAFACF6C1A315EDCB52&fingerprint=on&exact=on&op=index 97928fa059f8050487930eafacf6c1a315edcb52]<br />
<br />
{{bc|<nowiki><br />
[wsdm]<br />
Server = https://wsdmatty.github.io/$repo/$arch<br />
</nowiki>}}<br />
<br />
=== xuanrui ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/xuanruiqi Xuanrui Qi (xuanruiqi)]<br />
* '''Description:''' xuanruiqi's own packages and frequently-used packages, mainly of interest to functional programmers.<br />
* '''Upstream Page:''' https://www.xuanruiqi.com/linux.html<br />
* '''Key-ID:''' 6E06FBC8<br />
<br />
{{bc|<nowiki><br />
[xuanrui]<br />
Server = https://arch.xuanruiqi.com/repo<br />
</nowiki>}}<br />
<br />
=== xyne-x86_64 ===<br />
<br />
* '''Maintainer:''' [https://archlinux.org/people/trusted-users/#xyne Xyne]<br />
* '''Description:''' A repository for Xyne's own projects.<br />
* '''Upstream page:''' https://xyne.dev/projects/<br />
* '''Key-ID:''' Not required, as maintainer is a TU<br />
<br />
{{bc|<nowiki><br />
[xyne-x86_64]<br />
Server = https://xyne.dev/repos/xyne<br />
</nowiki>}}<br />
<br />
== Unsigned ==<br />
<br />
{{Note|Users will need to add the following to these entries: {{ic|1=SigLevel = PackageOptional}}}}<br />
<br />
{{Warning|HTTP must not be used for unsigned repositories, without HTTPS there is no validity check that the content you have downloaded was the content which the web server was serving, potentially allowing a [[Wikipedia:Man-in-the-middle attack|MiTM (Man in The Middle) attack]] to install any software to your system. HTTPS mitigates such vulnerability.}}<br />
<br />
=== alucryd ===<br />
<br />
* '''Maintainer:''' [https://archlinux.org/people/trusted-users/#alucryd Maxime Gauduin]<br />
* '''Description:''' Various packages Maxime Gauduin maintains (or not) in the AUR.<br />
<br />
{{bc|<nowiki><br />
[alucryd]<br />
Server = https://pkgbuild.com/~alucryd/$repo/x86_64<br />
</nowiki>}}<br />
<br />
=== alucryd-multilib ===<br />
<br />
* '''Maintainer:''' [https://archlinux.org/people/trusted-users/#alucryd Maxime Gauduin]<br />
* '''Description:''' Various packages needed to run Steam without its runtime environment.<br />
<br />
{{bc|<nowiki><br />
[alucryd-multilib]<br />
Server = https://pkgbuild.com/~alucryd/$repo/x86_64<br />
</nowiki>}}<br />
<br />
=== andrwe ===<br />
<br />
* '''Maintainer:''' Andrwe Lord Weber<br />
* '''Description:''' contains programs I'm using on many systems<br />
* '''Upstream page:''' https://andrwe.org/linux/repository<br />
<br />
{{bc|<nowiki><br />
[andrwe]<br />
Server = http://repo.andrwe.org/$arch<br />
</nowiki>}}<br />
<br />
=== arch-mact2 ===<br />
<br />
* '''Maintainer:''' [https://noa.codes Noa Himesaka]<br />
* '''Description:''' Additional kernel and utilities for use on Macs with T2 security chip, complementing archlinux-t2-packages. Should be used in conjunction with [[#archlinux-t2-packages|archlinux-t2-packages]] repository.<br />
* '''Upstream page:''' https://mirror.funami.tech/arch-mact2<br />
<br />
{{bc|<nowiki><br />
[arch-mact2]<br />
Server = https://mirror.funami.tech/arch-mact2/os/$arch<br />
</nowiki>}}<br />
<br />
=== archgeotux ===<br />
<br />
* '''Maintainer:''' Samuel Mesa<br />
* '''Description:''' Geospatial and geographic information system applications<br />
* '''Upstream page:''' https://archgeotux.sourceforge.io/<br />
<br />
{{bc|<nowiki><br />
[archgeotux]<br />
Server = https://sourceforge.net/projects/$repo/files/$arch/<br />
</nowiki>}}<br />
<br />
=== archlinuxfr ===<br />
<br />
* '''Maintainer:''' <br />
* '''Description:''' <br />
* '''Note:''' Contributors have to read [https://forums.archlinux.fr/viewtopic.php?f=16&t=22324 the rules related to this repository (fr)]<br />
* '''Upstream page:''' http://afur.archlinux.fr<br />
<br />
{{bc|<nowiki><br />
[archlinuxfr]<br />
Server = https://repo.archlinux.fr/$arch<br />
</nowiki>}}<br />
<br />
=== archlinuxgr ===<br />
<br />
* '''Maintainer:'''<br />
* '''Description:''' many interesting packages provided by the Hellenic (Greek) Arch Linux community<br />
<br />
{{bc|<nowiki><br />
[archlinuxgr]<br />
Server = https://archlinuxgr.tiven.org/archlinux/$arch<br />
</nowiki>}}<br />
<br />
=== archlinuxir ===<br />
<br />
* '''Maintainer:''' Bardia Moshiri<br />
* '''Description:''' Most used packages by the Iranian Arch Linux community.<br />
* '''Note:''' Server is hosted in Iran and traffic from Iranian IP's will count as half from ISP's (Nim baha).<br />
* '''Note:''' Keep in mind that the repository is updated every 6 hours.<br />
* '''Upstream page:''' https://mirror.bardia.tech<br />
<br />
{{bc|<nowiki><br />
[archlinuxir]<br />
Server = https://mirror.bardia.tech/archlinuxir/$arch<br />
</nowiki>}}<br />
<br />
=== archlinux-phalcon ===<br />
<br />
* '''Maintainer:''' Michal Sotolar <michal at sotolar dot com><br />
* '''Description:''' Phalcon Framework PHP 5.6 - 7.x extension builds<br />
* '''Upstream page:''' https://archlinux-phalcon.gitlab.io<br />
<br />
{{bc|<nowiki><br />
[archlinux-phalcon]<br />
Server = https://archlinux-phalcon.gitlab.io/repository<br />
</nowiki>}}<br />
<br />
=== archlinux-php ===<br />
<br />
* '''Maintainer:''' Michal Sotolar <michal at sotolar dot com><br />
* '''Description:''' PHP 5.6 - 7.x old stable builds coexistable with mainline version<br />
* '''Upstream page:''' https://archlinux-php.gitlab.io<br />
<br />
{{bc|<nowiki><br />
[archlinux-php]<br />
Server = https://archlinux-php.gitlab.io/repository<br />
</nowiki>}}<br />
<br />
=== archmint ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/ArchMint ArchMint]<br />
* '''Description:''' ArchMint GNU/Linux packages from developer's repository<br />
* '''Upstream page:''' https://sourceforge.net/projects/archmint/files/repo/<br />
<br />
{{bc|<nowiki><br />
[archmint]<br />
Server = https://sourceforge.net/projects/archmint/files/repo/$arch<br />
</nowiki>}}<br />
<br />
=== dx37essentials ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/DragonX256 DragonX256]<br />
* '''Description:''' Personal repository. Contains packages from AUR, which I using every day.<br />
* '''Git repo:''' https://gitlab.com/DX37/dx37essentials<br />
* '''Upstream page:''' https://dx3756.ru/dx37essentials<br />
<br />
{{bc|<nowiki><br />
[dx37essentials]<br />
Server = https://dx3756.ru/$repo/$arch<br />
Server = https://dx37.gitlab.io/$repo/$arch<br />
</nowiki>}}<br />
<br />
=== ede ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/kraileth kraileth]<br />
* '''Description:''' Unofficial Arch Linux repository for the Equinox Desktop Environment.<br />
* '''Git repo:''' https://github.com/edeproject/ede<br />
* '''Upstream page:''' https://edeproject.org/<br />
<br />
{{bc|<nowiki><br />
[ede]<br />
Server = http://ede.elderlinux.org/repos/archlinux/$arch<br />
</nowiki>}}<br />
<br />
=== extra-alucryd ===<br />
<br />
* '''Maintainer:''' [https://archlinux.org/people/trusted-users/#alucryd Maxime Gauduin]<br />
* '''Description:''' Various supplemental packages Maxime Gauduin maintains (or not) in the AUR.<br />
* '''Upstream page:''' https://github.com/FFY00/arch-python-repo<br />
<br />
{{bc|<nowiki><br />
[extra-alucryd]<br />
Server = https://pkgbuild.com/~alucryd/$repo/$arch<br />
</nowiki>}}<br />
<br />
=== ffy00 (python) ===<br />
<br />
* '''Maintainer:''' [https://archlinux.org/people/trusted-users/#FFY00 Filipe Laíns]<br />
* '''Description:''' Provides several different Python versions (eg. 3.5, 3.6, 3.7). All active Python releases should be available here.<br />
* '''Git repo:''' https://github.com/FFY00/arch-python-repo<br />
* '''Upstream page:''' https://github.com/FFY00/arch-python-repo<br />
<br />
{{bc|<nowiki><br />
[python]<br />
Server = https://ffy00.github.io/arch-python-repo/<br />
</nowiki>}}<br />
<br />
=== gpd-pocket-arch ===<br />
<br />
* '''Maintainer:''' [https://github.com/joshskidmore Josh Skidmore]<br />
* '''Description:''' Unofficial Arch Linux repository for the GPD Pocket.<br />
* '''Git repo:''' https://github.com/joshskidmore/gpd-pocket-arch<br />
* '''Upstream page:''' https://github.com/joshskidmore/gpd-pocket-arch<br />
<br />
{{bc|<nowiki><br />
[gpd-pocket-arch]<br />
Server = https://github.com/joshskidmore/gpd-pocket-arch/raw/master<br />
</nowiki>}}<br />
<br />
=== heftig ===<br />
<br />
* '''Maintainer:''' [https://archlinux.org/people/developers/#heftig Jan Alexander Steffens]<br />
* '''Description:''' Includes [https://pkgbuild.com/~heftig/packages/firefox-nightly/ firefox-nightly], {{AUR|freetype2-git}} and [https://pkgbuild.com/~heftig/packages/stone-soup-git/ stone-soup-git]<br />
* '''Upstream page:''' https://bbs.archlinux.org/viewtopic.php?id=117157<br />
<br />
{{bc|<nowiki><br />
[heftig]<br />
Server = https://pkgbuild.com/~heftig/repo/$arch<br />
</nowiki>}}<br />
<br />
=== jd-64 ===<br />
* '''Maintainer:''' [https://github.com/JaydenDev JaydenDev]<br />
* '''Description:''' My software as well as pre-built AUR packages!<br />
* '''Upstream page:''' https://github.com/JaydenDev/jd-64<br />
<br />
{{bc|<nowiki><br />
[jd-64]<br />
Server = https://jdev.eu.org/jd-64/x86_64/<br />
</nowiki>}}<br />
<br />
=== juju ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/Juju Juju]<br />
* '''Description:''' Emulators and development tools for some retro computers, along with some AUR packages I use<br />
* '''Upstream page:''' https://dev.azure.com/juju2143/archbuilds<br />
<br />
{{bc|<nowiki><br />
[juju]<br />
Server = https://a39.ca/archlinux/$repo/os/$arch<br />
</nowiki>}}<br />
<br />
=== kernel ===<br />
<br />
* '''Maintainer:''' blacksy3 <blacksky3@tuta.io><br />
* '''Description:''' Prebuilt packages for XanMod and Liquorix kernel with config tweak for performance<br />
* '''Git repo:''' https://github.com/blacksky3/linux-xanmod.git<br />
* '''Git repo:''' https://github.com/blacksky3/linux-lqx.git<br />
* '''Upstream page:''' https://repo.blacksky3.com/<br />
<br />
{{bc|<nowiki><br />
[kernel]<br />
Server = https://repo.blacksky3.com/$arch/$repo<br />
</nowiki>}}<br />
<br />
=== kicad-nightly ===<br />
<br />
* '''Maintainer:''' Rafael Silva <perigoso@riseup.net><br />
* '''Description:''' Prebuilt nightly packages for KiCad<br />
* '''Git repo:''' https://gitlab.com/kicad/packaging/kicad-arch/kicad-arch-builder<br />
* '''Upstream page:''' https://www.kicad.org/help/nightlies-and-rcs/<br />
<br />
{{bc|<nowiki><br />
[kicad-nightly]<br />
Server = https://kicad.gitlab.io/packaging/kicad-arch/kicad-arch-builder/<br />
</nowiki>}}<br />
<br />
=== Linux-Yaok ===<br />
<br />
* '''Maintainer:''' [https://github.com/Gontier-Julien Snowy chan]<br />
* '''Description:''' Yet Another Optimized Kernel, Linux Yaok is a kernel with Stability First and Performance in mind.<br />
* '''Upstream page:''' https://github.com/Gontier-Julien/Linux-YAOK<br />
{{bc|<nowiki><br />
[linux-yaok]<br />
Server = https://linuxyaok.dedyn.io/<br />
</nowiki>}}<br />
<br />
=== mesa-git ===<br />
<br />
* '''Maintainer:''' [https://archlinux.org/people/trusted-users/#lcarlier Laurent Carlier]<br />
* '''Description:''' Mesa git builds for the [[testing]] repositories<br />
<br />
{{bc|<nowiki><br />
[mesa-git]<br />
Server = https://pkgbuild.com/~lcarlier/$repo/$arch<br />
</nowiki>}}<br />
<br />
=== oracle ===<br />
<br />
* '''Maintainer:''' [[User:Malvineous]]<br />
* '''Description:''' [[Oracle Database client]] and associated tools, built from AUR packages and hosted on AWS S3 using [https://github.com/Malvineous/archlinux-pacman-repo Makefile scripts].<br />
* '''Conditions:''' By using this repository you agree to the [http://www.oracle.com/technetwork/licenses/instant-client-lic-152016.html Oracle Technology Network Development and Distribution License Terms for Instant Client].<br />
{{bc|<nowiki><br />
[oracle]<br />
Server = http://linux.shikadi.net/arch/$repo/$arch/<br />
</nowiki>}}<br />
<br />
=== principia ===<br />
<br />
* '''Maintainer:''' ROllerozxa <rollerozxa@voxelmanip.se><br />
* '''Description:''' Binary builds of the {{AUR|principia-git}} package.<br />
* '''Upstream page:''' https://grejer.voxelmanip.se/principia/arch-repo/<br />
<br />
{{bc|<nowiki><br />
[principia]<br />
Server = https://grejer.voxelmanip.se/principia/arch-repo/$arch<br />
</nowiki>}}<br />
<br />
=== pietma ===<br />
<br />
* '''Maintainer:''' MartiMcFly <martimcfly@autorisation.de><br />
* '''Description:''' Arch User Repository packages [https://aur.archlinux.org/packages/?K=martimcfly&SeB=m I create or maintain.].<br />
* '''Upstream page:''' http://pietma.com/tag/aur/<br />
<br />
{{bc|<nowiki><br />
[pietma]<br />
Server = https://repository.pietma.com/nexus/content/repositories/archlinux/$arch/$repo<br />
</nowiki>}}<br />
<br />
=== pnsft-pur ===<br />
<br />
* '''Maintainer:''' [https://aur.archlinux.org/account/ponsfoot ponsfoot]<br />
* '''Description:''' Japanese input method packages Mozc (vanilla) and libkkc<br />
<br />
{{bc|<nowiki><br />
[pnsft-pur]<br />
Server = https://osdn.net/projects/ponsfoot-aur/storage/pur/x86_64/<br />
</nowiki>}}<br />
<br />
=== rayr ===<br />
<br />
* '''Maintainer:''' [https://rayr.ml/LinkInBio Rayr]{{Dead link|2023|07|30|status=domain name not resolved}}<br />
* '''Description:''' Prebuilt packages of my AUR packages, as an Arch repo.<br />
* '''Upstream page:''' https://github.com/Rayrsn/ArchRepo<br />
<br />
{{bc|<nowiki><br />
[rayr]<br />
Server = https://rayrsn.github.io/ArchRepo/$arch<br />
</nowiki>}}<br />
<br />
=== rstudio ===<br />
<br />
* '''Maintainer:''' Artem Klevtsov <a.a.klevtsov@gmail.com><br />
* '''Description:''' RStudio IDE packages.<br />
* '''Upstream page:''' https://gitlab.com/aur1/rstudio<br />
<br />
{{bc|<nowiki><br />
[rstudio]<br />
Server = https://aur1.gitlab.io/$repo/$arch<br />
</nowiki>}}<br />
<br />
=== selinux ===<br />
<br />
* '''Maintainer:''' Nicolas Iooss (nicolas <dot> iooss <at> m4x <dot> org)<br />
* '''Description:''' Provide binary packages for [[SELinux]].<br />
* '''Upstream Page:''' https://github.com/archlinuxhardened/selinux<br />
<br />
{{bc|<nowiki><br />
[selinux]<br />
Server = https://github.com/archlinuxhardened/selinux/releases/download/ArchLinux-SELinux<br />
SigLevel = Never<br />
</nowiki>}}<br />
<br />
=== stx4 ===<br />
<br />
* '''Maintainer:''' StarterX4 <starterx4[at]gmail.com><br />
* '''Description:''' Any – some fonts and fakepkgs; x86_64 – archival yet might useful packages (like PacmanXG4), and some AUR soft I use[d].<br />
* '''Upstream Page:''' https://github.com/StarterX4/StarterX4.github.io<br />
<br />
{{bc|<nowiki><br />
[stx4-any]<br />
Server = https://starterx4.github.io/repos/arch/any/stx4<br />
<br />
[stx4-x86_64]<br />
Server = https://starterx4.github.io/repos/arch/x86_64/stx4<br />
</nowiki>}}<br />
<br />
=== symbiflow-git ===<br />
<br />
* '''Maintainer:''' Filipe Laíns <lains@archlinux.org><br />
* '''Description:''' Nightly builds for SymbiFlow components and related projects (mostly FPGA related projects).<br />
{{bc|<nowiki><br />
[symbiflow-git]<br />
Server = https://ffy00.github.io/symbiflow-arch-pkgs/<br />
</nowiki>}}<br />
<br />
=== thirtythreeforty ===<br />
<br />
* '''Maintainer:''' George Hilliard <thirtythreeforty@gmail.com><br />
* '''Description:''' Nightly builds for KiCAD development packages {{AUR|kicad-nightly}} and {{AUR|kicad-git}}<br />
{{bc|<nowiki><br />
[thirtythreeforty]<br />
Server = https://archrepo.thirtythreeforty.net/repo/thirtythreeforty<br />
</nowiki>}}<br />
<br />
=== userrepository ===<br />
<br />
* '''Maintainer:''' [https://twitter.com/brunomiguel Bruno Miguel] <bruno@privacyrequired.com> and <brunoalexandremiguel@gmail.com><br />
* '''Description:''' Repository containing software from AUR<br />
{{bc|<nowiki><br />
[userrepository]<br />
Server = https://userrepository.eu<br />
</nowiki>}}<br />
<br />
=== vdr4arch ===<br />
<br />
* '''Maintainers:''' [https://aur.archlinux.org/account/CReimer CReimer], [https://aur.archlinux.org/account/M-Reimer M-Reimer]<br />
* '''Description:''' A set of VDR packages for Arch Linux<br />
* '''Upstream page:''' https://github.com/VDR4Arch/vdr4arch<br />
<br />
{{Note|Packages are automatically built with [https://github.com/VDR4Arch/vdr4arch/blob/master/.ci/repo-make-ci.sh repo-make-ci.sh].}}<br />
<br />
{{bc|<nowiki><br />
[vdr4arch]<br />
Server = https://vdr4arch.github.io/$arch<br />
</nowiki>}}<br />
<br />
== Packages search ==<br />
<br />
{{Warning|{{ic|pkgs.org}} lists [[Arch Linux ARM]] aarch64 repositories as official under the Arch Linux organisation, this is factually incorrect, these repositories are unofficial and you use them at your own risk.}}<br />
<br />
Many of the unofficial Arch Linux repositories are indexed on https://archlinux.pkgs.org/.<br />
<br />
It provides repositories browser and packages search.</div>Malcontenthttps://wiki.archlinux.org/index.php?title=Arch_compared_to_other_distributions&diff=783110Arch compared to other distributions2023-07-14T05:12:09Z<p>Malcontent: Add , to number</p>
<hr />
<div>[[Category:About Arch]]<br />
[[bs:Arch compared to other distributions]]<br />
[[cs:Arch compared to other distributions]]<br />
[[de:Arch vs. Distribution X]]<br />
[[es:Arch compared to other distributions]]<br />
[[fa:آرچ در مقایسه با سایر توزیعها]]<br />
[[fi:Arch compared to other distributions]]<br />
[[fr:Arch compared to other distributions]]<br />
[[id:Arch compared to other distributions]]<br />
[[it:Arch compared to other distributions]]<br />
[[ja:Arch と他のディストリビューションの比較]]<br />
[[lt:Arch compared to other distributions]]<br />
[[pt:Arch compared to other distributions]]<br />
[[ru:Arch compared to other distributions]]<br />
[[tr:Arch compared to other distributions]]<br />
[[uk:Arch compared to other distributions]]<br />
[[zh-hans:Arch compared to other distributions]]<br />
{{Related articles start}}<br />
{{Related|Arch Linux}}<br />
{{Related|Arch-based distributions}}<br />
{{Related|Pacman/Rosetta}}<br />
{{Related|Arch is the best}}<br />
{{Related articles end}}<br />
<br />
This page attempts to draw a comparison between Arch Linux and other popular GNU/Linux distributions and UNIX-like operating systems. The summaries that follow are brief descriptions that may help a person decide if Arch Linux will suit their needs. Although reviews and descriptions can be useful, first-hand experience is invariably the best way to compare distributions.<br />
<br />
For a more complete comparison, see [[Wikipedia:Comparison of operating systems]] and [[Wikipedia:Comparison of Linux distributions]].<br />
<br />
In all of the following, only Arch Linux is compared with other distributions. Community ports that support architectures other than x86_64 can be found listed among the [[Arch-based distributions]].<br />
<br />
== Source-based ==<br />
<br />
Source-based distributions are highly portable, giving the advantage of controlling and compiling the entire OS and applications for a particular machine architecture and usage scheme, with the disadvantage of the time-consuming nature of source compilation. The Arch base and all packages are only compiled for the x86_64 architecture.<br />
<br />
=== CRUX ===<br />
<br />
* [https://crux.nu/ CRUX] is a lightweight distribution that focuses on the [[Arch terminology#KISS|KISS]] principle. CRUX inspired Judd Vinet to create Arch.<br />
* CRUX uses BSD-style init scripts, whereas Arch uses [[systemd]].<br />
* While Arch uses a rolling release system, CRUX has more or less yearly releases.<br />
* Both ship with ports-like systems, and, like *BSD, both provide a base environment to build upon.<br />
* Arch features [[pacman]], which handles binary system package management and works seamlessly with the [[Arch Build System]]. CRUX uses a community contributed system called ''prt-get'', which, in combination with its own ports system, handles dependency resolution, but builds all packages from source (though the CRUX base installation is binary).<br />
* Both Arch and CRUX officially support only the x86_64 architecture.<br />
* Arch features a large array of binary package repositories as well as the [[Arch User Repository]]. CRUX provides a more slimmed-down officially supported ports system in addition to a comparatively modest community repository.<br />
<br />
=== LFS ===<br />
<br />
* [https://www.linuxfromscratch.org/lfs/ LFS], (or Linux From Scratch) exists simply as documentation. The book instructs the user on obtaining the source code for a minimal base package set for a functional GNU/Linux system, and how to manually compile, patch and configure it from scratch. LFS is as minimal as it gets, and offers an excellent and educational process of building and customizing a base system.<br />
* LFS provides no online repositories; sources are manually obtained, compiled and installed with ''make''. (Several manual methods of package management exist, and are mentioned in LFS Hints).<br />
* Arch provides these very same packages, plus [[systemd]], a few extra tools and the powerful [[pacman]] package manager as its base system, already compiled for x86_64. Along with the minimal Arch base system, the Arch community and developers provide and maintain many thousands of binary packages installable via pacman as well as [[PKGBUILD]] build scripts for use with the [[Arch Build System]]. Arch also includes the [[makepkg]] tool for expediently building or customizing packages, readily installable by pacman.<br />
* Judd Vinet built Arch from scratch, and then wrote pacman in C. Historically, Arch was sometimes humorously described simply as "Linux, with a nice package manager."<br />
<br />
=== Gentoo/Funtoo Linux ===<br />
<br />
* Both Arch Linux and [https://gentoo.org/ Gentoo Linux] are rolling release systems, making packages available to the distribution a short time after they are released upstream.<br />
* The Gentoo packages and base system are built directly from source code according to user-specified ''USE flags''. Arch provides a ports-like system for building packages from source, though the Arch base system is designed to be installed as pre-built x86_64 binary. This generally makes Arch quicker to build and update, and allows Gentoo to be more systemically customizable.<br />
* Arch only supports x86_64 while Gentoo officially supports x86 (i486/i686), x86_64, PPC/PPC64, SPARC, Alpha, ARM, MIPS, HPPA, S/390 and Itanium architectures.<br />
* Gentoo's official package and system management tools tend to be rather more complex and "powerful" than those provided by Arch, and certain features which are at the very heart of Gentoo ([[Gentoo:Handbook:X86/Working/USE|USE flags]], [[Gentoo:Handbook:X86/Working/Portage#Terminology|SLOTs]], etc.) do not have any direct Arch Linux equivalent. Some of that is due to the fact that Arch is primarily a binary distribution, but differences in [[Arch Linux#Principles|design philosophy]] also play a big role, with Arch taking a more principled stance in favor of architectural simplicity and avoiding over-engineering.<br />
* Because both the Gentoo and Arch installations only include a base system, both are considered to be highly customizable. If comfortable with [[systemd]], Gentoo users will also generally feel at ease with most other aspects of Arch.<br />
<br />
=== GNU Guix System ===<br />
<br />
* [https://guix.gnu.org/ GNU Guix System] has been inspired by [https://nixos.org/ NixOS] in a way similar to how Arch has been inspired by [https://crux.nu/ CRUX].<br />
* Both Arch Linux and Guix System are rolling release distributions, making packages available to the distribution a short time after they are released upstream. Guix System is however primarily a source-based distribution (although pre-built binaries exist and are called "[https://guix.gnu.org/en/manual/en/guix.html#Substitutes substitutes]"), while Arch is primarily a binary distribution.<br />
* Arch uses [[pacman]] as package manager, whereas Guix System uses [[guix]], which supports [https://guix.gnu.org/manual/en/html_node/Features.html experimental packaging features] not present in other distributions.<br />
* Arch only supports x86_64, while Guix System officially supports [https://guix.gnu.org/manual/en/html_node/GNU-Distribution.html several architectures].<br />
* Arch uses [[systemd]] as [[init]] system, whereas Guix System uses the [https://www.gnu.org/software/shepherd/ GNU Shepherd].<br />
* Guix System breaks up with many traditional concepts of Unix, including the [[Arch filesystem hierarchy|Filesystem Hierarchy Standard]]. For instance, many files that in traditional distributions are spread across different directories, in Guix System will be located somewhere under {{ic|/gnu/store/}}.<br />
* Arch might occasionally ship software that is non-free (often drivers), while Guix System ships only free software and is endorsed by the [[Free Software Foundation]] – although alternative repositories that ship non-free software for Guix [https://gitlab.com/nonguix/nonguix exist].<br />
* Arch expects the user directly to configure installed software packages, while Guix System encourages a global system configuration in Scheme, which in turn [https://guix.gnu.org/manual/en/html_node/Invoking-guix-system.html instantiates] configuration files.<br />
<br />
== General ==<br />
<br />
These distributions offer a broad range of advantages and strengths, and can be made to serve most operating system uses.<br />
<br />
=== Debian ===<br />
<br />
* [https://www.debian.org/ Debian] is the largest upstream Linux distribution with a bigger community and features stable, testing, and unstable branches, offering over 148,000 [https://packages.debian.org/unstable/ packages]. The available number of Arch binary packages is more modest. However, when including the [[AUR]], the quantities are comparable.<br />
* Debian has a more vehement stance on free software but still includes non-free software in its non-free repositories. Arch is more lenient, and therefore inclusive, concerning ''non-free packages'' as defined by GNU.<br />
* Debian focuses on stringent testing of the Stable branch, which is "frozen" and supported up to [[debian:LTS|five years]]. Arch packages are more current than Debian Stable, being more comparable to the Debian Testing and Unstable branches, and has no fixed release schedule.<br />
* Debian is available for many architectures, including alpha, arm, hppa, i386, x86_64, ia64, m68k, mips, mipsel, powerpc, s390, and sparc, whereas Arch is x86_64 only.<br />
* Arch provides more expedient support for building custom, installable packages from outside sources, with a ports-like package build system. Debian does not offer a ports system, relying instead on its large binary repositories.<br />
* The Arch installation system only offers a minimal base, transparently exposed during system configuration, whereas Debian's methods, such as the use of apt ''tasks'' to install pre-selected groups of packages, offer a more automatically configured approach as well as several alternative methods of installation.<br />
* Arch generally packages software libraries together with their header files, whereas in Debian header files have to be downloaded separately.<br />
* Arch keeps patching to a minimum, thus avoiding problems that upstream are unable to review, whereas Debian patches its packages more liberally for a wider audience.<br />
<br />
=== Fedora ===<br />
<br />
* [https://getfedora.org/ Fedora Linux] is the upstream, community distribution of Red Hat® Enterprise Linux. Red Hat is the project’s primary sponsor, but thousands of independent developers also contribute to Fedora. Packages and projects are released on Fedora, and through its own distinct set of tests and quality assurance processes, those features migrate to CentOS Stream and eventually get incorporated into a version of Red Hat Enterprise Linux, and some eventually become adopted by other distributions. Arch has no fixed releases and does not serve as a branch for another distribution, even if [[Arch-based distributions|many other distributions]] are based on Arch Linux (e.g. SteamOS for the [[Steam Deck]]).<br />
* Fedora packages use the RPM format with the [https://docs.fedoraproject.org/en-US/fedora/latest/system-administrators-guide/package-management/DNF/ DNF] package manager. Arch uses [[pacman]] to manage its packages. Many packages of both projects, particularly desktop environments, are described as being 'vanilla', and without customization. <br />
* Fedora refuses to include non-free software in official repositories due to its dedication to free software, though third-party repositories are available for such packages. Arch is more lenient in its disposition toward non-free software, leaving the discernment to the user.<br />
* Fedora uses the graphical Anaconda installer and offers many installation images including an "everything" expert option which facilitates a base system install all the way up to a full-fledged desktop environment of your choosing. Fedora "spins" also provide alternative assortments of specific desktop environments, each with a modest assortment of default packages. Arch, on the other hand, is designed to be assembled from a minimal base system command line and therefore provides simple scripts meant to ease the process.<br />
* Fedora has a scheduled ~6 month release cycle, but officially supports discrete version upgrades with the DNF system-upgrade plugin. Arch is a rolling-release system.<br />
* Arch features a ports system, whereas Fedora does not.<br />
* Both Arch and Fedora are targeted at experienced users and developers. Both strongly encourage their users to contribute to project development.<br />
* Fedora has earned much community recognition for integration of SELinux, GCJ compiled packages (to remove the need for Oracle's JRE), and prolific upstream contribution; Red Hat and thus, Fedora developers by extension, contribute the highest percentage of Linux kernel code as compared to any other project.<br />
* Arch Linux provides what is widely regarded as the most thorough and comprehensive distribution wiki. The Fedora wiki is used in the original sense of the word "wiki", or a way to exchange information between developers, testers and users rapidly. It is not meant to be an end-user knowledge base like Arch's. Fedora's wiki resembles an issue tracker or a corporate wiki.<br />
<br />
=== Slackware ===<br />
<br />
* [http://www.slackware.com/ Slackware] uses BSD-style init scripts, whereas Arch uses [[systemd]].<br />
* Arch supplies a package management system in [[pacman]] which, unlike Slackware's standard tools, offers automatic dependency resolution and allows for more automated system upgrades. Slackware users typically prefer their method of manual dependency resolution, citing the level of system control it grants them, as well as Slackware's excellent supply of pre-installed libraries and dependencies.<br />
* Arch is a rolling-release system. Slackware is seen as more conservative in its release cycle, preferring proven stable packages. Arch is more ''bleeding-edge'' in this respect.<br />
* Arch Linux provides many thousands of binary packages within its official repositories, whereas Slackware official repositories are more modest.<br />
* Arch offers the [[Arch Build System]], an actual ports-like system, and also the [[AUR]], a very large collection of PKGBUILDs contributed by users. Slackware offers a similar, though slimmer system at [https://www.slackbuilds.org slackbuilds.org] which is a semi-official repository of Slackbuilds, which are analogous to Arch PKGBUILDs. Slackware users will generally be quite comfortable with most aspects of Arch.<br />
<br />
== Beginner-friendly ==<br />
<br />
Sometimes called "newbie distros", the beginner-friendly distributions share a lot of similarities, though Arch is quite different from them. Arch may be a better choice if you want to learn about GNU/Linux by building up from a small base, as an installation of Arch installs few packages in comparison. Specific differences between distributions are described below.<br />
<br />
=== Ubuntu ===<br />
<br />
* [https://www.ubuntu.com/ Ubuntu] is a popular Debian-based distribution commercially sponsored by Canonical Ltd., while Arch is an independently developed system built from scratch.<br />
* The two projects have very different goals and are targeted at a different user base. Arch is designed for users who desire a do-it-yourself approach, whereas Ubuntu provides a pre-configured system. Arch presents a simpler design from the base installation onward, relying on the user to customize it to their own specific needs. Many Arch users have started on Ubuntu and eventually migrated to Arch.<br />
* Arch development is not biased towards any one particular user interface beyond what its community provides support for. Furthermore, Canonical's commercial nature has led them to some controversial decisions, such as the inclusion of advertisements in Unity's ''Dash'' menu and user data collection. Arch is an independent, community-driven project with no commercial agenda.<br />
* Ubuntu moves between discrete releases every 6 months, whereas Arch is a rolling-release system.<br />
* Arch offers a ports-like package build system and the [[Arch User Repository]], where users can share source packages for the [[pacman]] package manager. Ubuntu uses the more complex [[Wikipedia:Advanced Packaging Tool|apt]], and allows redistribution of binary packages via [https://launchpad.net/ubuntu/+ppas Personal Package Archives].<br />
* The two communities differ in some ways as well. The Arch community is much smaller and is strongly encouraged to contribute to the distribution. In contrast, the Ubuntu community is relatively large and can therefore tolerate a much larger percentage of users who do not actively contribute to development, packaging, or repository maintenance.<br />
<br />
=== Linux Mint ===<br />
<br />
* [https://www.linuxmint.com/ Linux Mint] was born as an [[#Ubuntu|Ubuntu]] derivative, and later added the LMDE (Linux Mint Debian Edition) that is instead based on [[#Debian|Debian]]. On the other hand, Arch is an independent distribution that relies on its own [[ABS|build system]] and [[Official repositories|repositories]].<br />
* Mint includes several graphical tools for easier maintenance, called ''MintTools''. Arch only provides simple command-line tools like [[pacman]] and leaves system management to be organized by the user.<br />
* New versions of Mint are released every six months, about a month after Ubuntu. Each release is based on the most recent Ubuntu LTS and is supported for five years. Linux Mint Debian Edition (LMDE) is based on Debian Stable and only receives updates in Mint packages and security updates. Arch is instead a full rolling-release distribution.<br />
<br />
=== openSUSE ===<br />
<br />
[https://www.opensuse.org/ openSUSE] was born from the original SUSE Linux and is sponsored by SUSE (the makers of SUSE Enterprise Linux). SUSE Enterprise Linux Desktop (SLED) is based on openSUSE Tumbleweed and shares a common codebase with openSUSE Leap<br />
<br />
*OpenSUSE Uses the Zypp package manager (''zypper'' on commandline), the RPM package format and its well-regarded YaST2 GUI-driven configuration tool. Arch uses [[pacman]] to manage tar.zstd packages and does not offer graphical configuration tools. <br />
* openSUSE offers 2 different versions:<br />
**Leap is the long-term support version of openSUSE featuring discrete releases.<br />
**Tumbleweed is the rolling release version of openSUSE.<br />
*In contrast, Arch is strictly a rolling-release model and does not offer discrete release versions. Rather than a complete desktop environment, Arch offers a minimal base system installation. openSUSE may therefore be more appropriate for users who want a more GUI-driven environment, automatic configuration, or expected functionality out of the box while still allowing the customization possible on all distributions.<br />
<br />
=== Mandriva/Mageia ===<br />
<br />
Mandriva Linux (formerly Mandrake Linux) was created in 1998 with the goal of making GNU/Linux easy to use for everyone; it is RPM-based and uses the ''urpmi'' package manager. Mageia is a Mandriva fork created by former Mandriva employees which opposes its parent distribution's commercial position, being a non-profit and community-driven project. Arch takes a simpler approach than Mandriva or Mageia, being text-based and relying on more manual configuration, and is aimed at intermediate to advanced users.<br />
<br />
== The BSDs ==<br />
<br />
* The BSDs share a common origin and descend directly from the work done at UC Berkeley to produce a freely redistributable, free of cost, UNIX system. They are not GNU/Linux distributions, but rather, UNIX-like operating systems, and derived from the original AT&T UNIX code.<br />
* Arch and the BSDs share the concept of a tightly-integrated base and ports system. However, unlike GNU/Linux distributions such as Arch, the BSDs' kernel and userland programs (such as the shell and core utilities like ''ls'', ''cp'', ''cat'', and ''ps'') are developed together in a single source repository.<br />
* The [[Wikipedia:BSD licenses|BSD license]] is permissive, in contrast to the [[Wikipedia:GNU General Public License|GPL]], which has the stipulation that derivatives need to be released under the same license. Arch is released under the GPL.<br />
* To learn more about the BSD variants, see [[Wikipedia:Comparison of BSD operating systems]].<br />
<br />
== See also ==<br />
<br />
* [https://distrowatch.com/ DistroWatch] - Linux distributions news and reviews</div>Malcontenthttps://wiki.archlinux.org/index.php?title=Talk:Bash&diff=780565Talk:Bash2023-06-07T13:28:57Z<p>Malcontent: behavior</p>
<hr />
<div>== Return in non interactive mode ==<br />
<br />
''[Moved from [[Talk:Color Bash Prompt#Return in non interactive mode]] -- [[User:Kynikos|Kynikos]] ([[User talk:Kynikos|talk]]) 03:18, 26 April 2014 (UTC)]''<br />
<br />
{{bc|<nowiki><br />
# This file is sourced by all *interactive* bash shells on startup,<br />
# including some apparently interactive shells such as scp and rcp<br />
# that can't tolerate any output. So make sure this doesn't display<br />
# anything or bad things will happen !<br />
<br />
# Test for an interactive shell. There is no need to set anything<br />
# past this point for scp and rcp, and it's important to refrain from<br />
# outputting anything in those cases.<br />
<br />
# If not running interactively, don't do anything!<br />
[[ $- != *i* ]] && return<br />
</nowiki>}}<br />
Some Linux distributions like Arch Linux actually distribute a bashrc with a statement like {{ic|<nowiki>[[ $- != *i* ]] && return</nowiki>}} included (see above). The comments say the bashrc script has to exit (return) because tools like scp are running in interactive mode and don't support having some user customizations, this is the reason why we have to return. But the return code actually returns if the script isn't run in interactive mode ({{ic|1=!= *i*}}), which is the contrary of what we want to achieve. Can anyone explain me that? Either the comments are incorrect or it is unneeded to use that return statement. But on IRC, some people agreed with me regarding this problem. And on the {{ic|#bash}} channel, some said the statement is unneeded because all scripts (which are all running in non-interactive mode) do not source ANY configuration files like {{ic|/etc/profile}} and {{ic|bashrc}} file. [[User:Wget|Wget]] ([[User talk:Wget|talk]]) 20:18, 25 August 2013 (UTC)<br />
<br />
:Doesn't really belong here. --'''<span style="text-shadow:grey 0.1em 0.1em 0.1em; font-size:110%">[[User:Det|<span style="color:gold">D</span><span style="color:orange">e</span><span style="color:red">t</span>]][[User talk:Det|<sup><font color="white">talk</font></sup>]]</span>''' 11:37, 25 April 2014 (UTC)<br />
<br />
::Certainly, but as the question is not really answered, I'd suggest to move this discussion into [[Talk:Bash]]. The snippet is probably from some content recently removed from this page, but this should not matter. -- [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 21:17, 25 April 2014 (UTC)<br />
<br />
:::Agreed, moved here as suggested. -- [[User:Kynikos|Kynikos]] ([[User talk:Kynikos|talk]]) 03:18, 26 April 2014 (UTC)<br />
<br />
::::From [http://mywiki.wooledge.org/DotFiles]:<br />
:::::Bash has a special compile time option that will cause it to source the .bashrc file on non-login, non-interactive ssh sessions. This feature is only enabled by certain OS vendors (mostly Linux distributions). It is not enabled in a default upstream Bash build, and (empirically) not on OpenBSD either.<br />
:::::[...] Note that a test on SHLVL is also done, so if you do: ssh remotehost bash -c echo then the first bash will source .bashrc but not the second one (the explicit bash on the command line that runs echo).<br />
:::::'''The behavior of the bash patched to source a system level bashrc by some vendors is left as an exercise.'''<br />
::::(Emphasis mine; Arch sources a system-level bashrc).<br />
::::From [http://www.gnu.org/software/bash/manual/bash.html#Bash-Startup-Files]:<br />
:::::When Bash is started non-interactively, to run a shell script, for example, it looks for the variable BASH_ENV in the environment, expands its value if it appears there, and uses the expanded value as the name of a file to read and execute. [...] but the value of the PATH variable is not used to search for the filename.<br />
:::::As noted above, if a non-interactive shell is invoked with the --login option, Bash attempts to read and execute commands from the login shell startup files.<br />
::::The above comment on scp was removed from {{ic|.bashrc}} files in Arch Linux. Either way, it is clear that non-interactive shells '''do''' source configuration files under some circumstances. Questions:<br />
::::# What is the "special compile time option" for ssh sessions?<br />
::::# If files specified in {{ic|BASH_ENV}} do not use {{ic|PATH}}, what is then used? A default? The current directory?<br />
::::# Does a non-interactive login shell '''also''' source files in {{ic|BASH_ENV}} besides {{ic|.profile}} & co. ?<br />
::::-- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 14:21, 16 August 2015 (UTC)<br />
<br />
==Chart: Login shells - /etc/bash.bashrc==<br />
<br />
The [https://wiki.archlinux.org/index.php/bash#Configuration_files Configuration files chart] lists that {{ic|/etc/bash.bashrc}} is not used for a login shell, but is used for an interactive non-login shell. If I'm understanding correctly, I think this is accurate for upstream bash. But, as the chart says under {{ic|/etc/profile}}, Arch has this source {{ic|/etc/bash.bashrc}}. As this page is about how bash functions under Arch, not upstream, doesn't this mean that {{ic|/etc/bash.bashrc}} should be listed as "Yes" for both login shells, and interactive non-login shells? If someone's focused at the green/red Yes/No's, this chart makes it look like {{ic|/etc/bash.bashrc}} won't be sourced by a login shell. I'd say just change it to "Yes", but it could be changed to "Yes (see note)" and another note could be added that although upstream bash doesn't source {{ic|/etc/bash.bashrc}}, Arch's default {{ic|/etc/profile}} does.<br />
<br />
[[User:Jamespharvey20|Jamespharvey20]] ([[User talk:Jamespharvey20|talk]]) 09:31, 12 October 2018 (UTC)<br />
<br />
:There is a difference between "sourced by a shell" and "sourced by a shell script". Documenting the latter does not make sense because you can add custom source commands to force sourcing all listed config files in all types of shells as well as remove the command sourcing {{ic|/etc/bash.bashrc}} from {{ic|/etc/profile}}. -- [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 13:47, 12 October 2018 (UTC)</div>Malcontenthttps://wiki.archlinux.org/index.php?title=Talk:Bash&diff=780564Talk:Bash2023-06-07T13:28:16Z<p>Malcontent: Arch Linux</p>
<hr />
<div>== Return in non interactive mode ==<br />
<br />
''[Moved from [[Talk:Color Bash Prompt#Return in non interactive mode]] -- [[User:Kynikos|Kynikos]] ([[User talk:Kynikos|talk]]) 03:18, 26 April 2014 (UTC)]''<br />
<br />
{{bc|<nowiki><br />
# This file is sourced by all *interactive* bash shells on startup,<br />
# including some apparently interactive shells such as scp and rcp<br />
# that can't tolerate any output. So make sure this doesn't display<br />
# anything or bad things will happen !<br />
<br />
# Test for an interactive shell. There is no need to set anything<br />
# past this point for scp and rcp, and it's important to refrain from<br />
# outputting anything in those cases.<br />
<br />
# If not running interactively, don't do anything!<br />
[[ $- != *i* ]] && return<br />
</nowiki>}}<br />
Some Linux distributions like Arch Linux actually distribute a bashrc with a statement like {{ic|<nowiki>[[ $- != *i* ]] && return</nowiki>}} included (see above). The comments say the bashrc script has to exit (return) because tools like scp are running in interactive mode and don't support having some user customizations, this is the reason why we have to return. But the return code actually returns if the script isn't run in interactive mode ({{ic|1=!= *i*}}), which is the contrary of what we want to achieve. Can anyone explain me that? Either the comments are incorrect or it is unneeded to use that return statement. But on IRC, some people agreed with me regarding this problem. And on the {{ic|#bash}} channel, some said the statement is unneeded because all scripts (which are all running in non-interactive mode) do not source ANY configuration files like {{ic|/etc/profile}} and {{ic|bashrc}} file. [[User:Wget|Wget]] ([[User talk:Wget|talk]]) 20:18, 25 August 2013 (UTC)<br />
<br />
:Doesn't really belong here. --'''<span style="text-shadow:grey 0.1em 0.1em 0.1em; font-size:110%">[[User:Det|<span style="color:gold">D</span><span style="color:orange">e</span><span style="color:red">t</span>]][[User talk:Det|<sup><font color="white">talk</font></sup>]]</span>''' 11:37, 25 April 2014 (UTC)<br />
<br />
::Certainly, but as the question is not really answered, I'd suggest to move this discussion into [[Talk:Bash]]. The snippet is probably from some content recently removed from this page, but this should not matter. -- [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 21:17, 25 April 2014 (UTC)<br />
<br />
:::Agreed, moved here as suggested. -- [[User:Kynikos|Kynikos]] ([[User talk:Kynikos|talk]]) 03:18, 26 April 2014 (UTC)<br />
<br />
::::From [http://mywiki.wooledge.org/DotFiles]:<br />
:::::Bash has a special compile time option that will cause it to source the .bashrc file on non-login, non-interactive ssh sessions. This feature is only enabled by certain OS vendors (mostly Linux distributions). It is not enabled in a default upstream Bash build, and (empirically) not on OpenBSD either.<br />
:::::[...] Note that a test on SHLVL is also done, so if you do: ssh remotehost bash -c echo then the first bash will source .bashrc but not the second one (the explicit bash on the command line that runs echo).<br />
:::::'''The behaviour of the bash patched to source a system level bashrc by some vendors is left as an exercise.'''<br />
::::(Emphasis mine; Arch sources a system-level bashrc).<br />
::::From [http://www.gnu.org/software/bash/manual/bash.html#Bash-Startup-Files]:<br />
:::::When Bash is started non-interactively, to run a shell script, for example, it looks for the variable BASH_ENV in the environment, expands its value if it appears there, and uses the expanded value as the name of a file to read and execute. [...] but the value of the PATH variable is not used to search for the filename.<br />
:::::As noted above, if a non-interactive shell is invoked with the --login option, Bash attempts to read and execute commands from the login shell startup files.<br />
::::The above comment on scp was removed from {{ic|.bashrc}} files in Arch Linux. Either way, it is clear that non-interactive shells '''do''' source configuration files under some circumstances. Questions:<br />
::::# What is the "special compile time option" for ssh sessions?<br />
::::# If files specified in {{ic|BASH_ENV}} do not use {{ic|PATH}}, what is then used? A default? The current directory?<br />
::::# Does a non-interactive login shell '''also''' source files in {{ic|BASH_ENV}} besides {{ic|.profile}} & co. ?<br />
::::-- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 14:21, 16 August 2015 (UTC)<br />
<br />
==Chart: Login shells - /etc/bash.bashrc==<br />
<br />
The [https://wiki.archlinux.org/index.php/bash#Configuration_files Configuration files chart] lists that {{ic|/etc/bash.bashrc}} is not used for a login shell, but is used for an interactive non-login shell. If I'm understanding correctly, I think this is accurate for upstream bash. But, as the chart says under {{ic|/etc/profile}}, Arch has this source {{ic|/etc/bash.bashrc}}. As this page is about how bash functions under Arch, not upstream, doesn't this mean that {{ic|/etc/bash.bashrc}} should be listed as "Yes" for both login shells, and interactive non-login shells? If someone's focused at the green/red Yes/No's, this chart makes it look like {{ic|/etc/bash.bashrc}} won't be sourced by a login shell. I'd say just change it to "Yes", but it could be changed to "Yes (see note)" and another note could be added that although upstream bash doesn't source {{ic|/etc/bash.bashrc}}, Arch's default {{ic|/etc/profile}} does.<br />
<br />
[[User:Jamespharvey20|Jamespharvey20]] ([[User talk:Jamespharvey20|talk]]) 09:31, 12 October 2018 (UTC)<br />
<br />
:There is a difference between "sourced by a shell" and "sourced by a shell script". Documenting the latter does not make sense because you can add custom source commands to force sourcing all listed config files in all types of shells as well as remove the command sourcing {{ic|/etc/bash.bashrc}} from {{ic|/etc/profile}}. -- [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 13:47, 12 October 2018 (UTC)</div>Malcontenthttps://wiki.archlinux.org/index.php?title=Talk:Bash&diff=776392Talk:Bash2023-04-26T01:14:48Z<p>Malcontent: Arch Linux</p>
<hr />
<div>== Return in non interactive mode ==<br />
<br />
''[Moved from [[Talk:Color Bash Prompt#Return in non interactive mode]] -- [[User:Kynikos|Kynikos]] ([[User talk:Kynikos|talk]]) 03:18, 26 April 2014 (UTC)]''<br />
<br />
{{bc|<nowiki><br />
# This file is sourced by all *interactive* bash shells on startup,<br />
# including some apparently interactive shells such as scp and rcp<br />
# that can't tolerate any output. So make sure this doesn't display<br />
# anything or bad things will happen!<br />
<br />
# Test for an interactive shell. There is no need to set anything<br />
# past this point for scp and rcp, and it's important to refrain from<br />
# outputting anything in those cases.<br />
<br />
# If not running interactively, don't do anything!<br />
[[ $- != *i* ]] && return<br />
</nowiki>}}<br />
Some Linux distributions like Arch Linux actually distribute a bashrc with a statement like {{ic|<nowiki>[[ $- != *i* ]] && return</nowiki>}} included (see above). The comments say the bashrc script has to exit (return) because tools like scp are running in interactive mode and don't support having some user customizations, this is the reason why we have to return. But the return code actually returns if the script isn't run in interactive mode ({{ic|1=!= *i*}}), which is the contrary of what we want to achieve. Can anyone explain me that? Either the comments are incorrect or it is unneeded to use that return statement. But on IRC, some people agreed with me regarding this problem. And on the {{ic|#bash}} channel, some said the statement is unneeded because all scripts (which are all running in non-interactive mode) do not source ANY configuration files like {{ic|/etc/profile}} and {{ic|bashrc}} file. [[User:Wget|Wget]] ([[User talk:Wget|talk]]) 20:18, 25 August 2013 (UTC)<br />
<br />
:Doesn't really belong here. --'''<span style="text-shadow:grey 0.1em 0.1em 0.1em; font-size:110%">[[User:Det|<span style="color:gold">D</span><span style="color:orange">e</span><span style="color:red">t</span>]][[User talk:Det|<sup><font color="white">talk</font></sup>]]</span>''' 11:37, 25 April 2014 (UTC)<br />
<br />
::Certainly, but as the question is not really answered, I'd suggest to move this discussion into [[Talk:Bash]]. The snippet is probably from some content recently removed from this page, but this should not matter. -- [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 21:17, 25 April 2014 (UTC)<br />
<br />
:::Agreed, moved here as suggested. -- [[User:Kynikos|Kynikos]] ([[User talk:Kynikos|talk]]) 03:18, 26 April 2014 (UTC)<br />
<br />
::::From [http://mywiki.wooledge.org/DotFiles]:<br />
:::::Bash has a special compile time option that will cause it to source the .bashrc file on non-login, non-interactive ssh sessions. This feature is only enabled by certain OS vendors (mostly Linux distributions). It is not enabled in a default upstream Bash build, and (empirically) not on OpenBSD either.<br />
:::::[...] Note that a test on SHLVL is also done, so if you do: ssh remotehost bash -c echo then the first bash will source .bashrc but not the second one (the explicit bash on the command line that runs echo).<br />
:::::'''The behaviour of the bash patched to source a system level bashrc by some vendors is left as an exercise.'''<br />
::::(Emphasis mine; Arch sources a system-level bashrc).<br />
::::From [http://www.gnu.org/software/bash/manual/bash.html#Bash-Startup-Files]:<br />
:::::When Bash is started non-interactively, to run a shell script, for example, it looks for the variable BASH_ENV in the environment, expands its value if it appears there, and uses the expanded value as the name of a file to read and execute. [...] but the value of the PATH variable is not used to search for the filename.<br />
:::::As noted above, if a non-interactive shell is invoked with the --login option, Bash attempts to read and execute commands from the login shell startup files.<br />
::::The above comment on scp was removed from {{ic|.bashrc}} files in Arch Linux. Either way, it is clear that non-interactive shells '''do''' source configuration files under some circumstances. Questions:<br />
::::# What is the "special compile time option" for ssh sessions?<br />
::::# If files specified in {{ic|BASH_ENV}} do not use {{ic|PATH}}, what is then used? A default? The current directory?<br />
::::# Does a non-interactive login shell '''also''' source files in {{ic|BASH_ENV}} besides {{ic|.profile}} & co. ?<br />
::::-- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 14:21, 16 August 2015 (UTC)<br />
<br />
==Chart: Login shells - /etc/bash.bashrc==<br />
<br />
The [https://wiki.archlinux.org/index.php/bash#Configuration_files Configuration files chart] lists that {{ic|/etc/bash.bashrc}} is not used for a login shell, but is used for an interactive non-login shell. If I'm understanding correctly, I think this is accurate for upstream bash. But, as the chart says under {{ic|/etc/profile}}, Arch has this source {{ic|/etc/bash.bashrc}}. As this page is about how bash functions under Arch, not upstream, doesn't this mean that {{ic|/etc/bash.bashrc}} should be listed as "Yes" for both login shells, and interactive non-login shells? If someone's focused at the green/red Yes/No's, this chart makes it look like {{ic|/etc/bash.bashrc}} won't be sourced by a login shell. I'd say just change it to "Yes", but it could be changed to "Yes (see note)" and another note could be added that although upstream bash doesn't source {{ic|/etc/bash.bashrc}}, Arch's default {{ic|/etc/profile}} does.<br />
<br />
[[User:Jamespharvey20|Jamespharvey20]] ([[User talk:Jamespharvey20|talk]]) 09:31, 12 October 2018 (UTC)<br />
<br />
:There is a difference between "sourced by a shell" and "sourced by a shell script". Documenting the latter does not make sense because you can add custom source commands to force sourcing all listed config files in all types of shells as well as remove the command sourcing {{ic|/etc/bash.bashrc}} from {{ic|/etc/profile}}. -- [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 13:47, 12 October 2018 (UTC)</div>Malcontenthttps://wiki.archlinux.org/index.php?title=Talk:Bash&diff=776391Talk:Bash2023-04-26T01:13:27Z<p>Malcontent: fix whitespace</p>
<hr />
<div>== Return in non interactive mode ==<br />
<br />
''[Moved from [[Talk:Color Bash Prompt#Return in non interactive mode]] -- [[User:Kynikos|Kynikos]] ([[User talk:Kynikos|talk]]) 03:18, 26 April 2014 (UTC)]''<br />
<br />
{{bc|<nowiki><br />
# This file is sourced by all *interactive* bash shells on startup,<br />
# including some apparently interactive shells such as scp and rcp<br />
# that can't tolerate any output. So make sure this doesn't display<br />
# anything or bad things will happen!<br />
<br />
# Test for an interactive shell. There is no need to set anything<br />
# past this point for scp and rcp, and it's important to refrain from<br />
# outputting anything in those cases.<br />
<br />
# If not running interactively, don't do anything!<br />
[[ $- != *i* ]] && return<br />
</nowiki>}}<br />
Some Linux distributions like ArchLinux actually distribute a bashrc with a statement like {{ic|<nowiki>[[ $- != *i* ]] && return</nowiki>}} included (see above). The comments say the bashrc script has to exit (return) because tools like scp are running in interactive mode and don't support having some user customizations, this is the reason why we have to return. But the return code actually returns if the script isn't run in interactive mode ({{ic|1=!= *i*}}), which is the contrary of what we want to achieve. Can anyone explain me that? Either the comments are incorrect or it is unneeded to use that return statement. But on IRC, some people agreed with me regarding this problem. And on the {{ic|#bash}} channel, some said the statement is unneeded because all scripts (which are all running in non-interactive mode) do not source ANY configuration files like {{ic|/etc/profile}} and {{ic|bashrc}} file. [[User:Wget|Wget]] ([[User talk:Wget|talk]]) 20:18, 25 August 2013 (UTC)<br />
<br />
:Doesn't really belong here. --'''<span style="text-shadow:grey 0.1em 0.1em 0.1em; font-size:110%">[[User:Det|<span style="color:gold">D</span><span style="color:orange">e</span><span style="color:red">t</span>]][[User talk:Det|<sup><font color="white">talk</font></sup>]]</span>''' 11:37, 25 April 2014 (UTC)<br />
<br />
::Certainly, but as the question is not really answered, I'd suggest to move this discussion into [[Talk:Bash]]. The snippet is probably from some content recently removed from this page, but this should not matter. -- [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 21:17, 25 April 2014 (UTC)<br />
<br />
:::Agreed, moved here as suggested. -- [[User:Kynikos|Kynikos]] ([[User talk:Kynikos|talk]]) 03:18, 26 April 2014 (UTC)<br />
<br />
::::From [http://mywiki.wooledge.org/DotFiles]:<br />
:::::Bash has a special compile time option that will cause it to source the .bashrc file on non-login, non-interactive ssh sessions. This feature is only enabled by certain OS vendors (mostly Linux distributions). It is not enabled in a default upstream Bash build, and (empirically) not on OpenBSD either.<br />
:::::[...] Note that a test on SHLVL is also done, so if you do: ssh remotehost bash -c echo then the first bash will source .bashrc but not the second one (the explicit bash on the command line that runs echo).<br />
:::::'''The behaviour of the bash patched to source a system level bashrc by some vendors is left as an exercise.'''<br />
::::(Emphasis mine; Arch sources a system-level bashrc).<br />
::::From [http://www.gnu.org/software/bash/manual/bash.html#Bash-Startup-Files]:<br />
:::::When Bash is started non-interactively, to run a shell script, for example, it looks for the variable BASH_ENV in the environment, expands its value if it appears there, and uses the expanded value as the name of a file to read and execute. [...] but the value of the PATH variable is not used to search for the filename.<br />
:::::As noted above, if a non-interactive shell is invoked with the --login option, Bash attempts to read and execute commands from the login shell startup files.<br />
::::The above comment on scp was removed from {{ic|.bashrc}} files in Arch Linux. Either way, it is clear that non-interactive shells '''do''' source configuration files under some circumstances. Questions:<br />
::::# What is the "special compile time option" for ssh sessions?<br />
::::# If files specified in {{ic|BASH_ENV}} do not use {{ic|PATH}}, what is then used? A default? The current directory?<br />
::::# Does a non-interactive login shell '''also''' source files in {{ic|BASH_ENV}} besides {{ic|.profile}} & co. ?<br />
::::-- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 14:21, 16 August 2015 (UTC)<br />
<br />
==Chart: Login shells - /etc/bash.bashrc==<br />
<br />
The [https://wiki.archlinux.org/index.php/bash#Configuration_files Configuration files chart] lists that {{ic|/etc/bash.bashrc}} is not used for a login shell, but is used for an interactive non-login shell. If I'm understanding correctly, I think this is accurate for upstream bash. But, as the chart says under {{ic|/etc/profile}}, Arch has this source {{ic|/etc/bash.bashrc}}. As this page is about how bash functions under Arch, not upstream, doesn't this mean that {{ic|/etc/bash.bashrc}} should be listed as "Yes" for both login shells, and interactive non-login shells? If someone's focused at the green/red Yes/No's, this chart makes it look like {{ic|/etc/bash.bashrc}} won't be sourced by a login shell. I'd say just change it to "Yes", but it could be changed to "Yes (see note)" and another note could be added that although upstream bash doesn't source {{ic|/etc/bash.bashrc}}, Arch's default {{ic|/etc/profile}} does.<br />
<br />
[[User:Jamespharvey20|Jamespharvey20]] ([[User talk:Jamespharvey20|talk]]) 09:31, 12 October 2018 (UTC)<br />
<br />
:There is a difference between "sourced by a shell" and "sourced by a shell script". Documenting the latter does not make sense because you can add custom source commands to force sourcing all listed config files in all types of shells as well as remove the command sourcing {{ic|/etc/bash.bashrc}} from {{ic|/etc/profile}}. -- [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 13:47, 12 October 2018 (UTC)</div>Malcontenthttps://wiki.archlinux.org/index.php?title=Talk:Arch_compared_to_other_distributions&diff=773309Talk:Arch compared to other distributions2023-03-20T11:30:26Z<p>Malcontent: Add signature</p>
<hr />
<div>== Add Alpine, Void ==<br />
<br />
Void and Alpine are reasonably popular by now. One of their features is a focus on "minimal size", so a subsection could be added to the article accordingly. There's some ambiguity with the [[Arch compared to other distributions#General]] section - both distributions are general purpose, and Debian/Ubuntu also focuses on "minimal size" to some extent (package splitting). Therefore one could either propose a different section name, or alternatively include Void/Alpine in [[Arch compared to other distributions#General]].<br />
<br />
Either way we should think of a write-up and probably include these distributions in the article. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 14:22, 3 September 2021 (UTC)<br />
<br />
:I'll start working on this now. Will likely include Puppy Linux and Tiny Core Linux as well, due to their fit to this category and mix of prominence and endurance. See [https://entvibes.com/archwiki/Small%20Linux%20Distros%20-%20Google%20Trends%20-%202021-09-05%20134735.png here]. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 03:57, 5 September 2021 (UTC)<br />
<br />
Why was this moved to draft state? I was basically done with it. Feel free to add to it, but it's in a comparable state now to the other lists. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 07:40, 5 September 2021 (UTC)<br />
<br />
:We are not done reviewing it. — [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 07:42, 5 September 2021 (UTC)<br />
<br />
:: Can we nuke all this stuff? It screams of content that requires a lot of upkeep (package count, etc), general advertising and a tremendous amount of fluff. Arch ethos is to keep it simple. None of this is remotely simple.<br />
:: [[User:Grawlinson|Grawlinson]] ([[User talk:Grawlinson|talk]]) 01:42, 8 September 2021 (UTC)<br />
<br />
::: I included info about package coverage, in rough approximations, because there was some open consideration of what overlap these have with more general-purpose distributions. It's not essential, but has already been researched and is of relevance to defining the class. Simply removing the content if it proves out of date without a maintainer would be understandable. These are also just comparisons to Arch. LFS is arguably "simpler" than Arch and distributions which are considerably smaller than Arch are also, by necessity, simpler than Arch... Arch isn't all about simplicity. Even the decision to break away from CRUX was over the concern of added complexity created by the envisioned metadata-included creation of pacman. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 03:28, 8 September 2021 (UTC)<br />
<br />
::: Also, I agree and appreciate that simplicity is in the ethos of Arch. Not trying to contest that at all. Just pointing out that it does necessitate some definition. For instance, I suggested "lightweight" as an alternative name for what is now proposed as "minimal-size". This was criticized as, "meaningless." Arch is trademarked as "A simple, lightweight distribution." Certainly, we don't want to face the same criticism from the outside. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 04:29, 8 September 2021 (UTC)<br />
<br />
::: That, "defining what Arch means by simple and lightweight," is part of where I see the value in this page. It's a concrete comparison of the tradeoffs Arch makes vs other projects so that the casual outside observer can clearly see how Archers prioritize simplicity and lightness vs other goals. So minimal-size is a category that specifically helps to define how Arch compares to other projects which more highly priotize "minimalism" or "lightweightness" or whatever you want to call it (currently the idea is that "Minimal-size" is the most apt short description). [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 04:38, 8 September 2021 (UTC)<br />
<br />
::: As a specific example of defining what Archers mean by simple: An Archer might argue that the convenience and stability gained by having a package manager which is better at keeping track of all the moving components in the system and how they interrelate ultimately provides for a simpler overall experience which more than offsets the engineering complexity of it. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 04:46, 8 September 2021 (UTC)<br />
<br />
::: And a specific example of how that definition can help in shaping the future of the distro: I'm currently advocating for an automated install process which covers, at least, the most common use-cases outlined in the [[Installation_guide]]. The argument being around how the added complexity of having an automated process which better keeps track of all the moving components in the system and how they interrelate ultimately provides for a simpler overall experience which more than offsets the engineering complexity of it. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 05:10, 8 September 2021 (UTC)<br />
<br />
:::: I would like to see more actual ''comparisons'' to Arch, rather than merely listing features of other distributions. For example, Void Linux uses pull requests to accept packages into their repositories, while Arch has the AUR with user-submitted packages, which are then cherry-picked to the repositories. Alpine uses APKBUILD, which is very similar to PKGBUILD but is strictly limited to POSIX shell features, e.g. no arrays. And so on.<br />
<br />
:::::Those are great details to include! Please do. My draft only serves as a foundation. I'd like to see more detailed comparison too. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 22:55, 8 September 2021 (UTC)<br />
<br />
:::: Personally I would also skip Tiny Core Linux and Puppy Linux. You even admit to their limited relevance in the distro landscape. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 18:34, 8 September 2021 (UTC)<br />
<br />
::::: Yeah, I've noticed you feel strongly that distros included here should have broad relevance as basically being very general purpose or being generally ubiquitous to those familiar with Linux. I feel like there's some opportunity to cherry-pick a few less ubiquitous distros specifically for the purpose of highlighting implementations which stretch the boundaries of what people might typically do with Linux. For Arch, aiming to be incredibly versatile and fostering of regular tinkering and expansion of the idea of what you can achieve with your system, I feel like it's a worthwhile thing to point these out! For instance, Tiny Core I think gives a wow moment to a lot of people when they realize a whole functional graphical desktop can fit in 11MB, and that adding Wi-Fi and non-US keyboards adds a whole order of magnitude in size and complexity. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 23:02, 8 September 2021 (UTC)<br />
<br />
:::::: It's also a very poignant contrast! Arch is ''A simple, lightweight distribution'', but within the confines of being totally general-purpose. Tiny Core, by comparison, is '''''maximally''''' simple and lightweight as an absolute first priority. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 23:46, 8 September 2021 (UTC)<br />
<br />
=== Draft: Minimal-size ===<br />
<br />
These distributions range in capability from being focused on embedded systems deployment or niche purposes, to having overlap with the more typical general purpose distros listed above. The defining factor of this category is that one of the primary reasons for these distributions to exist is that they are made to have as small of a footprint, in terms of size and resource usage, as is possible for their intended purpose. This generally implies compromises which would not be seen with other, more general-purpose, distributions.<br />
<br />
These distributions can be as small as ~12 MiB on disk, and more typically the minimal install is between 100 MiB and 700 MiB. By contrast, Arch aims to be lightweight, but to serve as a more general purpose system has a base install closer to ~2 GiB, and needing ~512 MiB RAM.<br />
<br />
==== Alpine Linux ====<br />
<br />
* Is a security focused distribution first. Is developed with the expectation it will be deployed to embedded and network edge devices such as routers. The mix of embedded use and a desire to reduce the [https://www.cymune.com/blog-details/Attack-Surface-Reduction "attack surface"] (which comes from extraneous or overly-complex software) for high-value devices motivates making installations of Alpine very small.<br />
* A minimal install is ~130MiB on disk.<br />
* Userland binaries compiled with [[Wikipedia:Position-independent code|position-independent executables]], to limit available exploits.<br />
* Achieves very small size in part by foregoing the usual choice of [[GNU#Toolchain|glibc]], and instead uses [[C#Alternative_libc_implementations|musl libc]].<br />
* [[BusyBox]] based, also to reduce size and complexity.<br />
* Still strives to be a general purpose distribution, and covers a wide variety of potential uses. Lack of glibc can introduce [https://www.musl-libc.org/faq.html compatibility issues] for some applications.<br />
** Package coverage: Over [https://repology.org/repository/alpine_3_14 5000 core projects], and [https://repology.org/repository/alpine_edge over 7500] in edge.<br />
** Wide platform support: i686, x86_64, ARM (hf, v7, AArch64), ppc64le, s390x<br />
* [https://wiki.gentoo.org/wiki/Project:OpenRC OpenRC] for [[init]]<br />
* Started in 2005, with steadily growing adoption, particularly since about 2015. Is now the most prominent minimal-size distribution.<br />
<br />
==== Void Linux ====<br />
<br />
* Is a general-purpose distribution with a focus on being fast and as small as possible.<br />
* Minimal installs: 96MiB RAM, 600MiB disk (700 with glibc)<br />
* i686 and x86_64 support<br />
* Built around both musl and glibc.<br />
* [[Runit]] for [[init]] system (Arch uses [[systemd]] by default)<br />
* Using [https://github.com/void-linux/xbps xbps] package manager.<br />
** Over [https://repology.org/repository/void_x86_64 7000 packages], comparable size to OpenBSD Ports.<br />
<br />
==== Puppy Linux ====<br />
* Is an end-user, desktop-focused, portable-first distribution.<br />
** Boots into a [[ramdisk]], primary intent to boot quickly off a USB stick.<br />
* Small size to enable quick portable boot off USB<br />
** ~130MiB minimum on disk (Typical: i686 - 300MB, x86_64 - 600MB)<br />
* Maintains two main variants: One Ubuntu derived, the other Slackware (also Raspbian for [https://www.raspberrypi.org/ RasPi]/[[ARM]])<br />
* One of the oldest and most enduring of the minimalist distributions. Peak interest in 2008, has [https://entvibes.com/archwiki/Small%20Linux%20Distros%20-%20Google%20Trends%20-%202021-09-05%20134735.png faded in prominence since].<br />
<br />
==== Tiny Core Linux ====<br />
* Is an extremely small graphical Linux desktop<br />
** ~12 MiB on disk (with Wi-Fi and non-US keyboard support: ~106 MiB)<br />
* Achieves small size by cherry-picking some of the smallest tools available for each purpose:<br />
** [[BusyBox]], [https://www.irif.fr/~jch/software/kdrive.html Tiny X], [https://www.fltk.org/ Fltk], and [https://github.com/tinycorelinux/flwm Flwm]<br />
* Can be used as a portable OS, in similar manner to Puppy Linux<br />
* Is limited in scope. Monolithic package updated twice a year since 2009.<br />
** Repo browser not online. State of package repositories unclear.<br />
* Ports for: i686, x86_64, ARM, RasPi<br />
<br />
== Add NixOS Somewhere ==<br />
<br />
I think currently Arch and NixOS are the most interesting comparison out of everything. Arch has been known as, "Linux, with a nice package manager" NixOS is might be more, "A nice package manager, oh and Linux too; purely functional, btw." [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 14:07, 5 September 2021 (UTC)<br />
<br />
:[[Arch compared to other distributions#General]]? -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 14:48, 5 September 2021 (UTC)<br />
<br />
::Yep, sure. I'll start working up a draft. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 01:19, 6 September 2021 (UTC)<br />
<br />
:::This draft could still use some more direct comparisons to Arch.[[User:Einr|Einr]] ([[User talk:Einr|talk]]) 22:38, 8 September 2021 (UTC)<br />
<br />
=== NixOS ===<br />
<br />
* While most distributions ''include'' a package manager, NixOS is unique in that it is a package manager first and only secondarily a Linux distribution. [https://nixos.org/manual/nix/stable/#ch-about-nix Nix], the package management system, aims to be a subsystem which can be installed on practically ''any'' Linux distribution. The aim being to be a universally applicable dependency management system for developers.<br />
** Allows use as a continuous-integration environment.<br />
** Allows replacement of language-specific package managers.<br />
** Allows use of a single tool for all project build, machine configuration, and cloud deployment management.<br />
** Is a developer-centric OS.<br />
* Uses a purely functional package language, to avoid side-effects. The ultimate goal from this is to enable [https://reproducible-builds.org/ Reproducible Builds].<br />
** Making [https://discourse.nixos.org/t/nixos-unstable-s-iso-minimal-x86-64-linux-is-100-reproducible/13723 progress] in this.<br />
** This is a major security consideration for any software available in binary form.<br />
** Allows truly atomic changes, which are easily rolled back, for most system management operations. The aim is both for stability and to encourage tinkering, similar to Archer mentality.<br />
*** Arch, comparatively, is not designed around this notion. However, it is versatile and with the right selection of filesystem and supporting software can approach a similar level of reversibility. The snapshotting functionality of [[Btrfs#Snapshots|btrfs]], along with judicious configuration of software like [[Synchronization_and_backup_programs#File-based_increments|TimeShift]] can allow most of this benefit.<br />
* Has one of the largest, most up to date, package ecosystems in the Linux world; comparable to Arch, if AUR is included.<br />
** A core strategic project focus is on increasing and improving the package coverage, functional status, and up-to-date-ness. Semi-annual [https://nixos.org/blog/announcements.html#21.05 releases] have a release manager who actively tracks this and doles out praise and recognition for contributing.<br />
<br />
== Add particularly interesting note about NetBSD ==<br />
<br />
While writing up the content above about minimal distros and researching and filling in their platform support I threw in the note in the section below about NetBSD.<br />
<br />
This was just [https://wiki.archlinux.org/index.php?title=Arch_compared_to_other_distributions&type=revision&diff=694206&oldid=694205 reverted].<br />
The justification being: "remove the one detail about one specific BSD variant - not related to Arch, there is no explicit list of BSDs and everything can be found on the linked Wikipedia page"<br />
<br />
This justification doesn't stand up for several reasons:<br />
# This page is littered with references to platform support.<br />
# Arch is notable for only supporting x86_64. People are likely to specifically be looking here for platform support contrasts.<br />
# The Wikipedia page does mention the portability-focused design, but does not specifically call out that NetBSD is ''the'' portable OS as far as the *NIX world is concerned.<br />
<br />
Please only revert content when there's a ''very'' clear and widely acceptable reason not to include it. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 07:37, 5 September 2021 (UTC)<br />
<br />
:The page used to have a detailed list of BSDs. That quickly turned into an ad board. [https://wiki.archlinux.org/index.php?title=Arch_compared_to_other_distributions&oldid=418996#The_*BSDs] So we have no interest in having anything more than what the page has now. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 12:51, 5 September 2021 (UTC)<br />
<br />
::Perhaps then a quick one-line summary of each, and an ongoing policy that this isn't expanded further. Proposed content below. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 05:06, 6 September 2021 (UTC)<br />
<br />
:::The currently proposed content is missing any comparison with Arch, so it is out of this page's scope. Providing quick summaries of 3 BSDs is pointless, they can be found elsewhere. This page is about giving comparisons (with Arch!), not summaries. — [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 20:32, 7 September 2021 (UTC)<br />
<br />
::::Agreed! I thought the NetBSD note about being most-portable was a poignant self-evident contrast to Arch only supporting one platform, which is why I wanted to include that one specifically. If the choice is between none and all of the well known ones, I'd rather include all though. Here's a quick whack at a comparison. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 22:47, 8 September 2021 (UTC)<br />
<br />
=== Reverted content ===<br />
[Ed: This was in the BSDs section]<br />
* NetBSD is notable for it's portability-focused design. It runs on [https://www.netbsd.org/ports/ more platforms] than possibly any other OS.<br />
<br />
=== Proposed content ===<br />
* As in the Linux world, there are many BSD derivatives. The top three are summarized below.<br />
** FreeBSD - The biggest. Tries to be everything. Focused on SMP server use and implements fine-grained locking to improve scalability. Arch is also focused on being very general-purpose, and the Linux kernel is arguably the best refined kernel for SMP scalability in the open source world currently.<br />
** OpenBSD - Security-centric. Absolute focus on ongoing code audits. Arch tries to maintain security by keeping the core distribution tightly controlled through highly trusted users and rigorous review, but doesn't centrally focus on security as the main goal of the release.<br />
** NetBSD - Possibly the most portable OS. Runs on [https://www.netbsd.org/ports/ an extensive variety of platforms]. Arch instead only supports x86_64, in order to provide focus on the core use-case: contemporary desktop, mobile, and server.<br />
<br />
== Add corpo distros ==<br />
<br />
:What better contrast is there to Arch than the commercial server distros? Basically the ossified antithesis of rolling-release. RHEL, SLES... just a short summary of how they're keeping old kernels on life support. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 06:24, 6 September 2021 (UTC)<br />
<br />
:Just throwing up a quick draft. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 06:38, 6 September 2021 (UTC)<br />
<br />
::I don't think we should promote/advertise commercial distributions by mentioning them here. -- [[User:nl6720|nl6720]] ([[User talk:nl6720|talk]]) 07:02, 6 September 2021 (UTC)<br />
<br />
:::Part of me agrees. Most people seem to agree though that RedHat and SUSE have been fairly responsible and among the best of the corporate actors in the open source world. Both of these distros remain fully open source, and only support contracts are sold. Also, what I've written hardly reads as an endorsement. I'm adding a note now to drive the philosophical contrast, which is what this section is really about. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 23:55, 6 September 2021 (UTC)<br />
<br />
:::As a further note, I'm actively contributing these comparisons to help promote a dialog on what Arch stands for and how it stands out. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 00:04, 7 September 2021 (UTC)<br />
<br />
:::Playing devil's advocate (on ossified old-kernel life support, vs. constantly pushing everything to be up to date): A corporate CTO might argue that, in their current environment, they are dependent upon software which, due to it's niche "vertical" nature cannot be so actively kept up to date or perhaps exists in a lab or high-volume manufacturing environment which they must prioritize being as frozen as possible. They might point to the difficulty they experience currently in even completing a two-year-long migration every decade as they must receive buy-in from many silo'ed global business groups with their own specialty needs across dozens of global datacenters housing tens of thousands of servers. How, possibly, could they expect to migrate to rolling release? A CEO who insists that they investigate the possibility may have a team formed, with options investigated. Requests across the IT department are put out for views from developers and admins and internal customer-group representatives on the prospect. Sysadmins and performance engineers point to the massive improvements to Linux kernel observability which are only just reaching maturity in the latest kernels, begging and hoping and dreaming that they be able to use them across the whole landscape. Manufacturing leads respond bluntly, "Hell will freeze over before you touch our systems. We're still secretly hiding SunOS systems from you (oh did I say that out loud?)."<br />
<br />
::::An optimistic outcome: A compromise is formed. Rolling-release is allowed for a new internal-cloud, and new bare-metal installations must thoroughly justify LTS installs. Actually, you can just roll whatever ISO you want (with some usergroup gating and a bit of IT oversight)! All business groups are expected then to increasingly justify having old-kernel environments, which are further isolated. The CTO remembers to tip-toe around manufacturing (they found a possum in one of those SunOS servers, and no one is sure if it was living there already...). RedHat and SUSE catch wind of and encourage this trend and offer rolling release enterprise-commercial distros, allowing further re-allocation of engineering headcount towards new tech and ongoing security and stability audits; everyone wins. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 00:44, 7 September 2021 (UTC)<br />
<br />
:::::I don't know about those corporate details you mention. But Fedora and openSUSE, the underpinnings for RHEL and SLES respectively, are already mentioned on this page. As such, the main distinction points for these distros are already listed. openSUSE Leap is even 100% binary compatible to SLES nowadays. [https://www.suse.com/c/introducing-suse-linux-enterprise-15-sp3/] -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 18:39, 8 September 2021 (UTC)<br />
<br />
::::::Yeah, that's why I thought it best to only include a bare-bones summary of the primary detail which provides such a sharp contrast to the rolling release model of Arch here. As you've said, the other more detailed contrasts to Arch are better highlighted in the comparisons to the community versions of these distros. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 22:33, 8 September 2021 (UTC)<br />
<br />
=== Enterprise-commercial ===<br />
<br />
These distributions are the commercial arms of the corporate giants in the Linux world: RedHat and SUSE. The companies play a large part in providing to the kernel and core libraries, and these distributions are their support-provided offerings to corporations. Large corporations expect very long term support for in-house datacenter server installations, and that has led to Red Hat Enterprise Linux and SUSE Linux Enterprise Server having decade-long lifecycles where very old kernels and libraries are maintained with security packages and occasional feature backports. This is effectively the antithesis of the rolling-release model, as championed by Arch; Archers tend to believe that the most stable and secure system is achieved by maintaining a laser focus on keeping up to date.<br />
<br />
== <s>Swap order of CRUX and LFS</s> ==<br />
<br />
I know that CRUX has a special meaning for Arch, however LFS is a special case, as it not really a distribution, but more or less the starting point for who wants to create a distribution. Thus I think LFS should be the first of the list, then CRUX, then the rest. What do you people think? --[[User:Grufo|Grufo]] <sup>[ [[Special:Contributions/Grufo|contribs]] | [[User_talk:Grufo|talk]] ]</sup> 18:18, 29 October 2021 (UTC)<br />
<br />
:You could argue for it both ways (personally I prefer CRUX at top). I doubt it matters enough to change the article, though. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 13:29, 30 October 2021 (UTC)<br />
<br />
:: Yes, of course, it is a totally unimportant detail. I just noticed while reading the article that it feels strange to have a list with a distribution, a guide to how to create a distribution, a distribution, a distribution, a distribution, etc. But probably this is really subjective. --[[User:Grufo|Grufo]] <sup>[ [[Special:Contributions/Grufo|contribs]] | [[User_talk:Grufo|talk]] ]</sup> 08:52, 1 November 2021 (UTC)<br />
<br />
:::Instead, let's bring LFS to the bottom. That way, we can keep the actual distributions listed after each other, have the special case "isolated" from the rest while keeping CRUX at the top since it has a special meaning for Arch. [[User:Cont999|Cont999]] ([[User talk:Cont999|talk]]) 19:13, 7 October 2022 (UTC)<br />
<br />
::::This makes even less sense to me. It is even noted that 'Judd Vinet built Arch from scratch, and then wrote pacman in C. Historically, Arch was sometimes humorously described simply as "Linux, with a nice package manager."'. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 23:56, 7 October 2022 (UTC)<br />
<br />
:::::This didn't lead anywhere, closing. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 11:29, 20 March 2023 (UTC)<br />
<br />
== <s>Gentoo/Funtoo Linux</s> ==<br />
<br />
Gentoo's official package and system management tools tend to be rather more complex and "powerful" than those provided by Arch [...]<br />
<br />
Is there a reason why powerful is spelled with quotes in this example? If the features of portage are being questioned then I want to see real arguments against. Spelling powerful between quotes is unprofessional and makes it seem like it was written by biased Arch Linux users.<br />
<br />
Please drop the quotes or provide real arguments because portage is miles ahead of pacman in many ways. -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 11:30, 20 March 2023 (UTC)<br />
<br />
:The quotes refer to the concept of powerful, because more features in a package manager is not considered a virtue by everyone. It does not question portage actually having more features. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 11:29, 20 March 2023 (UTC)</div>Malcontenthttps://wiki.archlinux.org/index.php?title=Talk:Arch_compared_to_other_distributions&diff=773285Talk:Arch compared to other distributions2023-03-20T10:12:28Z<p>Malcontent: Gentoo/Funtoo Linux</p>
<hr />
<div>== Gentoo/Funtoo Linux ==<br />
<br />
Gentoo's official package and system management tools tend to be rather more complex and "powerful" than those provided by Arch [...]<br />
<br />
Is there a reason why powerful is spelled with quotes in this example? If the features of portage are being questioned then I want to see real arguments against. Spelling powerful between quotes is unprofessional and makes it seem like it was written by biased Arch Linux users.<br />
<br />
Please drop the quotes or provide real arguments because portage is miles ahead of pacman in many ways.<br />
<br />
== Add Alpine, Void ==<br />
<br />
Void and Alpine are reasonably popular by now. One of their features is a focus on "minimal size", so a subsection could be added to the article accordingly. There's some ambiguity with the [[Arch compared to other distributions#General]] section - both distributions are general purpose, and Debian/Ubuntu also focuses on "minimal size" to some extent (package splitting). Therefore one could either propose a different section name, or alternatively include Void/Alpine in [[Arch compared to other distributions#General]].<br />
<br />
Either way we should think of a write-up and probably include these distributions in the article. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 14:22, 3 September 2021 (UTC)<br />
<br />
:I'll start working on this now. Will likely include Puppy Linux and Tiny Core Linux as well, due to their fit to this category and mix of prominence and endurance. See [https://entvibes.com/archwiki/Small%20Linux%20Distros%20-%20Google%20Trends%20-%202021-09-05%20134735.png here]. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 03:57, 5 September 2021 (UTC)<br />
<br />
Why was this moved to draft state? I was basically done with it. Feel free to add to it, but it's in a comparable state now to the other lists. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 07:40, 5 September 2021 (UTC)<br />
<br />
:We are not done reviewing it. — [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 07:42, 5 September 2021 (UTC)<br />
<br />
:: Can we nuke all this stuff? It screams of content that requires a lot of upkeep (package count, etc), general advertising and a tremendous amount of fluff. Arch ethos is to keep it simple. None of this is remotely simple.<br />
:: [[User:Grawlinson|Grawlinson]] ([[User talk:Grawlinson|talk]]) 01:42, 8 September 2021 (UTC)<br />
<br />
::: I included info about package coverage, in rough approximations, because there was some open consideration of what overlap these have with more general-purpose distributions. It's not essential, but has already been researched and is of relevance to defining the class. Simply removing the content if it proves out of date without a maintainer would be understandable. These are also just comparisons to Arch. LFS is arguably "simpler" than Arch and distributions which are considerably smaller than Arch are also, by necessity, simpler than Arch... Arch isn't all about simplicity. Even the decision to break away from CRUX was over the concern of added complexity created by the envisioned metadata-included creation of pacman. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 03:28, 8 September 2021 (UTC)<br />
<br />
::: Also, I agree and appreciate that simplicity is in the ethos of Arch. Not trying to contest that at all. Just pointing out that it does necessitate some definition. For instance, I suggested "lightweight" as an alternative name for what is now proposed as "minimal-size". This was criticized as, "meaningless." Arch is trademarked as "A simple, lightweight distribution." Certainly, we don't want to face the same criticism from the outside. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 04:29, 8 September 2021 (UTC)<br />
<br />
::: That, "defining what Arch means by simple and lightweight," is part of where I see the value in this page. It's a concrete comparison of the tradeoffs Arch makes vs other projects so that the casual outside observer can clearly see how Archers prioritize simplicity and lightness vs other goals. So minimal-size is a category that specifically helps to define how Arch compares to other projects which more highly priotize "minimalism" or "lightweightness" or whatever you want to call it (currently the idea is that "Minimal-size" is the most apt short description). [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 04:38, 8 September 2021 (UTC)<br />
<br />
::: As a specific example of defining what Archers mean by simple: An Archer might argue that the convenience and stability gained by having a package manager which is better at keeping track of all the moving components in the system and how they interrelate ultimately provides for a simpler overall experience which more than offsets the engineering complexity of it. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 04:46, 8 September 2021 (UTC)<br />
<br />
::: And a specific example of how that definition can help in shaping the future of the distro: I'm currently advocating for an automated install process which covers, at least, the most common use-cases outlined in the [[Installation_guide]]. The argument being around how the added complexity of having an automated process which better keeps track of all the moving components in the system and how they interrelate ultimately provides for a simpler overall experience which more than offsets the engineering complexity of it. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 05:10, 8 September 2021 (UTC)<br />
<br />
:::: I would like to see more actual ''comparisons'' to Arch, rather than merely listing features of other distributions. For example, Void Linux uses pull requests to accept packages into their repositories, while Arch has the AUR with user-submitted packages, which are then cherry-picked to the repositories. Alpine uses APKBUILD, which is very similar to PKGBUILD but is strictly limited to POSIX shell features, e.g. no arrays. And so on.<br />
<br />
:::::Those are great details to include! Please do. My draft only serves as a foundation. I'd like to see more detailed comparison too. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 22:55, 8 September 2021 (UTC)<br />
<br />
:::: Personally I would also skip Tiny Core Linux and Puppy Linux. You even admit to their limited relevance in the distro landscape. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 18:34, 8 September 2021 (UTC)<br />
<br />
::::: Yeah, I've noticed you feel strongly that distros included here should have broad relevance as basically being very general purpose or being generally ubiquitous to those familiar with Linux. I feel like there's some opportunity to cherry-pick a few less ubiquitous distros specifically for the purpose of highlighting implementations which stretch the boundaries of what people might typically do with Linux. For Arch, aiming to be incredibly versatile and fostering of regular tinkering and expansion of the idea of what you can achieve with your system, I feel like it's a worthwhile thing to point these out! For instance, Tiny Core I think gives a wow moment to a lot of people when they realize a whole functional graphical desktop can fit in 11MB, and that adding Wi-Fi and non-US keyboards adds a whole order of magnitude in size and complexity. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 23:02, 8 September 2021 (UTC)<br />
<br />
:::::: It's also a very poignant contrast! Arch is ''A simple, lightweight distribution'', but within the confines of being totally general-purpose. Tiny Core, by comparison, is '''''maximally''''' simple and lightweight as an absolute first priority. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 23:46, 8 September 2021 (UTC)<br />
<br />
=== Draft: Minimal-size ===<br />
<br />
These distributions range in capability from being focused on embedded systems deployment or niche purposes, to having overlap with the more typical general purpose distros listed above. The defining factor of this category is that one of the primary reasons for these distributions to exist is that they are made to have as small of a footprint, in terms of size and resource usage, as is possible for their intended purpose. This generally implies compromises which would not be seen with other, more general-purpose, distributions.<br />
<br />
These distributions can be as small as ~12 MiB on disk, and more typically the minimal install is between 100 MiB and 700 MiB. By contrast, Arch aims to be lightweight, but to serve as a more general purpose system has a base install closer to ~2 GiB, and needing ~512 MiB RAM.<br />
<br />
==== Alpine Linux ====<br />
<br />
* Is a security focused distribution first. Is developed with the expectation it will be deployed to embedded and network edge devices such as routers. The mix of embedded use and a desire to reduce the [https://www.cymune.com/blog-details/Attack-Surface-Reduction "attack surface"] (which comes from extraneous or overly-complex software) for high-value devices motivates making installations of Alpine very small.<br />
* A minimal install is ~130MiB on disk.<br />
* Userland binaries compiled with [[Wikipedia:Position-independent code|position-independent executables]], to limit available exploits.<br />
* Achieves very small size in part by foregoing the usual choice of [[GNU#Toolchain|glibc]], and instead uses [[C#Alternative_libc_implementations|musl libc]].<br />
* [[BusyBox]] based, also to reduce size and complexity.<br />
* Still strives to be a general purpose distribution, and covers a wide variety of potential uses. Lack of glibc can introduce [https://www.musl-libc.org/faq.html compatibility issues] for some applications.<br />
** Package coverage: Over [https://repology.org/repository/alpine_3_14 5000 core projects], and [https://repology.org/repository/alpine_edge over 7500] in edge.<br />
** Wide platform support: i686, x86_64, ARM (hf, v7, AArch64), ppc64le, s390x<br />
* [https://wiki.gentoo.org/wiki/Project:OpenRC OpenRC] for [[init]]<br />
* Started in 2005, with steadily growing adoption, particularly since about 2015. Is now the most prominent minimal-size distribution.<br />
<br />
==== Void Linux ====<br />
<br />
* Is a general-purpose distribution with a focus on being fast and as small as possible.<br />
* Minimal installs: 96MiB RAM, 600MiB disk (700 with glibc)<br />
* i686 and x86_64 support<br />
* Built around both musl and glibc.<br />
* [[Runit]] for [[init]] system (Arch uses [[systemd]] by default)<br />
* Using [https://github.com/void-linux/xbps xbps] package manager.<br />
** Over [https://repology.org/repository/void_x86_64 7000 packages], comparable size to OpenBSD Ports.<br />
<br />
==== Puppy Linux ====<br />
* Is an end-user, desktop-focused, portable-first distribution.<br />
** Boots into a [[ramdisk]], primary intent to boot quickly off a USB stick.<br />
* Small size to enable quick portable boot off USB<br />
** ~130MiB minimum on disk (Typical: i686 - 300MB, x86_64 - 600MB)<br />
* Maintains two main variants: One Ubuntu derived, the other Slackware (also Raspbian for [https://www.raspberrypi.org/ RasPi]/[[ARM]])<br />
* One of the oldest and most enduring of the minimalist distributions. Peak interest in 2008, has [https://entvibes.com/archwiki/Small%20Linux%20Distros%20-%20Google%20Trends%20-%202021-09-05%20134735.png faded in prominence since].<br />
<br />
==== Tiny Core Linux ====<br />
* Is an extremely small graphical Linux desktop<br />
** ~12 MiB on disk (with Wi-Fi and non-US keyboard support: ~106 MiB)<br />
* Achieves small size by cherry-picking some of the smallest tools available for each purpose:<br />
** [[BusyBox]], [https://www.irif.fr/~jch/software/kdrive.html Tiny X], [https://www.fltk.org/ Fltk], and [https://github.com/tinycorelinux/flwm Flwm]<br />
* Can be used as a portable OS, in similar manner to Puppy Linux<br />
* Is limited in scope. Monolithic package updated twice a year since 2009.<br />
** Repo browser not online. State of package repositories unclear.<br />
* Ports for: i686, x86_64, ARM, RasPi<br />
<br />
== Add NixOS Somewhere ==<br />
<br />
I think currently Arch and NixOS are the most interesting comparison out of everything. Arch has been known as, "Linux, with a nice package manager" NixOS is might be more, "A nice package manager, oh and Linux too; purely functional, btw." [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 14:07, 5 September 2021 (UTC)<br />
<br />
:[[Arch compared to other distributions#General]]? -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 14:48, 5 September 2021 (UTC)<br />
<br />
::Yep, sure. I'll start working up a draft. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 01:19, 6 September 2021 (UTC)<br />
<br />
:::This draft could still use some more direct comparisons to Arch.[[User:Einr|Einr]] ([[User talk:Einr|talk]]) 22:38, 8 September 2021 (UTC)<br />
<br />
=== NixOS ===<br />
<br />
* While most distributions ''include'' a package manager, NixOS is unique in that it is a package manager first and only secondarily a Linux distribution. [https://nixos.org/manual/nix/stable/#ch-about-nix Nix], the package management system, aims to be a subsystem which can be installed on practically ''any'' Linux distribution. The aim being to be a universally applicable dependency management system for developers.<br />
** Allows use as a continuous-integration environment.<br />
** Allows replacement of language-specific package managers.<br />
** Allows use of a single tool for all project build, machine configuration, and cloud deployment management.<br />
** Is a developer-centric OS.<br />
* Uses a purely functional package language, to avoid side-effects. The ultimate goal from this is to enable [https://reproducible-builds.org/ Reproducible Builds].<br />
** Making [https://discourse.nixos.org/t/nixos-unstable-s-iso-minimal-x86-64-linux-is-100-reproducible/13723 progress] in this.<br />
** This is a major security consideration for any software available in binary form.<br />
** Allows truly atomic changes, which are easily rolled back, for most system management operations. The aim is both for stability and to encourage tinkering, similar to Archer mentality.<br />
*** Arch, comparatively, is not designed around this notion. However, it is versatile and with the right selection of filesystem and supporting software can approach a similar level of reversibility. The snapshotting functionality of [[Btrfs#Snapshots|btrfs]], along with judicious configuration of software like [[Synchronization_and_backup_programs#File-based_increments|TimeShift]] can allow most of this benefit.<br />
* Has one of the largest, most up to date, package ecosystems in the Linux world; comparable to Arch, if AUR is included.<br />
** A core strategic project focus is on increasing and improving the package coverage, functional status, and up-to-date-ness. Semi-annual [https://nixos.org/blog/announcements.html#21.05 releases] have a release manager who actively tracks this and doles out praise and recognition for contributing.<br />
<br />
== Add particularly interesting note about NetBSD ==<br />
<br />
While writing up the content above about minimal distros and researching and filling in their platform support I threw in the note in the section below about NetBSD.<br />
<br />
This was just [https://wiki.archlinux.org/index.php?title=Arch_compared_to_other_distributions&type=revision&diff=694206&oldid=694205 reverted].<br />
The justification being: "remove the one detail about one specific BSD variant - not related to Arch, there is no explicit list of BSDs and everything can be found on the linked Wikipedia page"<br />
<br />
This justification doesn't stand up for several reasons:<br />
# This page is littered with references to platform support.<br />
# Arch is notable for only supporting x86_64. People are likely to specifically be looking here for platform support contrasts.<br />
# The Wikipedia page does mention the portability-focused design, but does not specifically call out that NetBSD is ''the'' portable OS as far as the *NIX world is concerned.<br />
<br />
Please only revert content when there's a ''very'' clear and widely acceptable reason not to include it. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 07:37, 5 September 2021 (UTC)<br />
<br />
:The page used to have a detailed list of BSDs. That quickly turned into an ad board. [https://wiki.archlinux.org/index.php?title=Arch_compared_to_other_distributions&oldid=418996#The_*BSDs] So we have no interest in having anything more than what the page has now. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 12:51, 5 September 2021 (UTC)<br />
<br />
::Perhaps then a quick one-line summary of each, and an ongoing policy that this isn't expanded further. Proposed content below. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 05:06, 6 September 2021 (UTC)<br />
<br />
:::The currently proposed content is missing any comparison with Arch, so it is out of this page's scope. Providing quick summaries of 3 BSDs is pointless, they can be found elsewhere. This page is about giving comparisons (with Arch!), not summaries. — [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 20:32, 7 September 2021 (UTC)<br />
<br />
::::Agreed! I thought the NetBSD note about being most-portable was a poignant self-evident contrast to Arch only supporting one platform, which is why I wanted to include that one specifically. If the choice is between none and all of the well known ones, I'd rather include all though. Here's a quick whack at a comparison. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 22:47, 8 September 2021 (UTC)<br />
<br />
=== Reverted content ===<br />
[Ed: This was in the BSDs section]<br />
* NetBSD is notable for it's portability-focused design. It runs on [https://www.netbsd.org/ports/ more platforms] than possibly any other OS.<br />
<br />
=== Proposed content ===<br />
* As in the Linux world, there are many BSD derivatives. The top three are summarized below.<br />
** FreeBSD - The biggest. Tries to be everything. Focused on SMP server use and implements fine-grained locking to improve scalability. Arch is also focused on being very general-purpose, and the Linux kernel is arguably the best refined kernel for SMP scalability in the open source world currently.<br />
** OpenBSD - Security-centric. Absolute focus on ongoing code audits. Arch tries to maintain security by keeping the core distribution tightly controlled through highly trusted users and rigorous review, but doesn't centrally focus on security as the main goal of the release.<br />
** NetBSD - Possibly the most portable OS. Runs on [https://www.netbsd.org/ports/ an extensive variety of platforms]. Arch instead only supports x86_64, in order to provide focus on the core use-case: contemporary desktop, mobile, and server.<br />
<br />
== Add corpo distros ==<br />
<br />
:What better contrast is there to Arch than the commercial server distros? Basically the ossified antithesis of rolling-release. RHEL, SLES... just a short summary of how they're keeping old kernels on life support. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 06:24, 6 September 2021 (UTC)<br />
<br />
:Just throwing up a quick draft. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 06:38, 6 September 2021 (UTC)<br />
<br />
::I don't think we should promote/advertise commercial distributions by mentioning them here. -- [[User:nl6720|nl6720]] ([[User talk:nl6720|talk]]) 07:02, 6 September 2021 (UTC)<br />
<br />
:::Part of me agrees. Most people seem to agree though that RedHat and SUSE have been fairly responsible and among the best of the corporate actors in the open source world. Both of these distros remain fully open source, and only support contracts are sold. Also, what I've written hardly reads as an endorsement. I'm adding a note now to drive the philosophical contrast, which is what this section is really about. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 23:55, 6 September 2021 (UTC)<br />
<br />
:::As a further note, I'm actively contributing these comparisons to help promote a dialog on what Arch stands for and how it stands out. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 00:04, 7 September 2021 (UTC)<br />
<br />
:::Playing devil's advocate (on ossified old-kernel life support, vs. constantly pushing everything to be up to date): A corporate CTO might argue that, in their current environment, they are dependent upon software which, due to it's niche "vertical" nature cannot be so actively kept up to date or perhaps exists in a lab or high-volume manufacturing environment which they must prioritize being as frozen as possible. They might point to the difficulty they experience currently in even completing a two-year-long migration every decade as they must receive buy-in from many silo'ed global business groups with their own specialty needs across dozens of global datacenters housing tens of thousands of servers. How, possibly, could they expect to migrate to rolling release? A CEO who insists that they investigate the possibility may have a team formed, with options investigated. Requests across the IT department are put out for views from developers and admins and internal customer-group representatives on the prospect. Sysadmins and performance engineers point to the massive improvements to Linux kernel observability which are only just reaching maturity in the latest kernels, begging and hoping and dreaming that they be able to use them across the whole landscape. Manufacturing leads respond bluntly, "Hell will freeze over before you touch our systems. We're still secretly hiding SunOS systems from you (oh did I say that out loud?)."<br />
<br />
::::An optimistic outcome: A compromise is formed. Rolling-release is allowed for a new internal-cloud, and new bare-metal installations must thoroughly justify LTS installs. Actually, you can just roll whatever ISO you want (with some usergroup gating and a bit of IT oversight)! All business groups are expected then to increasingly justify having old-kernel environments, which are further isolated. The CTO remembers to tip-toe around manufacturing (they found a possum in one of those SunOS servers, and no one is sure if it was living there already...). RedHat and SUSE catch wind of and encourage this trend and offer rolling release enterprise-commercial distros, allowing further re-allocation of engineering headcount towards new tech and ongoing security and stability audits; everyone wins. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 00:44, 7 September 2021 (UTC)<br />
<br />
:::::I don't know about those corporate details you mention. But Fedora and openSUSE, the underpinnings for RHEL and SLES respectively, are already mentioned on this page. As such, the main distinction points for these distros are already listed. openSUSE Leap is even 100% binary compatible to SLES nowadays. [https://www.suse.com/c/introducing-suse-linux-enterprise-15-sp3/] -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 18:39, 8 September 2021 (UTC)<br />
<br />
::::::Yeah, that's why I thought it best to only include a bare-bones summary of the primary detail which provides such a sharp contrast to the rolling release model of Arch here. As you've said, the other more detailed contrasts to Arch are better highlighted in the comparisons to the community versions of these distros. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 22:33, 8 September 2021 (UTC)<br />
<br />
=== Enterprise-commercial ===<br />
<br />
These distributions are the commercial arms of the corporate giants in the Linux world: RedHat and SUSE. The companies play a large part in providing to the kernel and core libraries, and these distributions are their support-provided offerings to corporations. Large corporations expect very long term support for in-house datacenter server installations, and that has led to Red Hat Enterprise Linux and SUSE Linux Enterprise Server having decade-long lifecycles where very old kernels and libraries are maintained with security packages and occasional feature backports. This is effectively the antithesis of the rolling-release model, as championed by Arch; Archers tend to believe that the most stable and secure system is achieved by maintaining a laser focus on keeping up to date.<br />
<br />
== Swap order of CRUX and LFS ==<br />
<br />
I know that CRUX has a special meaning for Arch, however LFS is a special case, as it not really a distribution, but more or less the starting point for who wants to create a distribution. Thus I think LFS should be the first of the list, then CRUX, then the rest. What do you people think? --[[User:Grufo|Grufo]] <sup>[ [[Special:Contributions/Grufo|contribs]] | [[User_talk:Grufo|talk]] ]</sup> 18:18, 29 October 2021 (UTC)<br />
<br />
:You could argue for it both ways (personally I prefer CRUX at top). I doubt it matters enough to change the article, though. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 13:29, 30 October 2021 (UTC)<br />
<br />
:: Yes, of course, it is a totally unimportant detail. I just noticed while reading the article that it feels strange to have a list with a distribution, a guide to how to create a distribution, a distribution, a distribution, a distribution, etc. But probably this is really subjective. --[[User:Grufo|Grufo]] <sup>[ [[Special:Contributions/Grufo|contribs]] | [[User_talk:Grufo|talk]] ]</sup> 08:52, 1 November 2021 (UTC)<br />
<br />
:::Instead, let's bring LFS to the bottom. That way, we can keep the actual distributions listed after each other, have the special case "isolated" from the rest while keeping CRUX at the top since it has a special meaning for Arch. [[User:Cont999|Cont999]] ([[User talk:Cont999|talk]]) 19:13, 7 October 2022 (UTC)<br />
<br />
::::This makes even less sense to me. It is even noted that 'Judd Vinet built Arch from scratch, and then wrote pacman in C. Historically, Arch was sometimes humorously described simply as "Linux, with a nice package manager."'. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 23:56, 7 October 2022 (UTC)</div>Malcontenthttps://wiki.archlinux.org/index.php?title=Talk:Arch_compared_to_other_distributions&diff=773284Talk:Arch compared to other distributions2023-03-20T09:54:56Z<p>Malcontent: Gentoo/Funtoo Linux</p>
<hr />
<div>== Gentoo/Funtoo Linux ==<br />
<br />
"Gentoo's official package and system management tools tend to be rather more complex and "powerful" than those provided by Arch"<br />
<br />
Is there a reason why powerful is spelled with quotes in this example? If the features of portage are being questioned then I want to see real arguments against. Spelling powerful between quotes is unprofessional and makes it seem like it was written by biased Arch Linux users.<br />
<br />
Please drop the quotes or provide real arguments because portage is miles ahead of pacman in many ways.<br />
<br />
== Add Alpine, Void ==<br />
<br />
Void and Alpine are reasonably popular by now. One of their features is a focus on "minimal size", so a subsection could be added to the article accordingly. There's some ambiguity with the [[Arch compared to other distributions#General]] section - both distributions are general purpose, and Debian/Ubuntu also focuses on "minimal size" to some extent (package splitting). Therefore one could either propose a different section name, or alternatively include Void/Alpine in [[Arch compared to other distributions#General]].<br />
<br />
Either way we should think of a write-up and probably include these distributions in the article. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 14:22, 3 September 2021 (UTC)<br />
<br />
:I'll start working on this now. Will likely include Puppy Linux and Tiny Core Linux as well, due to their fit to this category and mix of prominence and endurance. See [https://entvibes.com/archwiki/Small%20Linux%20Distros%20-%20Google%20Trends%20-%202021-09-05%20134735.png here]. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 03:57, 5 September 2021 (UTC)<br />
<br />
Why was this moved to draft state? I was basically done with it. Feel free to add to it, but it's in a comparable state now to the other lists. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 07:40, 5 September 2021 (UTC)<br />
<br />
:We are not done reviewing it. — [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 07:42, 5 September 2021 (UTC)<br />
<br />
:: Can we nuke all this stuff? It screams of content that requires a lot of upkeep (package count, etc), general advertising and a tremendous amount of fluff. Arch ethos is to keep it simple. None of this is remotely simple.<br />
:: [[User:Grawlinson|Grawlinson]] ([[User talk:Grawlinson|talk]]) 01:42, 8 September 2021 (UTC)<br />
<br />
::: I included info about package coverage, in rough approximations, because there was some open consideration of what overlap these have with more general-purpose distributions. It's not essential, but has already been researched and is of relevance to defining the class. Simply removing the content if it proves out of date without a maintainer would be understandable. These are also just comparisons to Arch. LFS is arguably "simpler" than Arch and distributions which are considerably smaller than Arch are also, by necessity, simpler than Arch... Arch isn't all about simplicity. Even the decision to break away from CRUX was over the concern of added complexity created by the envisioned metadata-included creation of pacman. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 03:28, 8 September 2021 (UTC)<br />
<br />
::: Also, I agree and appreciate that simplicity is in the ethos of Arch. Not trying to contest that at all. Just pointing out that it does necessitate some definition. For instance, I suggested "lightweight" as an alternative name for what is now proposed as "minimal-size". This was criticized as, "meaningless." Arch is trademarked as "A simple, lightweight distribution." Certainly, we don't want to face the same criticism from the outside. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 04:29, 8 September 2021 (UTC)<br />
<br />
::: That, "defining what Arch means by simple and lightweight," is part of where I see the value in this page. It's a concrete comparison of the tradeoffs Arch makes vs other projects so that the casual outside observer can clearly see how Archers prioritize simplicity and lightness vs other goals. So minimal-size is a category that specifically helps to define how Arch compares to other projects which more highly priotize "minimalism" or "lightweightness" or whatever you want to call it (currently the idea is that "Minimal-size" is the most apt short description). [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 04:38, 8 September 2021 (UTC)<br />
<br />
::: As a specific example of defining what Archers mean by simple: An Archer might argue that the convenience and stability gained by having a package manager which is better at keeping track of all the moving components in the system and how they interrelate ultimately provides for a simpler overall experience which more than offsets the engineering complexity of it. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 04:46, 8 September 2021 (UTC)<br />
<br />
::: And a specific example of how that definition can help in shaping the future of the distro: I'm currently advocating for an automated install process which covers, at least, the most common use-cases outlined in the [[Installation_guide]]. The argument being around how the added complexity of having an automated process which better keeps track of all the moving components in the system and how they interrelate ultimately provides for a simpler overall experience which more than offsets the engineering complexity of it. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 05:10, 8 September 2021 (UTC)<br />
<br />
:::: I would like to see more actual ''comparisons'' to Arch, rather than merely listing features of other distributions. For example, Void Linux uses pull requests to accept packages into their repositories, while Arch has the AUR with user-submitted packages, which are then cherry-picked to the repositories. Alpine uses APKBUILD, which is very similar to PKGBUILD but is strictly limited to POSIX shell features, e.g. no arrays. And so on.<br />
<br />
:::::Those are great details to include! Please do. My draft only serves as a foundation. I'd like to see more detailed comparison too. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 22:55, 8 September 2021 (UTC)<br />
<br />
:::: Personally I would also skip Tiny Core Linux and Puppy Linux. You even admit to their limited relevance in the distro landscape. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 18:34, 8 September 2021 (UTC)<br />
<br />
::::: Yeah, I've noticed you feel strongly that distros included here should have broad relevance as basically being very general purpose or being generally ubiquitous to those familiar with Linux. I feel like there's some opportunity to cherry-pick a few less ubiquitous distros specifically for the purpose of highlighting implementations which stretch the boundaries of what people might typically do with Linux. For Arch, aiming to be incredibly versatile and fostering of regular tinkering and expansion of the idea of what you can achieve with your system, I feel like it's a worthwhile thing to point these out! For instance, Tiny Core I think gives a wow moment to a lot of people when they realize a whole functional graphical desktop can fit in 11MB, and that adding Wi-Fi and non-US keyboards adds a whole order of magnitude in size and complexity. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 23:02, 8 September 2021 (UTC)<br />
<br />
:::::: It's also a very poignant contrast! Arch is ''A simple, lightweight distribution'', but within the confines of being totally general-purpose. Tiny Core, by comparison, is '''''maximally''''' simple and lightweight as an absolute first priority. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 23:46, 8 September 2021 (UTC)<br />
<br />
=== Draft: Minimal-size ===<br />
<br />
These distributions range in capability from being focused on embedded systems deployment or niche purposes, to having overlap with the more typical general purpose distros listed above. The defining factor of this category is that one of the primary reasons for these distributions to exist is that they are made to have as small of a footprint, in terms of size and resource usage, as is possible for their intended purpose. This generally implies compromises which would not be seen with other, more general-purpose, distributions.<br />
<br />
These distributions can be as small as ~12 MiB on disk, and more typically the minimal install is between 100 MiB and 700 MiB. By contrast, Arch aims to be lightweight, but to serve as a more general purpose system has a base install closer to ~2 GiB, and needing ~512 MiB RAM.<br />
<br />
==== Alpine Linux ====<br />
<br />
* Is a security focused distribution first. Is developed with the expectation it will be deployed to embedded and network edge devices such as routers. The mix of embedded use and a desire to reduce the [https://www.cymune.com/blog-details/Attack-Surface-Reduction "attack surface"] (which comes from extraneous or overly-complex software) for high-value devices motivates making installations of Alpine very small.<br />
* A minimal install is ~130MiB on disk.<br />
* Userland binaries compiled with [[Wikipedia:Position-independent code|position-independent executables]], to limit available exploits.<br />
* Achieves very small size in part by foregoing the usual choice of [[GNU#Toolchain|glibc]], and instead uses [[C#Alternative_libc_implementations|musl libc]].<br />
* [[BusyBox]] based, also to reduce size and complexity.<br />
* Still strives to be a general purpose distribution, and covers a wide variety of potential uses. Lack of glibc can introduce [https://www.musl-libc.org/faq.html compatibility issues] for some applications.<br />
** Package coverage: Over [https://repology.org/repository/alpine_3_14 5000 core projects], and [https://repology.org/repository/alpine_edge over 7500] in edge.<br />
** Wide platform support: i686, x86_64, ARM (hf, v7, AArch64), ppc64le, s390x<br />
* [https://wiki.gentoo.org/wiki/Project:OpenRC OpenRC] for [[init]]<br />
* Started in 2005, with steadily growing adoption, particularly since about 2015. Is now the most prominent minimal-size distribution.<br />
<br />
==== Void Linux ====<br />
<br />
* Is a general-purpose distribution with a focus on being fast and as small as possible.<br />
* Minimal installs: 96MiB RAM, 600MiB disk (700 with glibc)<br />
* i686 and x86_64 support<br />
* Built around both musl and glibc.<br />
* [[Runit]] for [[init]] system (Arch uses [[systemd]] by default)<br />
* Using [https://github.com/void-linux/xbps xbps] package manager.<br />
** Over [https://repology.org/repository/void_x86_64 7000 packages], comparable size to OpenBSD Ports.<br />
<br />
==== Puppy Linux ====<br />
* Is an end-user, desktop-focused, portable-first distribution.<br />
** Boots into a [[ramdisk]], primary intent to boot quickly off a USB stick.<br />
* Small size to enable quick portable boot off USB<br />
** ~130MiB minimum on disk (Typical: i686 - 300MB, x86_64 - 600MB)<br />
* Maintains two main variants: One Ubuntu derived, the other Slackware (also Raspbian for [https://www.raspberrypi.org/ RasPi]/[[ARM]])<br />
* One of the oldest and most enduring of the minimalist distributions. Peak interest in 2008, has [https://entvibes.com/archwiki/Small%20Linux%20Distros%20-%20Google%20Trends%20-%202021-09-05%20134735.png faded in prominence since].<br />
<br />
==== Tiny Core Linux ====<br />
* Is an extremely small graphical Linux desktop<br />
** ~12 MiB on disk (with Wi-Fi and non-US keyboard support: ~106 MiB)<br />
* Achieves small size by cherry-picking some of the smallest tools available for each purpose:<br />
** [[BusyBox]], [https://www.irif.fr/~jch/software/kdrive.html Tiny X], [https://www.fltk.org/ Fltk], and [https://github.com/tinycorelinux/flwm Flwm]<br />
* Can be used as a portable OS, in similar manner to Puppy Linux<br />
* Is limited in scope. Monolithic package updated twice a year since 2009.<br />
** Repo browser not online. State of package repositories unclear.<br />
* Ports for: i686, x86_64, ARM, RasPi<br />
<br />
== Add NixOS Somewhere ==<br />
<br />
I think currently Arch and NixOS are the most interesting comparison out of everything. Arch has been known as, "Linux, with a nice package manager" NixOS is might be more, "A nice package manager, oh and Linux too; purely functional, btw." [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 14:07, 5 September 2021 (UTC)<br />
<br />
:[[Arch compared to other distributions#General]]? -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 14:48, 5 September 2021 (UTC)<br />
<br />
::Yep, sure. I'll start working up a draft. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 01:19, 6 September 2021 (UTC)<br />
<br />
:::This draft could still use some more direct comparisons to Arch.[[User:Einr|Einr]] ([[User talk:Einr|talk]]) 22:38, 8 September 2021 (UTC)<br />
<br />
=== NixOS ===<br />
<br />
* While most distributions ''include'' a package manager, NixOS is unique in that it is a package manager first and only secondarily a Linux distribution. [https://nixos.org/manual/nix/stable/#ch-about-nix Nix], the package management system, aims to be a subsystem which can be installed on practically ''any'' Linux distribution. The aim being to be a universally applicable dependency management system for developers.<br />
** Allows use as a continuous-integration environment.<br />
** Allows replacement of language-specific package managers.<br />
** Allows use of a single tool for all project build, machine configuration, and cloud deployment management.<br />
** Is a developer-centric OS.<br />
* Uses a purely functional package language, to avoid side-effects. The ultimate goal from this is to enable [https://reproducible-builds.org/ Reproducible Builds].<br />
** Making [https://discourse.nixos.org/t/nixos-unstable-s-iso-minimal-x86-64-linux-is-100-reproducible/13723 progress] in this.<br />
** This is a major security consideration for any software available in binary form.<br />
** Allows truly atomic changes, which are easily rolled back, for most system management operations. The aim is both for stability and to encourage tinkering, similar to Archer mentality.<br />
*** Arch, comparatively, is not designed around this notion. However, it is versatile and with the right selection of filesystem and supporting software can approach a similar level of reversibility. The snapshotting functionality of [[Btrfs#Snapshots|btrfs]], along with judicious configuration of software like [[Synchronization_and_backup_programs#File-based_increments|TimeShift]] can allow most of this benefit.<br />
* Has one of the largest, most up to date, package ecosystems in the Linux world; comparable to Arch, if AUR is included.<br />
** A core strategic project focus is on increasing and improving the package coverage, functional status, and up-to-date-ness. Semi-annual [https://nixos.org/blog/announcements.html#21.05 releases] have a release manager who actively tracks this and doles out praise and recognition for contributing.<br />
<br />
== Add particularly interesting note about NetBSD ==<br />
<br />
While writing up the content above about minimal distros and researching and filling in their platform support I threw in the note in the section below about NetBSD.<br />
<br />
This was just [https://wiki.archlinux.org/index.php?title=Arch_compared_to_other_distributions&type=revision&diff=694206&oldid=694205 reverted].<br />
The justification being: "remove the one detail about one specific BSD variant - not related to Arch, there is no explicit list of BSDs and everything can be found on the linked Wikipedia page"<br />
<br />
This justification doesn't stand up for several reasons:<br />
# This page is littered with references to platform support.<br />
# Arch is notable for only supporting x86_64. People are likely to specifically be looking here for platform support contrasts.<br />
# The Wikipedia page does mention the portability-focused design, but does not specifically call out that NetBSD is ''the'' portable OS as far as the *NIX world is concerned.<br />
<br />
Please only revert content when there's a ''very'' clear and widely acceptable reason not to include it. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 07:37, 5 September 2021 (UTC)<br />
<br />
:The page used to have a detailed list of BSDs. That quickly turned into an ad board. [https://wiki.archlinux.org/index.php?title=Arch_compared_to_other_distributions&oldid=418996#The_*BSDs] So we have no interest in having anything more than what the page has now. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 12:51, 5 September 2021 (UTC)<br />
<br />
::Perhaps then a quick one-line summary of each, and an ongoing policy that this isn't expanded further. Proposed content below. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 05:06, 6 September 2021 (UTC)<br />
<br />
:::The currently proposed content is missing any comparison with Arch, so it is out of this page's scope. Providing quick summaries of 3 BSDs is pointless, they can be found elsewhere. This page is about giving comparisons (with Arch!), not summaries. — [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 20:32, 7 September 2021 (UTC)<br />
<br />
::::Agreed! I thought the NetBSD note about being most-portable was a poignant self-evident contrast to Arch only supporting one platform, which is why I wanted to include that one specifically. If the choice is between none and all of the well known ones, I'd rather include all though. Here's a quick whack at a comparison. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 22:47, 8 September 2021 (UTC)<br />
<br />
=== Reverted content ===<br />
[Ed: This was in the BSDs section]<br />
* NetBSD is notable for it's portability-focused design. It runs on [https://www.netbsd.org/ports/ more platforms] than possibly any other OS.<br />
<br />
=== Proposed content ===<br />
* As in the Linux world, there are many BSD derivatives. The top three are summarized below.<br />
** FreeBSD - The biggest. Tries to be everything. Focused on SMP server use and implements fine-grained locking to improve scalability. Arch is also focused on being very general-purpose, and the Linux kernel is arguably the best refined kernel for SMP scalability in the open source world currently.<br />
** OpenBSD - Security-centric. Absolute focus on ongoing code audits. Arch tries to maintain security by keeping the core distribution tightly controlled through highly trusted users and rigorous review, but doesn't centrally focus on security as the main goal of the release.<br />
** NetBSD - Possibly the most portable OS. Runs on [https://www.netbsd.org/ports/ an extensive variety of platforms]. Arch instead only supports x86_64, in order to provide focus on the core use-case: contemporary desktop, mobile, and server.<br />
<br />
== Add corpo distros ==<br />
<br />
:What better contrast is there to Arch than the commercial server distros? Basically the ossified antithesis of rolling-release. RHEL, SLES... just a short summary of how they're keeping old kernels on life support. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 06:24, 6 September 2021 (UTC)<br />
<br />
:Just throwing up a quick draft. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 06:38, 6 September 2021 (UTC)<br />
<br />
::I don't think we should promote/advertise commercial distributions by mentioning them here. -- [[User:nl6720|nl6720]] ([[User talk:nl6720|talk]]) 07:02, 6 September 2021 (UTC)<br />
<br />
:::Part of me agrees. Most people seem to agree though that RedHat and SUSE have been fairly responsible and among the best of the corporate actors in the open source world. Both of these distros remain fully open source, and only support contracts are sold. Also, what I've written hardly reads as an endorsement. I'm adding a note now to drive the philosophical contrast, which is what this section is really about. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 23:55, 6 September 2021 (UTC)<br />
<br />
:::As a further note, I'm actively contributing these comparisons to help promote a dialog on what Arch stands for and how it stands out. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 00:04, 7 September 2021 (UTC)<br />
<br />
:::Playing devil's advocate (on ossified old-kernel life support, vs. constantly pushing everything to be up to date): A corporate CTO might argue that, in their current environment, they are dependent upon software which, due to it's niche "vertical" nature cannot be so actively kept up to date or perhaps exists in a lab or high-volume manufacturing environment which they must prioritize being as frozen as possible. They might point to the difficulty they experience currently in even completing a two-year-long migration every decade as they must receive buy-in from many silo'ed global business groups with their own specialty needs across dozens of global datacenters housing tens of thousands of servers. How, possibly, could they expect to migrate to rolling release? A CEO who insists that they investigate the possibility may have a team formed, with options investigated. Requests across the IT department are put out for views from developers and admins and internal customer-group representatives on the prospect. Sysadmins and performance engineers point to the massive improvements to Linux kernel observability which are only just reaching maturity in the latest kernels, begging and hoping and dreaming that they be able to use them across the whole landscape. Manufacturing leads respond bluntly, "Hell will freeze over before you touch our systems. We're still secretly hiding SunOS systems from you (oh did I say that out loud?)."<br />
<br />
::::An optimistic outcome: A compromise is formed. Rolling-release is allowed for a new internal-cloud, and new bare-metal installations must thoroughly justify LTS installs. Actually, you can just roll whatever ISO you want (with some usergroup gating and a bit of IT oversight)! All business groups are expected then to increasingly justify having old-kernel environments, which are further isolated. The CTO remembers to tip-toe around manufacturing (they found a possum in one of those SunOS servers, and no one is sure if it was living there already...). RedHat and SUSE catch wind of and encourage this trend and offer rolling release enterprise-commercial distros, allowing further re-allocation of engineering headcount towards new tech and ongoing security and stability audits; everyone wins. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 00:44, 7 September 2021 (UTC)<br />
<br />
:::::I don't know about those corporate details you mention. But Fedora and openSUSE, the underpinnings for RHEL and SLES respectively, are already mentioned on this page. As such, the main distinction points for these distros are already listed. openSUSE Leap is even 100% binary compatible to SLES nowadays. [https://www.suse.com/c/introducing-suse-linux-enterprise-15-sp3/] -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 18:39, 8 September 2021 (UTC)<br />
<br />
::::::Yeah, that's why I thought it best to only include a bare-bones summary of the primary detail which provides such a sharp contrast to the rolling release model of Arch here. As you've said, the other more detailed contrasts to Arch are better highlighted in the comparisons to the community versions of these distros. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 22:33, 8 September 2021 (UTC)<br />
<br />
=== Enterprise-commercial ===<br />
<br />
These distributions are the commercial arms of the corporate giants in the Linux world: RedHat and SUSE. The companies play a large part in providing to the kernel and core libraries, and these distributions are their support-provided offerings to corporations. Large corporations expect very long term support for in-house datacenter server installations, and that has led to Red Hat Enterprise Linux and SUSE Linux Enterprise Server having decade-long lifecycles where very old kernels and libraries are maintained with security packages and occasional feature backports. This is effectively the antithesis of the rolling-release model, as championed by Arch; Archers tend to believe that the most stable and secure system is achieved by maintaining a laser focus on keeping up to date.<br />
<br />
== Swap order of CRUX and LFS ==<br />
<br />
I know that CRUX has a special meaning for Arch, however LFS is a special case, as it not really a distribution, but more or less the starting point for who wants to create a distribution. Thus I think LFS should be the first of the list, then CRUX, then the rest. What do you people think? --[[User:Grufo|Grufo]] <sup>[ [[Special:Contributions/Grufo|contribs]] | [[User_talk:Grufo|talk]] ]</sup> 18:18, 29 October 2021 (UTC)<br />
<br />
:You could argue for it both ways (personally I prefer CRUX at top). I doubt it matters enough to change the article, though. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 13:29, 30 October 2021 (UTC)<br />
<br />
:: Yes, of course, it is a totally unimportant detail. I just noticed while reading the article that it feels strange to have a list with a distribution, a guide to how to create a distribution, a distribution, a distribution, a distribution, etc. But probably this is really subjective. --[[User:Grufo|Grufo]] <sup>[ [[Special:Contributions/Grufo|contribs]] | [[User_talk:Grufo|talk]] ]</sup> 08:52, 1 November 2021 (UTC)<br />
<br />
:::Instead, let's bring LFS to the bottom. That way, we can keep the actual distributions listed after each other, have the special case "isolated" from the rest while keeping CRUX at the top since it has a special meaning for Arch. [[User:Cont999|Cont999]] ([[User talk:Cont999|talk]]) 19:13, 7 October 2022 (UTC)<br />
<br />
::::This makes even less sense to me. It is even noted that 'Judd Vinet built Arch from scratch, and then wrote pacman in C. Historically, Arch was sometimes humorously described simply as "Linux, with a nice package manager."'. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 23:56, 7 October 2022 (UTC)</div>Malcontenthttps://wiki.archlinux.org/index.php?title=Talk:Arch_compared_to_other_distributions&diff=773283Talk:Arch compared to other distributions2023-03-20T09:48:07Z<p>Malcontent: Gentoo section is unfair (biased towards Arch)</p>
<hr />
<div>== Gentoo/Funtoo Linux ==<br />
<br />
"Gentoo's official package and system management tools tend to be rather more complex and "powerful" than those provided by Arch"<br />
<br />
Is there a reason why powerful is spelled with quotes in this example? If the features of portage are being questioned then I want to see real arguments against. Spelling powerful between quotes makes it seem like it was written by biased Arch Linux users.<br />
<br />
Please drop the quotes or provide real arguments because portage is miles ahead of pacman in many ways.<br />
<br />
== Add Alpine, Void ==<br />
<br />
Void and Alpine are reasonably popular by now. One of their features is a focus on "minimal size", so a subsection could be added to the article accordingly. There's some ambiguity with the [[Arch compared to other distributions#General]] section - both distributions are general purpose, and Debian/Ubuntu also focuses on "minimal size" to some extent (package splitting). Therefore one could either propose a different section name, or alternatively include Void/Alpine in [[Arch compared to other distributions#General]].<br />
<br />
Either way we should think of a write-up and probably include these distributions in the article. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 14:22, 3 September 2021 (UTC)<br />
<br />
:I'll start working on this now. Will likely include Puppy Linux and Tiny Core Linux as well, due to their fit to this category and mix of prominence and endurance. See [https://entvibes.com/archwiki/Small%20Linux%20Distros%20-%20Google%20Trends%20-%202021-09-05%20134735.png here]. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 03:57, 5 September 2021 (UTC)<br />
<br />
Why was this moved to draft state? I was basically done with it. Feel free to add to it, but it's in a comparable state now to the other lists. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 07:40, 5 September 2021 (UTC)<br />
<br />
:We are not done reviewing it. — [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 07:42, 5 September 2021 (UTC)<br />
<br />
:: Can we nuke all this stuff? It screams of content that requires a lot of upkeep (package count, etc), general advertising and a tremendous amount of fluff. Arch ethos is to keep it simple. None of this is remotely simple.<br />
:: [[User:Grawlinson|Grawlinson]] ([[User talk:Grawlinson|talk]]) 01:42, 8 September 2021 (UTC)<br />
<br />
::: I included info about package coverage, in rough approximations, because there was some open consideration of what overlap these have with more general-purpose distributions. It's not essential, but has already been researched and is of relevance to defining the class. Simply removing the content if it proves out of date without a maintainer would be understandable. These are also just comparisons to Arch. LFS is arguably "simpler" than Arch and distributions which are considerably smaller than Arch are also, by necessity, simpler than Arch... Arch isn't all about simplicity. Even the decision to break away from CRUX was over the concern of added complexity created by the envisioned metadata-included creation of pacman. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 03:28, 8 September 2021 (UTC)<br />
<br />
::: Also, I agree and appreciate that simplicity is in the ethos of Arch. Not trying to contest that at all. Just pointing out that it does necessitate some definition. For instance, I suggested "lightweight" as an alternative name for what is now proposed as "minimal-size". This was criticized as, "meaningless." Arch is trademarked as "A simple, lightweight distribution." Certainly, we don't want to face the same criticism from the outside. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 04:29, 8 September 2021 (UTC)<br />
<br />
::: That, "defining what Arch means by simple and lightweight," is part of where I see the value in this page. It's a concrete comparison of the tradeoffs Arch makes vs other projects so that the casual outside observer can clearly see how Archers prioritize simplicity and lightness vs other goals. So minimal-size is a category that specifically helps to define how Arch compares to other projects which more highly priotize "minimalism" or "lightweightness" or whatever you want to call it (currently the idea is that "Minimal-size" is the most apt short description). [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 04:38, 8 September 2021 (UTC)<br />
<br />
::: As a specific example of defining what Archers mean by simple: An Archer might argue that the convenience and stability gained by having a package manager which is better at keeping track of all the moving components in the system and how they interrelate ultimately provides for a simpler overall experience which more than offsets the engineering complexity of it. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 04:46, 8 September 2021 (UTC)<br />
<br />
::: And a specific example of how that definition can help in shaping the future of the distro: I'm currently advocating for an automated install process which covers, at least, the most common use-cases outlined in the [[Installation_guide]]. The argument being around how the added complexity of having an automated process which better keeps track of all the moving components in the system and how they interrelate ultimately provides for a simpler overall experience which more than offsets the engineering complexity of it. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 05:10, 8 September 2021 (UTC)<br />
<br />
:::: I would like to see more actual ''comparisons'' to Arch, rather than merely listing features of other distributions. For example, Void Linux uses pull requests to accept packages into their repositories, while Arch has the AUR with user-submitted packages, which are then cherry-picked to the repositories. Alpine uses APKBUILD, which is very similar to PKGBUILD but is strictly limited to POSIX shell features, e.g. no arrays. And so on.<br />
<br />
:::::Those are great details to include! Please do. My draft only serves as a foundation. I'd like to see more detailed comparison too. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 22:55, 8 September 2021 (UTC)<br />
<br />
:::: Personally I would also skip Tiny Core Linux and Puppy Linux. You even admit to their limited relevance in the distro landscape. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 18:34, 8 September 2021 (UTC)<br />
<br />
::::: Yeah, I've noticed you feel strongly that distros included here should have broad relevance as basically being very general purpose or being generally ubiquitous to those familiar with Linux. I feel like there's some opportunity to cherry-pick a few less ubiquitous distros specifically for the purpose of highlighting implementations which stretch the boundaries of what people might typically do with Linux. For Arch, aiming to be incredibly versatile and fostering of regular tinkering and expansion of the idea of what you can achieve with your system, I feel like it's a worthwhile thing to point these out! For instance, Tiny Core I think gives a wow moment to a lot of people when they realize a whole functional graphical desktop can fit in 11MB, and that adding Wi-Fi and non-US keyboards adds a whole order of magnitude in size and complexity. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 23:02, 8 September 2021 (UTC)<br />
<br />
:::::: It's also a very poignant contrast! Arch is ''A simple, lightweight distribution'', but within the confines of being totally general-purpose. Tiny Core, by comparison, is '''''maximally''''' simple and lightweight as an absolute first priority. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 23:46, 8 September 2021 (UTC)<br />
<br />
=== Draft: Minimal-size ===<br />
<br />
These distributions range in capability from being focused on embedded systems deployment or niche purposes, to having overlap with the more typical general purpose distros listed above. The defining factor of this category is that one of the primary reasons for these distributions to exist is that they are made to have as small of a footprint, in terms of size and resource usage, as is possible for their intended purpose. This generally implies compromises which would not be seen with other, more general-purpose, distributions.<br />
<br />
These distributions can be as small as ~12 MiB on disk, and more typically the minimal install is between 100 MiB and 700 MiB. By contrast, Arch aims to be lightweight, but to serve as a more general purpose system has a base install closer to ~2 GiB, and needing ~512 MiB RAM.<br />
<br />
==== Alpine Linux ====<br />
<br />
* Is a security focused distribution first. Is developed with the expectation it will be deployed to embedded and network edge devices such as routers. The mix of embedded use and a desire to reduce the [https://www.cymune.com/blog-details/Attack-Surface-Reduction "attack surface"] (which comes from extraneous or overly-complex software) for high-value devices motivates making installations of Alpine very small.<br />
* A minimal install is ~130MiB on disk.<br />
* Userland binaries compiled with [[Wikipedia:Position-independent code|position-independent executables]], to limit available exploits.<br />
* Achieves very small size in part by foregoing the usual choice of [[GNU#Toolchain|glibc]], and instead uses [[C#Alternative_libc_implementations|musl libc]].<br />
* [[BusyBox]] based, also to reduce size and complexity.<br />
* Still strives to be a general purpose distribution, and covers a wide variety of potential uses. Lack of glibc can introduce [https://www.musl-libc.org/faq.html compatibility issues] for some applications.<br />
** Package coverage: Over [https://repology.org/repository/alpine_3_14 5000 core projects], and [https://repology.org/repository/alpine_edge over 7500] in edge.<br />
** Wide platform support: i686, x86_64, ARM (hf, v7, AArch64), ppc64le, s390x<br />
* [https://wiki.gentoo.org/wiki/Project:OpenRC OpenRC] for [[init]]<br />
* Started in 2005, with steadily growing adoption, particularly since about 2015. Is now the most prominent minimal-size distribution.<br />
<br />
==== Void Linux ====<br />
<br />
* Is a general-purpose distribution with a focus on being fast and as small as possible.<br />
* Minimal installs: 96MiB RAM, 600MiB disk (700 with glibc)<br />
* i686 and x86_64 support<br />
* Built around both musl and glibc.<br />
* [[Runit]] for [[init]] system (Arch uses [[systemd]] by default)<br />
* Using [https://github.com/void-linux/xbps xbps] package manager.<br />
** Over [https://repology.org/repository/void_x86_64 7000 packages], comparable size to OpenBSD Ports.<br />
<br />
==== Puppy Linux ====<br />
* Is an end-user, desktop-focused, portable-first distribution.<br />
** Boots into a [[ramdisk]], primary intent to boot quickly off a USB stick.<br />
* Small size to enable quick portable boot off USB<br />
** ~130MiB minimum on disk (Typical: i686 - 300MB, x86_64 - 600MB)<br />
* Maintains two main variants: One Ubuntu derived, the other Slackware (also Raspbian for [https://www.raspberrypi.org/ RasPi]/[[ARM]])<br />
* One of the oldest and most enduring of the minimalist distributions. Peak interest in 2008, has [https://entvibes.com/archwiki/Small%20Linux%20Distros%20-%20Google%20Trends%20-%202021-09-05%20134735.png faded in prominence since].<br />
<br />
==== Tiny Core Linux ====<br />
* Is an extremely small graphical Linux desktop<br />
** ~12 MiB on disk (with Wi-Fi and non-US keyboard support: ~106 MiB)<br />
* Achieves small size by cherry-picking some of the smallest tools available for each purpose:<br />
** [[BusyBox]], [https://www.irif.fr/~jch/software/kdrive.html Tiny X], [https://www.fltk.org/ Fltk], and [https://github.com/tinycorelinux/flwm Flwm]<br />
* Can be used as a portable OS, in similar manner to Puppy Linux<br />
* Is limited in scope. Monolithic package updated twice a year since 2009.<br />
** Repo browser not online. State of package repositories unclear.<br />
* Ports for: i686, x86_64, ARM, RasPi<br />
<br />
== Add NixOS Somewhere ==<br />
<br />
I think currently Arch and NixOS are the most interesting comparison out of everything. Arch has been known as, "Linux, with a nice package manager" NixOS is might be more, "A nice package manager, oh and Linux too; purely functional, btw." [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 14:07, 5 September 2021 (UTC)<br />
<br />
:[[Arch compared to other distributions#General]]? -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 14:48, 5 September 2021 (UTC)<br />
<br />
::Yep, sure. I'll start working up a draft. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 01:19, 6 September 2021 (UTC)<br />
<br />
:::This draft could still use some more direct comparisons to Arch.[[User:Einr|Einr]] ([[User talk:Einr|talk]]) 22:38, 8 September 2021 (UTC)<br />
<br />
=== NixOS ===<br />
<br />
* While most distributions ''include'' a package manager, NixOS is unique in that it is a package manager first and only secondarily a Linux distribution. [https://nixos.org/manual/nix/stable/#ch-about-nix Nix], the package management system, aims to be a subsystem which can be installed on practically ''any'' Linux distribution. The aim being to be a universally applicable dependency management system for developers.<br />
** Allows use as a continuous-integration environment.<br />
** Allows replacement of language-specific package managers.<br />
** Allows use of a single tool for all project build, machine configuration, and cloud deployment management.<br />
** Is a developer-centric OS.<br />
* Uses a purely functional package language, to avoid side-effects. The ultimate goal from this is to enable [https://reproducible-builds.org/ Reproducible Builds].<br />
** Making [https://discourse.nixos.org/t/nixos-unstable-s-iso-minimal-x86-64-linux-is-100-reproducible/13723 progress] in this.<br />
** This is a major security consideration for any software available in binary form.<br />
** Allows truly atomic changes, which are easily rolled back, for most system management operations. The aim is both for stability and to encourage tinkering, similar to Archer mentality.<br />
*** Arch, comparatively, is not designed around this notion. However, it is versatile and with the right selection of filesystem and supporting software can approach a similar level of reversibility. The snapshotting functionality of [[Btrfs#Snapshots|btrfs]], along with judicious configuration of software like [[Synchronization_and_backup_programs#File-based_increments|TimeShift]] can allow most of this benefit.<br />
* Has one of the largest, most up to date, package ecosystems in the Linux world; comparable to Arch, if AUR is included.<br />
** A core strategic project focus is on increasing and improving the package coverage, functional status, and up-to-date-ness. Semi-annual [https://nixos.org/blog/announcements.html#21.05 releases] have a release manager who actively tracks this and doles out praise and recognition for contributing.<br />
<br />
== Add particularly interesting note about NetBSD ==<br />
<br />
While writing up the content above about minimal distros and researching and filling in their platform support I threw in the note in the section below about NetBSD.<br />
<br />
This was just [https://wiki.archlinux.org/index.php?title=Arch_compared_to_other_distributions&type=revision&diff=694206&oldid=694205 reverted].<br />
The justification being: "remove the one detail about one specific BSD variant - not related to Arch, there is no explicit list of BSDs and everything can be found on the linked Wikipedia page"<br />
<br />
This justification doesn't stand up for several reasons:<br />
# This page is littered with references to platform support.<br />
# Arch is notable for only supporting x86_64. People are likely to specifically be looking here for platform support contrasts.<br />
# The Wikipedia page does mention the portability-focused design, but does not specifically call out that NetBSD is ''the'' portable OS as far as the *NIX world is concerned.<br />
<br />
Please only revert content when there's a ''very'' clear and widely acceptable reason not to include it. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 07:37, 5 September 2021 (UTC)<br />
<br />
:The page used to have a detailed list of BSDs. That quickly turned into an ad board. [https://wiki.archlinux.org/index.php?title=Arch_compared_to_other_distributions&oldid=418996#The_*BSDs] So we have no interest in having anything more than what the page has now. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 12:51, 5 September 2021 (UTC)<br />
<br />
::Perhaps then a quick one-line summary of each, and an ongoing policy that this isn't expanded further. Proposed content below. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 05:06, 6 September 2021 (UTC)<br />
<br />
:::The currently proposed content is missing any comparison with Arch, so it is out of this page's scope. Providing quick summaries of 3 BSDs is pointless, they can be found elsewhere. This page is about giving comparisons (with Arch!), not summaries. — [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 20:32, 7 September 2021 (UTC)<br />
<br />
::::Agreed! I thought the NetBSD note about being most-portable was a poignant self-evident contrast to Arch only supporting one platform, which is why I wanted to include that one specifically. If the choice is between none and all of the well known ones, I'd rather include all though. Here's a quick whack at a comparison. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 22:47, 8 September 2021 (UTC)<br />
<br />
=== Reverted content ===<br />
[Ed: This was in the BSDs section]<br />
* NetBSD is notable for it's portability-focused design. It runs on [https://www.netbsd.org/ports/ more platforms] than possibly any other OS.<br />
<br />
=== Proposed content ===<br />
* As in the Linux world, there are many BSD derivatives. The top three are summarized below.<br />
** FreeBSD - The biggest. Tries to be everything. Focused on SMP server use and implements fine-grained locking to improve scalability. Arch is also focused on being very general-purpose, and the Linux kernel is arguably the best refined kernel for SMP scalability in the open source world currently.<br />
** OpenBSD - Security-centric. Absolute focus on ongoing code audits. Arch tries to maintain security by keeping the core distribution tightly controlled through highly trusted users and rigorous review, but doesn't centrally focus on security as the main goal of the release.<br />
** NetBSD - Possibly the most portable OS. Runs on [https://www.netbsd.org/ports/ an extensive variety of platforms]. Arch instead only supports x86_64, in order to provide focus on the core use-case: contemporary desktop, mobile, and server.<br />
<br />
== Add corpo distros ==<br />
<br />
:What better contrast is there to Arch than the commercial server distros? Basically the ossified antithesis of rolling-release. RHEL, SLES... just a short summary of how they're keeping old kernels on life support. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 06:24, 6 September 2021 (UTC)<br />
<br />
:Just throwing up a quick draft. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 06:38, 6 September 2021 (UTC)<br />
<br />
::I don't think we should promote/advertise commercial distributions by mentioning them here. -- [[User:nl6720|nl6720]] ([[User talk:nl6720|talk]]) 07:02, 6 September 2021 (UTC)<br />
<br />
:::Part of me agrees. Most people seem to agree though that RedHat and SUSE have been fairly responsible and among the best of the corporate actors in the open source world. Both of these distros remain fully open source, and only support contracts are sold. Also, what I've written hardly reads as an endorsement. I'm adding a note now to drive the philosophical contrast, which is what this section is really about. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 23:55, 6 September 2021 (UTC)<br />
<br />
:::As a further note, I'm actively contributing these comparisons to help promote a dialog on what Arch stands for and how it stands out. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 00:04, 7 September 2021 (UTC)<br />
<br />
:::Playing devil's advocate (on ossified old-kernel life support, vs. constantly pushing everything to be up to date): A corporate CTO might argue that, in their current environment, they are dependent upon software which, due to it's niche "vertical" nature cannot be so actively kept up to date or perhaps exists in a lab or high-volume manufacturing environment which they must prioritize being as frozen as possible. They might point to the difficulty they experience currently in even completing a two-year-long migration every decade as they must receive buy-in from many silo'ed global business groups with their own specialty needs across dozens of global datacenters housing tens of thousands of servers. How, possibly, could they expect to migrate to rolling release? A CEO who insists that they investigate the possibility may have a team formed, with options investigated. Requests across the IT department are put out for views from developers and admins and internal customer-group representatives on the prospect. Sysadmins and performance engineers point to the massive improvements to Linux kernel observability which are only just reaching maturity in the latest kernels, begging and hoping and dreaming that they be able to use them across the whole landscape. Manufacturing leads respond bluntly, "Hell will freeze over before you touch our systems. We're still secretly hiding SunOS systems from you (oh did I say that out loud?)."<br />
<br />
::::An optimistic outcome: A compromise is formed. Rolling-release is allowed for a new internal-cloud, and new bare-metal installations must thoroughly justify LTS installs. Actually, you can just roll whatever ISO you want (with some usergroup gating and a bit of IT oversight)! All business groups are expected then to increasingly justify having old-kernel environments, which are further isolated. The CTO remembers to tip-toe around manufacturing (they found a possum in one of those SunOS servers, and no one is sure if it was living there already...). RedHat and SUSE catch wind of and encourage this trend and offer rolling release enterprise-commercial distros, allowing further re-allocation of engineering headcount towards new tech and ongoing security and stability audits; everyone wins. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 00:44, 7 September 2021 (UTC)<br />
<br />
:::::I don't know about those corporate details you mention. But Fedora and openSUSE, the underpinnings for RHEL and SLES respectively, are already mentioned on this page. As such, the main distinction points for these distros are already listed. openSUSE Leap is even 100% binary compatible to SLES nowadays. [https://www.suse.com/c/introducing-suse-linux-enterprise-15-sp3/] -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 18:39, 8 September 2021 (UTC)<br />
<br />
::::::Yeah, that's why I thought it best to only include a bare-bones summary of the primary detail which provides such a sharp contrast to the rolling release model of Arch here. As you've said, the other more detailed contrasts to Arch are better highlighted in the comparisons to the community versions of these distros. [[User:Einr|Einr]] ([[User talk:Einr|talk]]) 22:33, 8 September 2021 (UTC)<br />
<br />
=== Enterprise-commercial ===<br />
<br />
These distributions are the commercial arms of the corporate giants in the Linux world: RedHat and SUSE. The companies play a large part in providing to the kernel and core libraries, and these distributions are their support-provided offerings to corporations. Large corporations expect very long term support for in-house datacenter server installations, and that has led to Red Hat Enterprise Linux and SUSE Linux Enterprise Server having decade-long lifecycles where very old kernels and libraries are maintained with security packages and occasional feature backports. This is effectively the antithesis of the rolling-release model, as championed by Arch; Archers tend to believe that the most stable and secure system is achieved by maintaining a laser focus on keeping up to date.<br />
<br />
== Swap order of CRUX and LFS ==<br />
<br />
I know that CRUX has a special meaning for Arch, however LFS is a special case, as it not really a distribution, but more or less the starting point for who wants to create a distribution. Thus I think LFS should be the first of the list, then CRUX, then the rest. What do you people think? --[[User:Grufo|Grufo]] <sup>[ [[Special:Contributions/Grufo|contribs]] | [[User_talk:Grufo|talk]] ]</sup> 18:18, 29 October 2021 (UTC)<br />
<br />
:You could argue for it both ways (personally I prefer CRUX at top). I doubt it matters enough to change the article, though. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 13:29, 30 October 2021 (UTC)<br />
<br />
:: Yes, of course, it is a totally unimportant detail. I just noticed while reading the article that it feels strange to have a list with a distribution, a guide to how to create a distribution, a distribution, a distribution, a distribution, etc. But probably this is really subjective. --[[User:Grufo|Grufo]] <sup>[ [[Special:Contributions/Grufo|contribs]] | [[User_talk:Grufo|talk]] ]</sup> 08:52, 1 November 2021 (UTC)<br />
<br />
:::Instead, let's bring LFS to the bottom. That way, we can keep the actual distributions listed after each other, have the special case "isolated" from the rest while keeping CRUX at the top since it has a special meaning for Arch. [[User:Cont999|Cont999]] ([[User talk:Cont999|talk]]) 19:13, 7 October 2022 (UTC)<br />
<br />
::::This makes even less sense to me. It is even noted that 'Judd Vinet built Arch from scratch, and then wrote pacman in C. Historically, Arch was sometimes humorously described simply as "Linux, with a nice package manager."'. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 23:56, 7 October 2022 (UTC)</div>Malcontenthttps://wiki.archlinux.org/index.php?title=Talk:Bitcoin&diff=699229Talk:Bitcoin2021-10-15T17:21:28Z<p>Malcontent: /* Full node (Blockchain size) */</p>
<hr />
<div>== Full node (Blockchain size) ==<br />
<br />
Please update the size to 400 GB (as of October 2021). Thanks. -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 16:04, 7 October 2021 (UTC)</div>Malcontenthttps://wiki.archlinux.org/index.php?title=Talk:Bitcoin&diff=698519Talk:Bitcoin2021-10-07T16:04:27Z<p>Malcontent: Suggest new blockchain size</p>
<hr />
<div>== Full node (Blockchain size) ==<br />
<br />
<s>Please update the size to 350 GB (as of October 2020). Thanks.</s> -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 00:01, 12 October 2020 (UTC)<br />
<br />
Please update the size to 400 GB (as of October 2021). Thanks. -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 16:04, 7 October 2021 (UTC)</div>Malcontenthttps://wiki.archlinux.org/index.php?title=Talk:Bitcoin&diff=637718Talk:Bitcoin2020-10-12T00:01:43Z<p>Malcontent: Blockchain size needs update</p>
<hr />
<div>== Full node (Blockchain size) ==<br />
<br />
Please update the size to 350 GB (as of October 2020). Thanks. -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 00:01, 12 October 2020 (UTC)</div>Malcontenthttps://wiki.archlinux.org/index.php?title=QEMU&diff=635691QEMU2020-09-18T14:19:03Z<p>Malcontent: English wording fix</p>
<hr />
<div>[[Category:Emulation]]<br />
[[Category:Hypervisors]]<br />
[[de:Qemu]]<br />
[[es:QEMU]]<br />
[[fr:Qemu]]<br />
[[ja:QEMU]]<br />
[[zh-hans:QEMU]]<br />
[[zh-hant:QEMU]]<br />
{{Related articles start}}<br />
{{Related|:Category:Hypervisors}}<br />
{{Related|Libvirt}}<br />
{{Related|QEMU/Guest graphics acceleration}}<br />
{{Related|PCI passthrough via OVMF}}<br />
{{Related articles end}}<br />
<br />
According to the [http://wiki.qemu.org/Main_Page QEMU about page], "QEMU is a generic and open source machine emulator and virtualizer."<br />
<br />
When used as a machine emulator, QEMU can run OSes and programs made for one machine (e.g. an ARM board) on a different machine (e.g. your x86 PC). By using dynamic translation, it achieves very good performance.<br />
<br />
QEMU can use other hypervisors like [[Xen]] or [[KVM]] to use CPU extensions ([[Wikipedia:Hardware-assisted virtualization|HVM]]) for virtualization. When used as a virtualizer, QEMU achieves near native performances by executing the guest code directly on the host CPU.<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|qemu}} package (or {{Pkg|qemu-headless}} for the version without GUI) and below optional packages for your needs:<br />
<br />
* {{Pkg|qemu-arch-extra}} - extra architectures support<br />
* {{Pkg|qemu-block-gluster}} - [[Glusterfs]] block support<br />
* {{Pkg|qemu-block-iscsi}} - [[iSCSI]] block support<br />
* {{Pkg|qemu-block-rbd}} - RBD block support <br />
* {{Pkg|samba}} - [[Samba|SMB/CIFS]] server support<br />
<br />
Alternatively, {{AUR|qemu-user-static}} exists as a usermode and static variant.<br />
<br />
=== QEMU variants ===<br />
<br />
QEMU is offered in several variants suited for different use cases.<br />
<br />
As a first classification, QEMU is offered in full-system and usermode emulation modes:<br />
<br />
; Full-system emulation<br />
: In this mode, QEMU emulates a full system, including one or several processors and various peripherals. It is more accurate but slower, and does not require the emulated OS to be Linux.<br />
: QEMU commands for full-system emulation are named {{ic|qemu-system-''target_architecture''}}, e.g. {{ic|qemu-system-x86_64}} for emulating intel 64-bit CPUs, {{ic|qemu-system-i386}} for intel 32 bits CPUs, {{ic|qemu-system-arm}} for ARM (32 bits), {{ic|qemu-system-aarch64}} for ARM64, etc.<br />
: If the target architecture matches the host CPU, this mode may still benefit from a significant speedup by using a hypervisor like [[#Enabling KVM|KVM]] or Xen.<br />
; [https://www.qemu.org/docs/master/user/main.html Usermode emulation]: In this mode, QEMU is able to invoke a Linux executable compiled for a (potentially) different architecture by leveraging the host system resources. There may be compatibility issues, e.g. some features may not be implemented, dynamically linked executables will not work out of the box (see [[#Chrooting into arm/arm64 environment from x86_64|the section below]] to address this) and only Linux is supported (although [https://wiki.winehq.org/Emulation Wine may be used] for running Windows executables).<br />
: QEMU commands for usermode emulation are named {{ic|qemu-''target_architecture''}}, e.g. {{ic|qemu-x86_64}} for emulating intel 64-bit CPUs.<br />
<br />
QEMU is offered in dynamically-linked and statically-linked variants:<br />
<br />
; Dynamically-linked (default): {{ic|qemu-*}} commands depend on the host OS libraries, so executables are smaller.<br />
; Statically-linked: {{ic|qemu-*}} commands can be copied to any Linux system with the same architecture.<br />
<br />
In the case of Arch Linux, full-system emulation is offered as:<br />
<br />
; Non-headless (default): This variant enables GUI features that require additional dependencies (like SDL or GTK).<br />
; Headless: This is a slimmer variant that does not require GUI (this is suitable e.g. for servers).<br />
<br />
Note that headless and non-headless versions install commands with the same name (e.g. {{ic|qemu-system-x86_64}}) and thus cannot be both installed at the same time.<br />
<br />
=== Details on packages offered in Arch Linux ===<br />
<br />
* The {{Pkg|qemu}} package provides the {{ic|x86_64}} architecture emulators for full-system emulation ({{ic|qemu-system-x86_64}}). The {{Pkg|qemu-arch-extra}} package provides the {{ic|x86_64}} usermode variant ({{ic|qemu-x86_64}}) and also for the rest of supported architectures it includes both full-system and usermode variants (e.g. {{ic|qemu-system-arm}} and {{ic|qemu-arm}}).<br />
* The headless versions of these packages (only applicable to full-system emulation) are {{Pkg|qemu-headless}} ({{ic|x86_64}}-only) and {{Pkg|qemu-headless-arch-extra}} (rest of architectures).<br />
* Full-system emulation can be expanded with some QEMU modules present in separate packages: {{Pkg|qemu-block-gluster}}, {{Pkg|qemu-block-iscsi}}, {{Pkg|qemu-block-rbd}} and {{Pkg|qemu-guest-agent}}.<br />
* The unofficial AUR package {{AUR|qemu-user-static}} provides a usermode and static variant for all target architectures supported by QEMU. A precompiled version of this package exists: {{AUR|qemu-user-static-bin}}. The installed QEMU commands are named {{ic|qemu-''target_architecture''-static}}, for example, {{ic|qemu-x86_64-static}} for intel 64-bit CPUs.<br />
<br />
{{Note|At present, Arch does not offer a full-system mode and statically linked variant (neither officially nor via AUR), as this is usually not needed.}}<br />
<br />
== Graphical front-ends for QEMU ==<br />
<br />
Unlike other virtualization programs such as [[VirtualBox]] and [[VMware]], QEMU does not provide a GUI to manage virtual machines (other than the window that appears when running a virtual machine), nor does it provide a way to create persistent virtual machines with saved settings. All parameters to run a virtual machine must be specified on the command line at every launch, unless you have created a custom script to start your virtual machine(s).<br />
<br />
[[Libvirt]] provides a convenient way to manage QEMU virtual machines. See [[Libvirt#Client|list of libvirt clients]] for available front-ends.<br />
<br />
Other GUI front-ends for QEMU:<br />
<br />
* {{App|AQEMU|QEMU GUI written in Qt5.|https://github.com/tobimensch/aqemu|{{AUR|aqemu}}}}<br />
<br />
== Creating new virtualized system ==<br />
<br />
=== Creating a hard disk image ===<br />
<br />
{{Accuracy|If I get the man page right the raw format only allocates the full size if the filesystem does not support "holes" or it is <br />
explicitly told to preallocate. See man qemu-img in section Notes.}} <br />
<br />
{{Tip|See [[Wikibooks:QEMU/Images]] for more information on QEMU images.}}<br />
<br />
To run QEMU you will need a hard disk image, unless you are booting a live system from CD-ROM or the network (and not doing so to install an operating system to a hard disk image). A hard disk image is a file which stores the contents of the emulated hard disk.<br />
<br />
A hard disk image can be ''raw'', so that it is literally byte-by-byte the same as what the guest sees, and will always use the full capacity of the guest hard drive on the host. This method provides the least I/O overhead, but can waste a lot of space, as not-used space on the guest cannot be used on the host.<br />
<br />
Alternatively, the hard disk image can be in a format such as ''qcow2'' which only allocates space to the image file when the guest operating system actually writes to those sectors on its virtual hard disk. The image appears as the full size to the guest operating system, even though it may take up only a very small amount of space on the host system. This image format also supports QEMU snapshotting functionality (see [[#Creating and managing snapshots via the monitor console]] for details). However, using this format instead of ''raw'' will likely affect performance.<br />
<br />
QEMU provides the {{ic|qemu-img}} command to create hard disk images. For example to create a 4 GB image in the ''raw'' format:<br />
<br />
$ qemu-img create -f raw ''image_file'' 4G<br />
<br />
You may use {{ic|-f qcow2}} to create a ''qcow2'' disk instead.<br />
<br />
{{Note|You can also simply create a ''raw'' image by creating a file of the needed size using {{ic|dd}} or {{ic|fallocate}}.}}<br />
<br />
{{Warning|If you store the hard disk images on a [[Btrfs]] file system, you should consider disabling [[Btrfs#Copy-on-Write (CoW)|Copy-on-Write]] for the directory before creating any images.}}<br />
<br />
==== Overlay storage images ====<br />
<br />
You can create a storage image once (the 'backing' image) and have QEMU keep mutations to this image in an overlay image. This allows you to revert to a previous state of this storage image. You could revert by creating a new overlay image at the time you wish to revert, based on the original backing image.<br />
<br />
To create an overlay image, issue a command like:<br />
<br />
$ qemu-img create -o backing_file=''img1.raw'',backing_fmt=''raw'' -f ''qcow2'' ''img1.cow''<br />
<br />
After that you can run your QEMU VM as usual (see [[#Running virtualized system]]):<br />
<br />
$ qemu-system-x86_64 ''img1.cow''<br />
<br />
The backing image will then be left intact and mutations to this storage will be recorded in the overlay image file.<br />
<br />
When the path to the backing image changes, repair is required.<br />
<br />
{{Warning|The backing image's absolute filesystem path is stored in the (binary) overlay image file. Changing the backing image's path requires some effort.}}<br />
<br />
Make sure that the original backing image's path still leads to this image. If necessary, make a symbolic link at the original path to the new path. Then issue a command like:<br />
<br />
$ qemu-img rebase -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
At your discretion, you may alternatively perform an 'unsafe' rebase where the old path to the backing image is not checked:<br />
<br />
$ qemu-img rebase -u -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
==== Resizing an image ====<br />
<br />
{{Warning|Resizing an image containing an NTFS boot file system could make the operating system installed on it unbootable. It is recommended to create a backup first.}}<br />
<br />
The {{ic|qemu-img}} executable has the {{ic|resize}} option, which enables easy resizing of a hard drive image. It works for both ''raw'' and ''qcow2''. For example, to increase image space by 10 GB, run:<br />
<br />
$ qemu-img resize ''disk_image'' +10G<br />
<br />
After enlarging the disk image, you must use file system and partitioning tools inside the virtual machine to actually begin using the new space. When shrinking a disk image, you must '''first reduce the allocated file systems and partition sizes''' using the file system and partitioning tools inside the virtual machine and then shrink the disk image accordingly, otherwise shrinking the disk image will result in data loss! For a Windows guest, open the "create and format hard disk partitions" control panel.<br />
<br />
==== Converting an image ====<br />
<br />
You can convert an image to other formats using {{ic|qemu-img convert}}. This example shows how to convert a ''raw'' image to ''qcow2'':<br />
<br />
$ qemu-img convert -f raw -O qcow2 ''input''.img ''output''.qcow2<br />
<br />
This will not remove the original input file.<br />
<br />
=== Preparing the installation media ===<br />
<br />
To install an operating system into your disk image, you need the installation medium (e.g. optical disk, USB-drive, or ISO image) for the operating system. The installation medium should not be mounted because QEMU accesses the media directly.<br />
<br />
{{Tip|If using an optical disk, it is a good idea to first dump the media to a file because this both improves performance and does not require you to have direct access to the devices (that is, you can run QEMU as a regular user without having to change access permissions on the media's device file). For example, if the CD-ROM device node is named {{ic|/dev/cdrom}}, you can dump it to a file with the command: {{bc|1=$ dd if=/dev/cdrom of=''cd_image.iso'' bs=4k}}}}<br />
<br />
=== Installing the operating system ===<br />
<br />
This is the first time you will need to start the emulator. To install the operating system on the disk image, you must attach both the disk image and the installation media to the virtual machine, and have it boot from the installation media.<br />
<br />
For example on i386 guests, to install from a bootable ISO file as CD-ROM and a raw disk image:<br />
<br />
$ qemu-system-x86_64 -cdrom ''iso_image'' -boot order=d -drive file=''disk_image'',format=raw<br />
<br />
See {{man|1|qemu}} for more information about loading other media types (such as floppy, disk images or physical drives) and [[#Running virtualized system]] for other useful options.<br />
<br />
After the operating system has finished installing, the QEMU image can be booted directly (see [[#Running virtualized system]]).<br />
<br />
{{Note|By default only 128 MB of memory is assigned to the machine. The amount of memory can be adjusted with the {{ic|-m}} switch, for example {{ic|-m 512M}} or {{ic|-m 2G}}.}}<br />
<br />
{{Tip|<br />
* Instead of specifying {{ic|1=-boot order=x}}, some users may feel more comfortable using a boot menu: {{ic|1=-boot menu=on}}, at least during configuration and experimentation.<br />
* When running QEMU in headless mode, it starts a local VNC server on port 5900 per default. You can use [[TigerVNC]] to connect to the guest OS: {{ic|vncviewer :5900}}<br />
* If you need to replace floppies or CDs as part of the installation process, you can use the QEMU machine monitor (press {{ic|Ctrl+Alt+2}} in the virtual machine's window) to remove and attach storage devices to a virtual machine. Type {{ic|info block}} to see the block devices, and use the {{ic|change}} command to swap out a device. Press {{ic|Ctrl+Alt+1}} to go back to the virtual machine.<br />
}}<br />
<br />
== Running virtualized system ==<br />
<br />
{{ic|qemu-system-*}} binaries (for example {{ic|qemu-system-i386}} or {{ic|qemu-system-x86_64}}, depending on guest's architecture) are used to run the virtualized guest. The usage is:<br />
<br />
$ qemu-system-x86_64 ''options'' ''disk_image''<br />
<br />
Options are the same for all {{ic|qemu-system-*}} binaries, see {{man|1|qemu}} for documentation of all options.<br />
<br />
By default, QEMU will show the virtual machine's video output in a window. One thing to keep in mind: when you click inside the QEMU window, the mouse pointer is grabbed. To release it, press {{ic|Ctrl+Alt+g}}.<br />
<br />
{{Warning|QEMU should never be run as root. If you must launch it in a script as root, you should use the {{ic|-runas}} option to make QEMU drop root privileges.}}<br />
<br />
=== Enabling KVM ===<br />
<br />
KVM (''Kernel-based Virtual Machine'') full virtualization must be supported by your Linux kernel and your hardware, and necessary [[kernel modules]] must be loaded. See [[KVM]] for more information.<br />
<br />
To start QEMU in KVM mode, append {{ic|-enable-kvm}} to the additional start options. To check if KVM is enabled for a running VM, enter the [[#QEMU monitor]] and type {{ic|info kvm}}.<br />
<br />
{{Note|<br />
* The argument {{ic|1=accel=kvm}} of the {{ic|-machine}} option is equivalent to the {{ic|-enable-kvm}} or the {{ic|-accel kvm}} option.<br />
* CPU model {{ic|host}} requires KVM<br />
* If you start your VM with a GUI tool and experience very bad performance, you should check for proper KVM support, as QEMU may be falling back to software emulation.<br />
* KVM needs to be enabled in order to start Windows 7 and Windows 8 properly without a ''blue screen''.<br />
}}<br />
<br />
=== Enabling IOMMU (Intel VT-d/AMD-Vi) support ===<br />
<br />
First enable IOMMU, see [[PCI passthrough via OVMF#Setting up IOMMU]].<br />
<br />
Add {{ic|-device intel-iommu}} to create the IOMMU device:<br />
<br />
$ qemu-system-x86_64 '''-enable-kvm -machine q35 -device intel-iommu''' -cpu host ..<br />
<br />
{{Note|<br />
On Intel CPU based systems creating an IOMMU device in a QEMU guest with {{ic|-device intel-iommu}} will disable PCI passthrough with an error like: {{bc|Device at bus pcie.0 addr 09.0 requires iommu notifier which is currently not supported by intel-iommu emulation}} While adding the kernel parameter {{ic|1=intel_iommu=on}} is still needed for remapping IO (e.g. [[PCI passthrough via OVMF#Isolating the GPU|PCI passthrough with vfio-pci]]), {{ic|-device intel-iommu}} should not be set if PCI PCI passthrough is required.<br />
}}<br />
<br />
== Sharing data between host and guest ==<br />
<br />
=== Network ===<br />
<br />
Data can be shared between the host and guest OS using any network protocol that can transfer files, such as [[NFS]], [[SMB]], [[Wikipedia:Network block device|NBD]], HTTP, [[Very Secure FTP Daemon|FTP]], or [[SSH]], provided that you have set up the network appropriately and enabled the appropriate services.<br />
<br />
The default user-mode networking allows the guest to access the host OS at the IP address 10.0.2.2. Any servers that you are running on your host OS, such as a SSH server or SMB server, will be accessible at this IP address. So on the guests, you can mount directories exported on the host via [[SMB]] or [[NFS]], or you can access the host's HTTP server, etc.<br />
It will not be possible for the host OS to access servers running on the guest OS, but this can be done with other network configurations (see [[#Tap networking with QEMU]]).<br />
<br />
=== QEMU's port forwarding ===<br />
<br />
QEMU can forward ports from the host to the guest to enable e.g. connecting from the host to an SSH server running on the guest.<br />
<br />
For example, to bind port 10022 on the host with port 22 (SSH) on the guest, start QEMU with a command like:<br />
<br />
$ qemu-system-x86_64 ''disk_image'' -nic user,hostfwd=tcp::10022-:22<br />
<br />
Make sure the sshd is running on the guest and connect with:<br />
<br />
$ ssh ''guest-user''@localhost -p 10022<br />
<br />
You can use [[SSHFS]] to mount the guest's file system at the host for shared read and write access.<br />
<br />
=== QEMU's built-in SMB server ===<br />
<br />
QEMU's documentation says it has a "built-in" SMB server, but actually it just starts up [[Samba]] on the host with an automatically generated {{ic|smb.conf}} file located in {{ic|/tmp/qemu-smb.''random_string''}} and makes it accessible to the guest at a different IP address (10.0.2.4 by default). This only works for user networking, and is useful when you do not want to start the normal [[Samba]] service on the host, which the guest can also access if you have set up shares on it.<br />
<br />
Only a single directory can be set as shared with the option {{ic|1=smb=}}, but adding more directories (even while the virtual machine is running) could be as easy as creating symbolic links in the shared directory if QEMU configured SMB to follow symbolic links. It does not do so, but the configuration of the running SMB server can be changed as described below.<br />
<br />
''Samba'' must be installed on the host. To enable this feature, start QEMU with a command like:<br />
<br />
$ qemu-system-x86_64 ''disk_image'' -net nic -net user,smb=''shared_dir_path''<br />
<br />
where {{ic|''shared_dir_path''}} is a directory that you want to share between the guest and host.<br />
<br />
Then, in the guest, you will be able to access the shared directory on the host 10.0.2.4 with the share name "qemu". For example, in Windows Explorer you would go to {{ic|\\10.0.2.4\qemu}}.<br />
<br />
{{Note|<br />
* If you are using sharing options multiple times like {{ic|1=-net user,smb=''shared_dir_path1'' -net user,smb=''shared_dir_path2''}} or {{ic|1=-net user,smb=''shared_dir_path1'',smb=''shared_dir_path2''}} then it will share only the last defined one.<br />
* If you cannot access the shared folder and the guest system is Windows, check that the [http://ecross.mvps.org/howto/enable-netbios-over-tcp-ip-with-windows.htm NetBIOS protocol is enabled] and that a firewall does not block [https://technet.microsoft.com/en-us/library/cc940063.aspx ports] used by the NetBIOS protocol.<br />
* If you cannot access the shared folder and the guest system is Windows 10 Enterprise or Education or Windows Server 2016, [https://support.microsoft.com/en-us/help/4046019 enable guest access].<br />
}}<br />
<br />
One way to share multiple directories and to add or remove them while the virtual machine is running, is to share an empty directory and create/remove symbolic links to the directories in the shared directory. For this to work, the configuration of the running SMB server can be changed with the following script, which also allows the execution of files on the guest that are not set executable on the host:<br />
<br />
#!/bin/bash<br />
eval $(ps h -C smbd -o pid,args | grep /tmp/qemu-smb | gawk '{print "pid="$1";conf="$6}')<br />
echo "[global]<br />
allow insecure wide links = yes<br />
[qemu]<br />
follow symlinks = yes<br />
wide links = yes<br />
acl allow execute always = yes" >> $conf<br />
# in case the change is not detected automatically:<br />
smbcontrol --configfile=$conf $pid reload-config<br />
<br />
This can be applied to the running server started by qemu only after the guest has connected to the network drive the first time. An alternative to this method is to add additional shares to the configuration file like so:<br />
<br />
echo "[''myshare'']<br />
path=''another_path''<br />
read only=no<br />
guest ok=yes<br />
force user=''username''" >> $conf<br />
<br />
This share will be available on the guest as {{ic|\\10.0.2.4\''myshare''}}.<br />
<br />
=== Using filesystem passthrough and VirtFS ===<br />
<br />
See the [https://wiki.qemu.org/Documentation/9psetup QEMU documentation].<br />
<br />
=== Mounting a partition of the guest on the host ===<br />
<br />
It can be useful to mount a drive image under the host system, it can be a way to transfer files in and out of the guest. This should be done when the virtual machine is not running.<br />
<br />
The procedure to mount the drive on the host depends on the type of qemu image, ''raw'' or ''qcow2''. We detail thereafter the steps to mount a drive in the two formats in [[#Mounting a partition from a raw image]] and [[#Mounting a partition from a qcow2 image]]. For the full documentation see [[Wikibooks:QEMU/Images#Mounting an image on the host]].<br />
<br />
{{Warning|You must make sure to unmount the partitions before running the virtual machine again. Otherwise, data corruption is very likely to occur.}}<br />
<br />
==== Mounting a partition from a raw image ====<br />
<br />
It is possible to mount partitions that are inside a raw disk image file by setting them up as loopback devices.<br />
<br />
===== With manually specifying byte offset =====<br />
<br />
One way to mount a disk image partition is to mount the disk image at a certain offset using a command like the following:<br />
<br />
# mount -o loop,offset=32256 ''disk_image'' ''mountpoint''<br />
<br />
The {{ic|1=offset=32256}} option is actually passed to the {{ic|losetup}} program to set up a loopback device that starts at byte offset 32256 of the file and continues to the end. This loopback device is then mounted. You may also use the {{ic|sizelimit}} option to specify the exact size of the partition, but this is usually unnecessary.<br />
<br />
Depending on your disk image, the needed partition may not start at offset 32256. Run {{ic|fdisk -l ''disk_image''}} to see the partitions in the image. fdisk gives the start and end offsets in 512-byte sectors, so multiply by 512 to get the correct offset to pass to {{ic|mount}}.<br />
<br />
===== With loop module autodetecting partitions =====<br />
<br />
The Linux loop driver actually supports partitions in loopback devices, but it is disabled by default. To enable it, do the following:<br />
<br />
* Get rid of all your loopback devices (unmount all mounted images, etc.).<br />
* [[Kernel_modules#Manual_module_handling|Unload]] the {{ic|loop}} kernel module, and load it with the {{ic|1=max_part=15}} parameter set. Additionally, the maximum number of loop devices can be controlled with the {{ic|max_loop}} parameter.<br />
<br />
{{Tip|You can put an entry in {{ic|/etc/modprobe.d}} to load the loop module with {{ic|1=max_part=15}} every time, or you can put {{ic|1=loop.max_part=15}} on the kernel command-line, depending on whether you have the {{ic|loop.ko}} module built into your kernel or not.}}<br />
<br />
Set up your image as a loopback device:<br />
<br />
# losetup -f -P ''disk_image''<br />
<br />
Then, if the device created was {{ic|/dev/loop0}}, additional devices {{ic|/dev/loop0pX}} will have been automatically created, where X is the number of the partition. These partition loopback devices can be mounted directly. For example:<br />
<br />
# mount /dev/loop0p1 ''mountpoint''<br />
<br />
To mount the disk image with ''udisksctl'', see [[Udisks#Mount loop devices]].<br />
<br />
===== With kpartx =====<br />
<br />
'''kpartx''' from the {{Pkg|multipath-tools}} package can read a partition table on a device and create a new device for each partition. For example:<br />
<br />
# kpartx -a ''disk_image''<br />
<br />
This will setup the loopback device and create the necessary partition(s) device(s) in {{ic|/dev/mapper/}}.<br />
<br />
==== Mounting a partition from a qcow2 image ====<br />
<br />
We will use {{ic|qemu-nbd}}, which lets use the NBD (''network block device'') protocol to share the disk image.<br />
<br />
First, we need the ''nbd'' module loaded:<br />
<br />
# modprobe nbd max_part=16<br />
<br />
Then, we can share the disk and create the device entries:<br />
<br />
# qemu-nbd -c /dev/nbd0 ''/path/to/image.qcow2''<br />
<br />
Discover the partitions:<br />
<br />
# partprobe /dev/nbd0<br />
<br />
''fdisk'' can be used to get information regarding the different partitions in {{{ic|''nbd0''}}:<br />
<br />
{{hc|# fdisk -l /dev/nbd0|2=<br />
Disk /dev/nbd0: 25.2 GiB, 27074281472 bytes, 52879456 sectors<br />
Units: sectors of 1 * 512 = 512 bytes<br />
Sector size (logical/physical): 512 bytes / 512 bytes<br />
I/O size (minimum/optimal): 512 bytes / 512 bytes<br />
Disklabel type: dos<br />
Disk identifier: 0xa6a4d542<br />
<br />
Device Boot Start End Sectors Size Id Type<br />
/dev/nbd0p1 * 2048 1026047 1024000 500M 7 HPFS/NTFS/exFAT<br />
/dev/nbd0p2 1026048 52877311 51851264 24.7G 7 HPFS/NTFS/exFAT}}<br />
<br />
Then mount any partition of the drive image, for example the partition 2:<br />
<br />
# mount /dev/nbd0'''p2''' ''mountpoint''<br />
<br />
After the usage, it is important to unmount the image and reverse previous steps, i.e. unmount the partition and disconnect the nbd device:<br />
<br />
# umount ''mountpoint''<br />
# qemu-nbd -d /dev/nbd0<br />
<br />
=== Using any real partition as the single primary partition of a hard disk image ===<br />
<br />
Sometimes, you may wish to use one of your system partitions from within QEMU. Using a raw partition for a virtual machine will improve performance, as the read and write operations do not go through the file system layer on the physical host. Such a partition also provides a way to share data between the host and guest.<br />
<br />
In Arch Linux, device files for raw partitions are, by default, owned by ''root'' and the ''disk'' group. If you would like to have a non-root user be able to read and write to a raw partition, you must either change the owner of the partition's device file to that user, add that user to the ''disk'' group, or use [[ACL]] for more fine-grained access control.<br />
<br />
{{Warning|<br />
* Although it is possible, it is not recommended to allow virtual machines to alter critical data on the host system, such as the root partition.<br />
* You must not mount a file system on a partition read-write on both the host and the guest at the same time. Otherwise, data corruption will result.<br />
}}<br />
<br />
After doing so, you can attach the partition to a QEMU virtual machine as a virtual disk.<br />
<br />
However, things are a little more complicated if you want to have the ''entire'' virtual machine contained in a partition. In that case, there would be no disk image file to actually boot the virtual machine since you cannot install a bootloader to a partition that is itself formatted as a file system and not as a partitioned device with an MBR. Such a virtual machine can be booted either by specifying the [[kernel]] and [[initrd]] manually, or by simulating a disk with an MBR by using the [https://www.kernel.org/doc/html/latest/admin-guide/device-mapper/index.html Device-mapper], linear [[RAID]], or a [https://www.kernel.org/doc/html/latest/admin-guide/blockdev/nbd.html Linux Network Block Device].<br />
<br />
==== By specifying kernel and initrd manually ====<br />
<br />
QEMU supports loading [[Kernels|Linux kernels]] and [[initramfs|init ramdisks]] directly, thereby circumventing bootloaders such as [[GRUB]]. It then can be launched with the physical partition containing the root file system as the virtual disk, which will not appear to be partitioned. This is done by issuing a command similar to the following:<br />
<br />
{{Note|In this example, it is the '''host's''' images that are being used, not the guest's. If you wish to use the guest's images, either mount {{ic|/dev/sda3}} read-only (to protect the file system from the host) and specify the {{ic|/full/path/to/images}} or use some kexec hackery in the guest to reload the guest's kernel (extends boot time). }}<br />
<br />
$ qemu-system-x86_64 -kernel /boot/vmlinuz-linux -initrd /boot/initramfs-linux.img -append root=/dev/sda /dev/sda3<br />
<br />
In the above example, the physical partition being used for the guest's root file system is {{ic|/dev/sda3}} on the host, but it shows up as {{ic|/dev/sda}} on the guest.<br />
<br />
You may, of course, specify any kernel and initrd that you want, and not just the ones that come with Arch Linux.<br />
<br />
When there are multiple [[kernel parameters]] to be passed to the {{ic|-append}} option, they need to be quoted using single or double quotes. For example:<br />
<br />
... -append 'root=/dev/sda1 console=ttyS0'<br />
<br />
==== Simulate a virtual disk with MBR ====<br />
<br />
A more complicated way to have a virtual machine use a physical partition, while keeping that partition formatted as a file system and not just having the guest partition the partition as if it were a disk, is to simulate an MBR for it so that it can boot using a bootloader such as GRUB.<br />
<br />
For the following, suppose you have a plain, unmounted {{ic|/dev/hda''N''}} partition with some file system on it you wish to make part of a QEMU disk image. The trick is to dynamically prepend a master boot record (MBR) to the real partition you wish to embed in a QEMU raw disk image. More generally, the partition can be any part of a larger simulated disk, in particular a block device that simulates the original physical disk but only exposes {{ic|/dev/hda''N''}} to the virtual machine.<br />
<br />
A virtual disk of this type can be represented by a VMDK file that contains references to (a copy of) the MBR and the partition, but QEMU does not support this VMDK format. For instance, a virtual disk [https://www.virtualbox.org/manual/ch09.html#rawdisk created by]<br />
<br />
$ VBoxManage internalcommands createrawvmdk -filename ''/path/to/file.vmdk'' -rawdisk /dev/hda<br />
<br />
will be rejected by QEMU with the error message<br />
<br />
Unsupported image type 'partitionedDevice'<br />
<br />
Note that {{ic|VBoxManage}} creates two files, {{ic|''file.vmdk''}} and {{ic|''file-pt.vmdk''}}, the latter being a copy of the MBR, to which the text file {{ic|file.vmdk}} points. Read operations outside the target partition or the MBR would give zeros, while written data would be discarded.<br />
<br />
===== Device Mapper =====<br />
<br />
A method that is similar to the use of a VMDK descriptor file uses the device mapper to prepend a loop device attached to the MBR file to the target partition. In case we do not need our virtual disk to have the same size as the original, we first create a file to hold the MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=2048<br />
<br />
Here, a 1 MB (2048 * 512 bytes) file is created in accordance with partition alignment policies used by modern disk partitioning tools. For compatibility with older partitioning software, 63 sectors instead of 2048 might be required. The MBR only needs a single 512 bytes block, the additional free space can be used for a BIOS boot partition and, in the case of a hybrid partitioning scheme, for a GUID Partition Table. Then, we attach a loop device to the MBR file:<br />
<br />
# losetup --show -f ''/path/to/mbr''<br />
/dev/loop0<br />
<br />
In this example, the resulting device is {{ic|/dev/loop0}}. The device mapper is now used to join the MBR and the partition:<br />
<br />
# echo "0 2048 linear /dev/loop0 0<br />
2048 `blockdev --getsz /dev/hda''N''` linear /dev/hda''N'' 0" | dmsetup create qemu<br />
<br />
The resulting {{ic|/dev/mapper/qemu}} is what we will use as a QEMU raw disk image. Additional steps are required to create a partition table (see the section that describes the use of a linear RAID for an example) and boot loader code on the virtual disk (which will be stored in {{ic|''/path/to/mbr''}}).<br />
<br />
The following setup is an example where the position of {{ic|/dev/hda''N''}} on the virtual disk is to be the same as on the physical disk and the rest of the disk is hidden, except for the MBR, which is provided as a copy:<br />
<br />
# dd if=/dev/hda count=1 of=''/path/to/mbr''<br />
# loop=`losetup --show -f ''/path/to/mbr''`<br />
# start=`blockdev --report /dev/hda''N'' | tail -1 | awk '{print $5}'`<br />
# size=`blockdev --getsz /dev/hda''N''`<br />
# disksize=`blockdev --getsz /dev/hda`<br />
# echo "0 1 linear $loop 0<br />
1 $((start-1)) zero<br />
$start $size linear /dev/hda''N'' 0<br />
$((start+size)) $((disksize-start-size)) zero" | dmsetup create qemu<br />
<br />
The table provided as standard input to {{ic|dmsetup}} has a similar format as the table in a VDMK descriptor file produced by {{ic|VBoxManage}} and can alternatively be loaded from a file with {{ic|dmsetup create qemu --table ''table_file''}}. To the virtual machine, only {{ic|/dev/hda''N''}} is accessible, while the rest of the hard disk reads as zeros and discards written data, except for the first sector. We can print the table for {{ic|/dev/mapper/qemu}} with {{ic|dmsetup table qemu}} (use {{ic|udevadm info -rq name /sys/dev/block/''major'':''minor''}} to translate {{ic|''major'':''minor''}} to the corresponding {{ic|/dev/''blockdevice''}} name). Use {{ic|dmsetup remove qemu}} and {{ic|losetup -d $loop}} to delete the created devices.<br />
<br />
A situation where this example would be useful is an existing Windows XP installation in a multi-boot configuration and maybe a hybrid partitioning scheme (on the physical hardware, Windows XP could be the only operating system that uses the MBR partition table, while more modern operating systems installed on the same computer could use the GUID Partition Table). Windows XP supports hardware profiles, so that that the same installation can be used with different hardware configurations alternatingly (in this case bare metal vs. virtual) with Windows needing to install drivers for newly detected hardware only once for every profile. Note that in this example the boot loader code in the copied MBR needs to be updated to directly load Windows XP from {{ic|/dev/hda''N''}} instead of trying to start the multi-boot capable boot loader (like GRUB) present in the original system. Alternatively, a copy of the boot partition containing the boot loader installation can be included in the virtual disk the same way as the MBR.<br />
<br />
===== Linear RAID =====<br />
<br />
You can also do this using software [[RAID]] in linear mode (you need the {{ic|linear.ko}} kernel driver) and a loopback device: <br />
<br />
First, you create some small file to hold the MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=32<br />
<br />
Here, a 16 KB (32 * 512 bytes) file is created. It is important not to make it too small (even if the MBR only needs a single 512 bytes block), since the smaller it will be, the smaller the chunk size of the software RAID device will have to be, which could have an impact on performance. Then, you setup a loopback device to the MBR file:<br />
<br />
# losetup -f ''/path/to/mbr''<br />
<br />
Let us assume the resulting device is {{ic|/dev/loop0}}, because we would not already have been using other loopbacks. Next step is to create the "merged" MBR + {{ic|/dev/hda''N''}} disk image using software RAID:<br />
<br />
# modprobe linear<br />
# mdadm --build --verbose /dev/md0 --chunk=16 --level=linear --raid-devices=2 /dev/loop0 /dev/hda''N''<br />
<br />
The resulting {{ic|/dev/md0}} is what you will use as a QEMU raw disk image (do not forget to set the permissions so that the emulator can access it). The last (and somewhat tricky) step is to set the disk configuration (disk geometry and partitions table) so that the primary partition start point in the MBR matches the one of {{ic|/dev/hda''N''}} inside {{ic|/dev/md0}} (an offset of exactly 16 * 512 = 16384 bytes in this example). Do this using {{ic|fdisk}} on the host machine, not in the emulator: the default raw disc detection routine from QEMU often results in non-kilobyte-roundable offsets (such as 31.5 KB, as in the previous section) that cannot be managed by the software RAID code. Hence, from the the host:<br />
<br />
# fdisk /dev/md0<br />
<br />
Press {{ic|X}} to enter the expert menu. Set number of 's'ectors per track so that the size of one cylinder matches the size of your MBR file. For two heads and a sector size of 512, the number of sectors per track should be 16, so we get cylinders of size 2x16x512=16k.<br />
<br />
Now, press {{ic|R}} to return to the main menu.<br />
<br />
Press {{ic|P}} and check that the cylinder size is now 16k.<br />
<br />
Now, create a single primary partition corresponding to {{ic|/dev/hda''N''}}. It should start at cylinder 2 and end at the end of the disk (note that the number of cylinders now differs from what it was when you entered fdisk.<br />
<br />
Finally, 'w'rite the result to the file: you are done. You now have a partition you can mount directly from your host, as well as part of a QEMU disk image:<br />
<br />
$ qemu-system-x86_64 -hdc /dev/md0 ''[...]''<br />
<br />
You can, of course, safely set any bootloader on this disk image using QEMU, provided the original {{ic|/dev/hda''N''}} partition contains the necessary tools.<br />
<br />
===== Network Block Device =====<br />
<br />
Instead of the methods decribed above, you may use {{ic|nbd-server}} (from the {{pkg|nbd}} package) to create an MBR wrapper for QEMU.<br />
<br />
Assuming you have already set up your MBR wrapper file like above, rename it to {{ic|wrapper.img.0}}. Then create a symbolic link named {{ic|wrapper.img.1}} in the same directory, pointing to your partition. Then put the following script in the same directory:<br />
<br />
#!/bin/sh<br />
dir="$(realpath "$(dirname "$0")")"<br />
cat >wrapper.conf <<EOF<br />
[generic]<br />
allowlist = true<br />
listenaddr = 127.713705<br />
port = 10809<br />
<br />
[wrap]<br />
exportname = $dir/wrapper.img<br />
multifile = true<br />
EOF<br />
<br />
nbd-server \<br />
-C wrapper.conf \<br />
-p wrapper.pid \<br />
"$@"<br />
<br />
The {{ic|.0}} and {{ic|.1}} suffixes are essential; the rest can be changed. After running the above script (which you may need to do as root to make sure nbd-server is able to access the partition), you can launch QEMU with:<br />
<br />
qemu-system-x86_64 -drive file=nbd:127.713705:10809:exportname=wrap ''[...]''<br />
<br />
== Networking ==<br />
<br />
{{Style|Network topologies (sections [[#Host-only networking]], [[#Internal networking]] and info spread out across other sections) should not be described alongside the various virtual interfaces implementations, such as [[#User-mode networking]], [[#Tap networking with QEMU]], [[#Networking with VDE2]].}}<br />
<br />
The performance of virtual networking should be better with tap devices and bridges than with user-mode networking or vde because tap devices and bridges are implemented in-kernel.<br />
<br />
In addition, networking performance can be improved by assigning virtual machines a [http://wiki.libvirt.org/page/Virtio virtio] network device rather than the default emulation of an e1000 NIC. See [[#Installing virtio drivers]] for more information.<br />
<br />
=== Link-level address caveat ===<br />
<br />
By giving the {{ic|-net nic}} argument to QEMU, it will, by default, assign a virtual machine a network interface with the link-level address {{ic|52:54:00:12:34:56}}. However, when using bridged networking with multiple virtual machines, it is essential that each virtual machine has a unique link-level (MAC) address on the virtual machine side of the tap device. Otherwise, the bridge will not work correctly, because it will receive packets from multiple sources that have the same link-level address. This problem occurs even if the tap devices themselves have unique link-level addresses because the source link-level address is not rewritten as packets pass through the tap device.<br />
<br />
Make sure that each virtual machine has a unique link-level address, but it should always start with {{ic|52:54:}}. Use the following option, replace ''X'' with arbitrary hexadecimal digit:<br />
<br />
$ qemu-system-x86_64 -net nic,macaddr=52:54:''XX:XX:XX:XX'' -net vde ''disk_image''<br />
<br />
Generating unique link-level addresses can be done in several ways:<br />
<br />
* Manually specify unique link-level address for each NIC. The benefit is that the DHCP server will assign the same IP address each time the virtual machine is run, but it is unusable for large number of virtual machines.<br />
* Generate random link-level address each time the virtual machine is run. Practically zero probability of collisions, but the downside is that the DHCP server will assign a different IP address each time. You can use the following command in a script to generate random link-level address in a {{ic|macaddr}} variable:<br />
<br />
{{bc|1=<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
qemu-system-x86_64 -net nic,macaddr="$macaddr" -net vde ''disk_image''<br />
}}<br />
<br />
* Use the following script {{ic|qemu-mac-hasher.py}} to generate the link-level address from the virtual machine name using a hashing function. Given that the names of virtual machines are unique, this method combines the benefits of the aforementioned methods: it generates the same link-level address each time the script is run, yet it preserves the practically zero probability of collisions.<br />
<br />
{{hc|qemu-mac-hasher.py|<nowiki><br />
#!/usr/bin/env python<br />
<br />
import sys<br />
import zlib<br />
<br />
if len(sys.argv) != 2:<br />
print("usage: %s <VM Name>" % sys.argv[0])<br />
sys.exit(1)<br />
<br />
crc = zlib.crc32(sys.argv[1].encode("utf-8")) & 0xffffffff<br />
crc = str(hex(crc))[2:]<br />
print("52:54:%s%s:%s%s:%s%s:%s%s" % tuple(crc))<br />
</nowiki>}}<br />
<br />
In a script, you can use for example:<br />
<br />
vm_name="''VM Name''"<br />
qemu-system-x86_64 -name "$vm_name" -net nic,macaddr=$(qemu-mac-hasher.py "$vm_name") -net vde ''disk_image''<br />
<br />
=== User-mode networking ===<br />
<br />
By default, without any {{ic|-netdev}} arguments, QEMU will use user-mode networking with a built-in DHCP server. Your virtual machines will be assigned an IP address when they run their DHCP client, and they will be able to access the physical host's network through IP masquerading done by QEMU.<br />
<br />
{{warning|This only works with the TCP and UDP protocols, so ICMP, including {{ic|ping}}, will not work. Do not use {{ic|ping}} to test network connectivity. To make ping work in the guest see [[Sysctl#Allow unprivileged users to create IPPROTO_ICMP sockets]].}}<br />
<br />
This default configuration allows your virtual machines to easily access the Internet, provided that the host is connected to it, but the virtual machines will not be directly visible on the external network, nor will virtual machines be able to talk to each other if you start up more than one concurrently.<br />
<br />
QEMU's user-mode networking can offer more capabilities such as built-in TFTP or SMB servers, redirecting host ports to the guest (for example to allow SSH connections to the guest) or attaching guests to VLANs so that they can talk to each other. See the QEMU documentation on the {{ic|-net user}} flag for more details.<br />
<br />
However, user-mode networking has limitations in both utility and performance. More advanced network configurations require the use of tap devices or other methods.<br />
<br />
{{Note|If the host system uses [[systemd-networkd]], make sure to symlink the {{ic|/etc/resolv.conf}} file as described in [[systemd-networkd#Required services and setup]], otherwise the DNS lookup in the guest system will not work.}}<br />
<br />
=== Tap networking with QEMU ===<br />
<br />
[[wikipedia:TUN/TAP|Tap devices]] are a Linux kernel feature that allows you to create virtual network interfaces that appear as real network interfaces. Packets sent to a tap interface are delivered to a userspace program, such as QEMU, that has bound itself to the interface.<br />
<br />
QEMU can use tap networking for a virtual machine so that packets sent to the tap interface will be sent to the virtual machine and appear as coming from a network interface (usually an Ethernet interface) in the virtual machine. Conversely, everything that the virtual machine sends through its network interface will appear on the tap interface.<br />
<br />
Tap devices are supported by the Linux bridge drivers, so it is possible to bridge together tap devices with each other and possibly with other host interfaces such as {{ic|eth0}}. This is desirable if you want your virtual machines to be able to talk to each other, or if you want other machines on your LAN to be able to talk to the virtual machines.<br />
<br />
{{Warning|If you bridge together tap device and some host interface, such as {{ic|eth0}}, your virtual machines will appear directly on the external network, which will expose them to possible attack. Depending on what resources your virtual machines have access to, you may need to take all the [[Firewalls|precautions]] you normally would take in securing a computer to secure your virtual machines. If the risk is too great, virtual machines have little resources or you set up multiple virtual machines, a better solution might be to use [[#Host-only networking|host-only networking]] and set up NAT. In this case you only need one firewall on the host instead of multiple firewalls for each guest.}}<br />
<br />
As indicated in the user-mode networking section, tap devices offer higher networking performance than user-mode. If the guest OS supports virtio network driver, then the networking performance will be increased considerably as well. Supposing the use of the tap0 device, that the virtio driver is used on the guest, and that no scripts are used to help start/stop networking, next is part of the qemu command one should see:<br />
<br />
-device virtio-net,netdev=network0 -netdev tap,id=network0,ifname=tap0,script=no,downscript=no<br />
<br />
But if already using a tap device with virtio networking driver, one can even boost the networking performance by enabling vhost, like:<br />
<br />
-device virtio-net,netdev=network0 -netdev tap,id=network0,ifname=tap0,script=no,downscript=no,vhost=on<br />
<br />
See [https://web.archive.org/web/20160222161955/http://www.linux-kvm.com:80/content/how-maximize-virtio-net-performance-vhost-net] for more information.<br />
<br />
==== Host-only networking ====<br />
<br />
If the bridge is given an IP address and traffic destined for it is allowed, but no real interface (e.g. {{ic|eth0}}) is connected to the bridge, then the virtual machines will be able to talk to each other and the host system. However, they will not be able to talk to anything on the external network, provided that you do not set up IP masquerading on the physical host. This configuration is called ''host-only networking'' by other virtualization software such as [[VirtualBox]].<br />
<br />
{{Tip|<br />
* If you want to set up IP masquerading, e.g. NAT for virtual machines, see the [[Internet sharing#Enable NAT]] page.<br />
* See [[Network bridge]] for information on creating bridge.<br />
* You may want to have a DHCP server running on the bridge interface to service the virtual network. For example, to use the {{ic|172.20.0.1/16}} subnet with [[dnsmasq]] as the DHCP server:<br />
<br />
{{bc|1=<br />
# ip addr add 172.20.0.1/16 dev br0<br />
# ip link set br0 up<br />
# dnsmasq --interface=br0 --bind-interfaces --dhcp-range=172.20.0.2,172.20.255.254<br />
}}<br />
}}<br />
<br />
==== Internal networking ====<br />
<br />
If you do not give the bridge an IP address and add an [[iptables]] rule to drop all traffic to the bridge in the INPUT chain, then the virtual machines will be able to talk to each other, but not to the physical host or to the outside network. This configuration is called ''internal networking'' by other virtualization software such as [[VirtualBox]]. You will need to either assign static IP addresses to the virtual machines or run a DHCP server on one of them.<br />
<br />
By default iptables would drop packets in the bridge network. You may need to use such iptables rule to allow packets in a bridged network:<br />
<br />
# iptables -I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Bridged networking using qemu-bridge-helper ====<br />
<br />
{{Note|This method is available since QEMU 1.1, see http://wiki.qemu.org/Features/HelperNetworking.}}<br />
<br />
This method does not require a start-up script and readily accommodates multiple taps and multiple bridges. It uses {{ic|/usr/lib/qemu/qemu-bridge-helper}} binary, which allows creating tap devices on an existing bridge.<br />
<br />
{{Tip|See [[Network bridge]] for information on creating bridge.}}<br />
<br />
First, create a configuration file containing the names of all bridges to be used by QEMU:<br />
<br />
{{hc|/etc/qemu/bridge.conf|<br />
allow ''bridge0''<br />
allow ''bridge1''<br />
...}}<br />
<br />
Now start the VM. The most basic usage would be:<br />
<br />
$ qemu-system-x86_64 -net nic -net bridge,br=''bridge0'' ''[...]''<br />
<br />
With multiple taps, the most basic usage requires specifying the VLAN for all additional NICs:<br />
<br />
$ qemu-system-x86_64 -net nic -net bridge,br=''bridge0'' -net nic,vlan=1 -net bridge,vlan=1,br=''bridge1'' ''[...]''<br />
<br />
==== Creating bridge manually ====<br />
<br />
{{Style|This section needs serious cleanup and may contain out-of-date information.}}<br />
<br />
{{Tip|Since QEMU 1.1, the [http://wiki.qemu.org/Features/HelperNetworking network bridge helper] can set tun/tap up for you without the need for additional scripting. See [[#Bridged networking using qemu-bridge-helper]].}}<br />
<br />
The following describes how to bridge a virtual machine to a host interface such as {{ic|eth0}}, which is probably the most common configuration. This configuration makes it appear that the virtual machine is located directly on the external network, on the same Ethernet segment as the physical host machine.<br />
<br />
We will replace the normal Ethernet adapter with a bridge adapter and bind the normal Ethernet adapter to it.<br />
<br />
* Install {{Pkg|bridge-utils}}, which provides {{ic|brctl}} to manipulate bridges.<br />
<br />
* Enable IPv4 forwarding:<br />
# sysctl -w net.ipv4.ip_forward=1<br />
<br />
To make the change permanent, change {{ic|1=net.ipv4.ip_forward = 0}} to {{ic|1=net.ipv4.ip_forward = 1}} in {{ic|/etc/sysctl.d/99-sysctl.conf}}.<br />
<br />
* Load the {{ic|tun}} module and configure it to be loaded on boot. See [[Kernel modules]] for details.<br />
<br />
* Now create the bridge. See [[Bridge with netctl]] for details. Remember to name your bridge as {{ic|br0}}, or change the scripts below to your bridge's name.<br />
<br />
* Create the script that QEMU uses to bring up the tap adapter with {{ic|root:kvm}} 750 permissions:<br />
<br />
{{hc|/etc/qemu-ifup|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifup"<br />
echo "Bringing up $1 for bridged mode..."<br />
sudo /usr/bin/ip link set $1 up promisc on<br />
echo "Adding $1 to br0..."<br />
sudo /usr/bin/brctl addif br0 $1<br />
sleep 2<br />
</nowiki>}}<br />
<br />
* Create the script that QEMU uses to bring down the tap adapter in {{ic|/etc/qemu-ifdown}} with {{ic|root:kvm}} 750 permissions:<br />
{{hc|/etc/qemu-ifdown|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifdown"<br />
sudo /usr/bin/ip link set $1 down<br />
sudo /usr/bin/brctl delif br0 $1<br />
sudo /usr/bin/ip link delete dev $1<br />
</nowiki>}}<br />
<br />
* Use {{ic|visudo}} to add the following to your {{ic|sudoers}} file:<br />
<br />
{{bc|<nowiki><br />
Cmnd_Alias QEMU=/usr/bin/ip,/usr/bin/modprobe,/usr/bin/brctl<br />
%kvm ALL=NOPASSWD: QEMU<br />
</nowiki>}}<br />
<br />
* You launch QEMU using the following {{ic|run-qemu}} script:<br />
<br />
{{hc|run-qemu|<nowiki><br />
#!/bin/bash<br />
USERID=$(whoami)<br />
<br />
# Get name of newly created TAP device; see https://bbs.archlinux.org/viewtopic.php?pid=1285079#p1285079<br />
precreationg=$(/usr/bin/ip tuntap list | /usr/bin/cut -d: -f1 | /usr/bin/sort)<br />
sudo /usr/bin/ip tuntap add user $USERID mode tap<br />
postcreation=$(/usr/bin/ip tuntap list | /usr/bin/cut -d: -f1 | /usr/bin/sort)<br />
IFACE=$(comm -13 <(echo "$precreationg") <(echo "$postcreation"))<br />
<br />
# This line creates a random MAC address. The downside is the DHCP server will assign a different IP address each time<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
# Instead, uncomment and edit this line to set a static MAC address. The benefit is that the DHCP server will assign the same IP address.<br />
# macaddr='52:54:be:36:42:a9'<br />
<br />
qemu-system-x86_64 -net nic,macaddr=$macaddr -net tap,ifname="$IFACE" $*<br />
<br />
sudo ip link set dev $IFACE down &> /dev/null<br />
sudo ip tuntap del $IFACE mode tap &> /dev/null<br />
</nowiki>}}<br />
<br />
Then to launch a VM, do something like this<br />
<br />
$ run-qemu -hda ''myvm.img'' -m 512<br />
<br />
* It is recommended for performance and security reasons to disable the [http://ebtables.netfilter.org/documentation/bridge-nf.html firewall on the bridge]:<br />
<br />
{{hc|/etc/sysctl.d/10-disable-firewall-on-bridge.conf|<nowiki><br />
net.bridge.bridge-nf-call-ip6tables = 0<br />
net.bridge.bridge-nf-call-iptables = 0<br />
net.bridge.bridge-nf-call-arptables = 0<br />
</nowiki>}}<br />
<br />
Run {{ic|sysctl -p /etc/sysctl.d/10-disable-firewall-on-bridge.conf}} to apply the changes immediately.<br />
<br />
See the [http://wiki.libvirt.org/page/Networking#Creating_network_initscripts libvirt wiki] and [https://bugzilla.redhat.com/show_bug.cgi?id=512206 Fedora bug 512206]. If you get errors by sysctl during boot about non-existing files, make the {{ic|bridge}} module load at boot. See [[Kernel modules#Automatic module loading with systemd]].<br />
<br />
Alternatively, you can configure [[iptables]] to allow all traffic to be forwarded across the bridge by adding a rule like this:<br />
<br />
-I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Network sharing between physical device and a Tap device through iptables ====<br />
<br />
{{Merge|Internet_sharing|Duplication, not specific to QEMU.}}<br />
<br />
Bridged networking works fine between a wired interface (Eg. eth0), and it is easy to setup. However if the host gets connected to the network through a wireless device, then bridging is not possible.<br />
<br />
See [[Network bridge#Wireless interface on a bridge]] as a reference.<br />
<br />
One way to overcome that is to setup a tap device with a static IP, making linux automatically handle the routing for it, and then forward traffic between the tap interface and the device connected to the network through iptables rules.<br />
<br />
See [[Internet sharing]] as a reference.<br />
<br />
There you can find what is needed to share the network between devices, included tap and tun ones. The following just hints further on some of the host configurations required. As indicated in the reference above, the client needs to be configured for a static IP, using the IP assigned to the tap interface as the gateway. The caveat is that the DNS servers on the client might need to be manually edited if they change when changing from one host device connected to the network to another.<br />
<br />
To allow IP forwarding on every boot, one need to add the following lines to sysctl configuration file inside {{ic|/etc/sysctl.d}}:<br />
<br />
net.ipv4.ip_forward = 1<br />
net.ipv6.conf.default.forwarding = 1<br />
net.ipv6.conf.all.forwarding = 1<br />
<br />
The iptables rules can look like:<br />
<br />
# Forwarding from/to outside<br />
iptables -A FORWARD -i ${INT} -o ${EXT_0} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_1} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_2} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_0} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_1} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_2} -o ${INT} -j ACCEPT<br />
# NAT/Masquerade (network address translation)<br />
iptables -t nat -A POSTROUTING -o ${EXT_0} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_1} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_2} -j MASQUERADE<br />
<br />
The prior supposes there are 3 devices connected to the network sharing traffic with one internal device, where for example:<br />
<br />
INT=tap0<br />
EXT_0=eth0<br />
EXT_1=wlan0<br />
EXT_2=tun0<br />
<br />
The prior shows a forwarding that would allow sharing wired and wireless connections with the tap device.<br />
<br />
The forwarding rules shown are stateless, and for pure forwarding. One could think of restricting specific traffic, putting a firewall in place to protect the guest and others. However those would decrease the networking performance, while a simple bridge does not include any of that.<br />
<br />
Bonus: Whether the connection is wired or wireless, if one gets connected through VPN to a remote site with a tun device, supposing the tun device opened for that connection is tun0, and the prior iptables rules are applied, then the remote connection gets also shared with the guest. This avoids the need for the guest to also open a VPN connection. Again, as the guest networking needs to be static, then if connecting the host remotely this way, one most probably will need to edit the DNS servers on the guest.<br />
<br />
=== Networking with VDE2 ===<br />
<br />
{{Style|This section needs serious cleanup and may contain out-of-date information.}}<br />
<br />
==== What is VDE? ====<br />
<br />
VDE stands for Virtual Distributed Ethernet. It started as an enhancement of [[User-mode Linux|uml]]_switch. It is a toolbox to manage virtual networks.<br />
<br />
The idea is to create virtual switches, which are basically sockets, and to "plug" both physical and virtual machines in them. The configuration we show here is quite simple; However, VDE is much more powerful than this, it can plug virtual switches together, run them on different hosts and monitor the traffic in the switches. You are invited to read [https://wiki.virtualsquare.org/ the documentation of the project].<br />
<br />
The advantage of this method is you do not have to add sudo privileges to your users. Regular users should not be allowed to run modprobe.<br />
<br />
==== Basics ====<br />
<br />
VDE support can be [[pacman|installed]] via the {{Pkg|vde2}} package.<br />
<br />
In our config, we use tun/tap to create a virtual interface on my host. Load the {{ic|tun}} module (see [[Kernel modules]] for details):<br />
<br />
# modprobe tun<br />
<br />
Now create the virtual switch:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
<br />
This line creates the switch, creates {{ic|tap0}}, "plugs" it, and allows the users of the group {{ic|users}} to use it.<br />
<br />
The interface is plugged in but not configured yet. To configure it, run this command:<br />
<br />
# ip addr add 192.168.100.254/24 dev tap0<br />
<br />
Now, you just have to run KVM with these {{ic|-net}} options as a normal user:<br />
<br />
$ qemu-system-x86_64 -net nic -net vde -hda ''[...]''<br />
<br />
Configure networking for your guest as you would do in a physical network.<br />
<br />
{{Tip|You might want to set up NAT on tap device to access the internet from the virtual machine. See [[Internet sharing#Enable NAT]] for more information.}}<br />
<br />
==== Startup scripts ====<br />
<br />
Example of main script starting VDE:<br />
<br />
{{hc|/etc/systemd/scripts/qemu-network-env|<nowiki><br />
#!/bin/sh<br />
# QEMU/VDE network environment preparation script<br />
<br />
# The IP configuration for the tap device that will be used for<br />
# the virtual machine network:<br />
<br />
TAP_DEV=tap0<br />
TAP_IP=192.168.100.254<br />
TAP_MASK=24<br />
TAP_NETWORK=192.168.100.0<br />
<br />
# Host interface<br />
NIC=eth0<br />
<br />
case "$1" in<br />
start)<br />
echo -n "Starting VDE network for QEMU: "<br />
<br />
# If you want tun kernel module to be loaded by script uncomment here<br />
#modprobe tun 2>/dev/null<br />
## Wait for the module to be loaded<br />
#while ! lsmod | grep -q "^tun"; do echo "Waiting for tun device"; sleep 1; done<br />
<br />
# Start tap switch<br />
vde_switch -tap "$TAP_DEV" -daemon -mod 660 -group users<br />
<br />
# Bring tap interface up<br />
ip address add "$TAP_IP"/"$TAP_MASK" dev "$TAP_DEV"<br />
ip link set "$TAP_DEV" up<br />
<br />
# Start IP Forwarding<br />
echo "1" > /proc/sys/net/ipv4/ip_forward<br />
iptables -t nat -A POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
;;<br />
stop)<br />
echo -n "Stopping VDE network for QEMU: "<br />
# Delete the NAT rules<br />
iptables -t nat -D POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
<br />
# Bring tap interface down<br />
ip link set "$TAP_DEV" down<br />
<br />
# Kill VDE switch<br />
pgrep vde_switch | xargs kill -TERM<br />
;;<br />
restart|reload)<br />
$0 stop<br />
sleep 1<br />
$0 start<br />
;;<br />
*)<br />
echo "Usage: $0 {start|stop|restart|reload}"<br />
exit 1<br />
esac<br />
exit 0<br />
</nowiki>}}<br />
<br />
Example of systemd service using the above script:<br />
<br />
{{hc|/etc/systemd/system/qemu-network-env.service|<nowiki><br />
[Unit]<br />
Description=Manage VDE Switch<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/etc/systemd/scripts/qemu-network-env start<br />
ExecStop=/etc/systemd/scripts/qemu-network-env stop<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
Change permissions for {{ic|qemu-network-env}} to be executable<br />
<br />
# chmod u+x /etc/systemd/scripts/qemu-network-env<br />
<br />
You can [[start]] {{ic|qemu-network-env.service}} as usual.<br />
<br />
====Alternative method====<br />
<br />
If the above method does not work or you do not want to mess with kernel configs, TUN, dnsmasq, and iptables you can do the following for the same result.<br />
<br />
# vde_switch -daemon -mod 660 -group users<br />
# slirpvde --dhcp --daemon<br />
<br />
Then, to start the VM with a connection to the network of the host:<br />
<br />
$ qemu-system-x86_64 -net nic,macaddr=52:54:00:00:EE:03 -net vde ''disk_image''<br />
<br />
=== VDE2 Bridge ===<br />
<br />
Based on [https://selamatpagicikgu.wordpress.com/2011/06/08/quickhowto-qemu-networking-using-vde-tuntap-and-bridge/ quickhowto: qemu networking using vde, tun/tap, and bridge] graphic. Any virtual machine connected to vde is externally exposed. For example, each virtual machine can receive DHCP configuration directly from your ADSL router.<br />
<br />
==== Basics ====<br />
<br />
Remember that you need {{ic|tun}} module and {{Pkg|bridge-utils}} package.<br />
<br />
Create the vde2/tap device:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
# ip link set tap0 up<br />
<br />
Create bridge:<br />
<br />
# brctl addbr br0<br />
<br />
Add devices:<br />
<br />
# brctl addif br0 eth0<br />
# brctl addif br0 tap0<br />
<br />
And configure bridge interface:<br />
<br />
# dhcpcd br0<br />
<br />
==== Startup scripts ====<br />
<br />
All devices must be set up. And only the bridge needs an IP address. For physical devices on the bridge (e.g. {{ic|eth0}}), this can be done with [[netctl]] using a custom Ethernet profile with:<br />
<br />
{{hc|/etc/netctl/ethernet-noip|2=<br />
Description='A more versatile static Ethernet connection'<br />
Interface=eth0<br />
Connection=ethernet<br />
IP=no<br />
}}<br />
<br />
The following custom systemd service can be used to create and activate a VDE2 tap interface for use in the {{ic|users}} user group.<br />
<br />
{{hc|/etc/systemd/system/vde2@.service|2=<br />
[Unit]<br />
Description=Network Connectivity for %i<br />
Wants=network.target<br />
Before=network.target<br />
<br />
[Service]<br />
Type=oneshot<br />
RemainAfterExit=yes<br />
ExecStart=/usr/bin/vde_switch -tap %i -daemon -mod 660 -group users<br />
ExecStart=/usr/bin/ip link set dev %i up<br />
ExecStop=/usr/bin/ip addr flush dev %i<br />
ExecStop=/usr/bin/ip link set dev %i down<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
}}<br />
<br />
And finally, you can create the [[Bridge with netctl|bridge interface with netctl]].<br />
<br />
=== Shorthand configuration ===<br />
<br />
If you are using QEMU with various networking options a lot, you probably have created a lot of {{ic|-netdev}} and {{ic|-device}} argument pairs, which gets quite repetitive. You can instead use the {{ic|-nic}} argument to combine {{ic|-netdev}} and {{ic|-device}} together, so that, for example, these arguments:<br />
<br />
-netdev tap,id=network0,ifname=tap0,script=no,downscript=no,vhost=on -device virtio-net-pci,netdev=network0<br />
<br />
become:<br />
<br />
-nic tap,script=no,downscript=no,vhost=on,model=virtio-net-pci<br />
<br />
Notice the lack of network IDs, and that the device was created with {{ic|1=model=}}. The first half of the {{ic|-nic}} parameters are {{ic|-netdev}} parameters, whereas the second half (after {{ic|1=model=}}) are related with the device. The same parameters (for example, {{ic|1=smb=}}) are used. To completely disable the networking use {{ic|-nic none}}.<br />
<br />
See [https://qemu.weilnetz.de/doc/qemu-doc.html#Network-options QEMU networking documentation] for more information on parameters you can use.<br />
<br />
== Graphic card ==<br />
<br />
QEMU can emulate a standard graphic card text mode using {{ic|-curses}} command line option. This allows to type text and see text output directly inside a text terminal.<br />
<br />
QEMU can emulate several types of VGA card. The card type is passed in the {{ic|-vga ''type''}} command line option and can be {{ic|std}}, {{ic|qxl}}, {{ic|vmware}}, {{ic|virtio}}, {{ic|cirrus}} or {{ic|none}}.<br />
<br />
=== std ===<br />
<br />
With {{ic|-vga std}} you can get a resolution of up to 2560 x 1600 pixels without requiring guest drivers. This is the default since QEMU 2.2.<br />
<br />
=== qxl ===<br />
<br />
QXL is a paravirtual graphics driver with 2D support. To use it, pass the {{ic|-vga qxl}} option and install drivers in the guest. You may want to use [[#SPICE]] for improved graphical performance when using QXL.<br />
<br />
On Linux guests, the {{ic|qxl}} and {{ic|bochs_drm}} kernel modules must be loaded in order to gain a decent performance.<br />
<br />
Default VGA memory size for QXL devices is 16M which is sufficient to drive resolutions approximately up to QHD (2560x1440). To enable higher resolutions, [[#Multi-monitor support|increase vga_memmb]].<br />
<br />
=== vmware ===<br />
<br />
Although it is a bit buggy, it performs better than std and cirrus. Install the VMware drivers {{Pkg|xf86-video-vmware}} and {{Pkg|xf86-input-vmmouse}} for Arch Linux guests.<br />
<br />
=== virtio ===<br />
<br />
{{ic|virtio-vga}} / {{ic|virtio-gpu}} is a paravirtual 3D graphics driver based on [https://virgil3d.github.io/ virgl]. Currently a work in progress, supporting only very recent (>= 4.4) Linux guests with {{Pkg|mesa}} (>=11.2) compiled with the option {{ic|1=gallium-drivers=virgl}}.<br />
<br />
To enable 3D acceleration on the guest system select this vga with {{ic|-vga virtio}} and enable the opengl context in the display device with {{ic|1=-display sdl,gl=on}} or {{ic|1=-display gtk,gl=on}} for the sdl and gtk display output respectively. Successful configuration can be confirmed looking at the kernel log in the guest:<br />
<br />
{{hc|$ dmesg {{!}} grep drm |<br />
[drm] pci: virtio-vga detected<br />
[drm] virgl 3d acceleration enabled<br />
}}<br />
<br />
=== cirrus ===<br />
<br />
The cirrus graphical adapter was the default [http://wiki.qemu.org/ChangeLog/2.2#VGA before 2.2]. It [https://www.kraxel.org/blog/2014/10/qemu-using-cirrus-considered-harmful/ should not] be used on modern systems.<br />
<br />
=== none ===<br />
<br />
This is like a PC that has no VGA card at all. You would not even be able to access it with the {{ic|-vnc}} option. Also, this is different from the {{ic|-nographic}} option which lets QEMU emulate a VGA card, but disables the SDL display.<br />
<br />
== SPICE ==<br />
The [http://spice-space.org/ SPICE project] aims to provide a complete open source solution for remote access to virtual machines in a seamless way.<br />
=== Enabling SPICE support on the host ===<br />
The following is an example of booting with SPICE as the remote desktop protocol, including the support for copy and paste from host:<br />
<br />
$ qemu-system-x86_64 -vga qxl -device virtio-serial-pci -spice port=5930,disable-ticketing -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
The parameters have the following meaning:<br />
<br />
# {{ic|-device virtio-serial-pci}} adds a virtio-serial device<br />
# {{ic|1=-spice port=5930,disable-ticketing}} set TCP port {{ic|5930}} for spice channels listening and allow client to connect without authentication{{Tip|Using [[wikipedia:Unix_socket|Unix sockets]] instead of TCP ports does not involve using network stack on the host system. It does not imply that packets are encapsulated and decapsulated to use the network and the related protocol. The sockets are identified solely by the inodes on the hard drive. It is therefore considered better for performance. Use instead {{ic|1=-spice unix,addr=/tmp/vm_spice.socket,disable-ticketing}}.}}<br />
# {{ic|1=-device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0}} opens a port for spice vdagent in the virtio-serial device,<br />
# {{ic|1=-chardev spicevmc,id=spicechannel0,name=vdagent}} adds a spicevmc chardev for that port. It is important that the {{ic|1=chardev=}} option of the {{ic|virtserialport}} device matches the {{ic|1=id=}} option given to the {{ic|chardev}} option ({{ic|spicechannel0}} in this example). It is also important that the port name is {{ic|com.redhat.spice.0}}, because that is the namespace where vdagent is looking for in the guest. And finally, specify {{ic|1=name=vdagent}} so that spice knows what this channel is for.<br />
<br />
=== Connecting to the guest with a SPICE client ===<br />
<br />
A SPICE client is necessary to connect to the guest. In Arch, the following clients are available:<br />
<br />
{{App|virt-viewer|SPICE client recommended by the protocol developers, a subset of the virt-manager project.|https://virt-manager.org/|{{Pkg|virt-viewer}}}}<br />
<br />
{{App|spice-gtk|SPICE GTK client, a subset of the SPICE project. Embedded into other applications as a widget.|https://www.spice-space.org/|{{Pkg|spice-gtk}}}}<br />
<br />
For clients that run on smartphone or on other platforms, refer to the ''Other clients'' section in [http://www.spice-space.org/download.html spice-space download].<br />
<br />
==== Manually running a SPICE client ====<br />
<br />
One way of connecting to a guest listening on Unix socket {{ic|/tmp/vm_spice.socket}} is to manually run the SPICE client using {{ic|$ remote-viewer spice+unix:///tmp/vm_spice.socket}} or {{ic|1=$ spicy --uri="spice+unix:///tmp/vm_spice.socket"}}, depending on the desired client. Since QEMU in SPICE mode acts similarly to a remote desktop server, it may be more convenient to run QEMU in daemon mode with the {{ic|-daemonize}} parameter.<br />
<br />
{{Tip|To connect to the guest through SSH tunelling, the following type of command can be used: {{bc|$ ssh -fL 5999:localhost:5930 ''my.domain.org'' sleep 10; spicy -h 127.0.0.1 -p 5999}}<br />
This example connects ''spicy'' to the local port {{ic|5999}} which is forwarded through SSH to the guest's SPICE server located at the address ''my.domain.org'', port {{ic|5930}}.<br />
Note the {{ic|-f}} option that requests ssh to execute the command {{ic|sleep 10}} in the background. This way, the ssh session runs while the client is active and auto-closes once the client ends.<br />
}}<br />
<br />
==== Running a SPICE client with QEMU ====<br />
<br />
QEMU can automatically start a SPICE client with an appropriate socket, if the display is set to SPICE with the {{ic|-display spice-app}} parameter. This will use the system's default SPICE client as the viewer, determined by your [[XDG_MIME_Applications#mimeapps.list|mimeapps.list]] files.<br />
<br />
=== Enabling SPICE support on the guest ===<br />
<br />
For '''Arch Linux guests''', for improved support for multiple monitors or clipboard sharing, the following packages should be installed:<br />
* {{Pkg|spice-vdagent}}: Spice agent xorg client that enables copy and paste between client and X-session and more.<br />
* {{Pkg|xf86-video-qxl}}: Xorg X11 qxl video driver<br />
For guests under '''other operating systems''', refer to the ''Guest'' section in [http://www.spice-space.org/download.html spice-space download].<br />
<br />
=== Password authentication with SPICE ===<br />
<br />
If you want to enable password authentication with SPICE you need to remove {{ic|disable-ticketing}} from the {{ic|-spice}} argument and instead add {{ic|1=password=''yourpassword''}}. For example:<br />
<br />
$ qemu-system-x86_64 -vga qxl -spice port=5900,password=''yourpassword'' -device virtio-serial-pci -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
Your SPICE client should now ask for the password to be able to connect to the SPICE server.<br />
<br />
=== TLS encrypted communication with SPICE ===<br />
<br />
You can also configure TLS encryption for communicating with the SPICE server. First, you need to have a directory which contains the following files (the names must be exactly as indicated):<br />
<br />
* {{ic|ca-cert.pem}}: the CA master certificate.<br />
* {{ic|server-cert.pem}}: the server certificate signed with {{ic|ca-cert.pem}}.<br />
* {{ic|server-key.pem}}: the server private key.<br />
<br />
An example of generation of self-signed certificates with your own generated CA for your server is shown in the [https://www.spice-space.org/spice-user-manual.html#_generating_self_signed_certificates Spice User Manual].<br />
<br />
Afterwards, you can run QEMU with SPICE as explained above but using the following {{ic|-spice}} argument: {{ic|1=-spice tls-port=5901,password=''yourpassword'',x509-dir=''/path/to/pki_certs''}}, where {{ic|''/path/to/pki_certs''}} is the directory path that contains the three needed files shown earlier.<br />
<br />
It is now possible to connect to the server using {{pkg|virt-viewer}}:<br />
<br />
$ remote-viewer spice://''hostname''?tls-port=5901 --spice-ca-file=''/path/to/ca-cert.pem'' --spice-host-subject="C=''XX'',L=''city'',O=''organization'',CN=''hostname''" --spice-secure-channels=all<br />
<br />
Keep in mind that the {{ic|--spice-host-subject}} parameter needs to be set according to your {{ic|server-cert.pem}} subject. You also need to copy {{ic|ca-cert.pem}} to every client to verify the server certificate.<br />
<br />
{{Tip|You can get the subject line of the server certificate in the correct format for {{ic|--spice-host-subject}} (with entries separated by commas) using the following command: {{bc|<nowiki>$ openssl x509 -noout -subject -in server-cert.pem | cut -d' ' -f2- | sed 's/\///' | sed 's/\//,/g'</nowiki>}}<br />
}}<br />
<br />
The equivalent {{Pkg|spice-gtk}} command is:<br />
<br />
$ spicy -h ''hostname'' -s 5901 --spice-ca-file=ca-cert.pem --spice-host-subject="C=''XX'',L=''city'',O=''organization'',CN=''hostname''" --spice-secure-channels=all<br />
<br />
== VNC ==<br />
<br />
One can add the {{ic|-vnc :''X''}} option to have QEMU redirect the VGA display to the VNC session. Substitute {{ic|''X''}} for the number of the display (0 will then listen on 5900, 1 on 5901...).<br />
<br />
$ qemu-system-x86_64 -vnc :0<br />
<br />
An example is also provided in the [[#Starting QEMU virtual machines on boot]] section.<br />
{{Warning|The default VNC server setup does not use any form of authentication. Any user can connect from any host.}}<br />
<br />
=== Basic password authentication ===<br />
<br />
An access password can be setup easily by using the {{ic|password}} option. The password must be indicated in the QEMU monitor and connection is only possible once the password is provided.<br />
<br />
$ qemu-system-x86_64 -vnc :0,password -monitor stdio<br />
<br />
In the QEMU monitor, password is set using the command {{ic|change vnc password}} and then indicating the password.<br />
<br />
The following command line directly runs vnc with a password:<br />
<br />
$ printf "change vnc password\n%s\n" MYPASSWORD | qemu-system-x86_64 -vnc :0,password -monitor stdio<br />
<br />
{{Note|The password is limited to 8 characters and can be guessed through brute force attack. More elaborated protection is strongly recommended for public network.}}<br />
<br />
== Audio ==<br />
<br />
=== Host ===<br />
<br />
The {{ic|-audiodev}} flag sets the audio backend driver and its options. The list of available audio backend drivers and their optional settings is detailed in the {{man|1|qemu}}. man page.<br />
<br />
At the bare minimum, you need to choose a driver and set an id.<br />
<br />
-audiodev pa,id=snd0<br />
<br />
=== Guest ===<br />
<br />
==== With audiodev ====<br />
<br />
===== Intel HD Audio =====<br />
<br />
For Intel HD Audio emulation add both controller and codec devices. To list the available Intel HDA Audio devices:<br />
<br />
$ qemu-system-x86_64 -device help | grep hda<br />
<br />
Add the audio controller<br />
<br />
-device ich9-intel-hda<br />
<br />
Add the audio codec and map it to a host audio backend id<br />
<br />
-device hda-output,audiodev=snd0<br />
<br />
===== Intel 82801AA AC97 =====<br />
<br />
For AC97 emulation just add the audio card device and map it to a host audio backend id<br />
<br />
-device AC97,audiodev=snd0<br />
<br />
==== Without audiodev ====<br />
<br />
To get list of the supported emulation audio drivers:<br />
$ qemu-system-x86_64 -soundhw help<br />
<br />
To use e.g. {{ic|hda}} driver for the guest use the {{ic|-device intel-hda -device hda-duplex}} command with QEMU.<br />
<br />
{{Note|Video graphic card emulated drivers for the guest machine may also cause a problem with the sound quality. Test one by one to make it work. You can list possible options with {{ic|<nowiki>qemu-system-x86_64 -h | grep vga</nowiki>}}.}}<br />
<br />
== Installing virtio drivers ==<br />
<br />
QEMU offers guests the ability to use paravirtualized block and network devices using the [http://wiki.libvirt.org/page/Virtio virtio] drivers, which provide better performance and lower overhead.<br />
<br />
* A virtio block device requires the option {{Ic|-drive}} for passing a disk image, with parameter {{Ic|1=if=virtio}}:<br />
$ qemu-system-x86_64 -boot order=c -drive file=''disk_image'',if=virtio<br />
<br />
* Almost the same goes for the network:<br />
$ qemu-system-x86_64 -nic user,model=virtio-net-pci<br />
<br />
{{Note|This will only work if the guest machine has drivers for virtio devices. Linux does, and the required drivers are included in Arch Linux, but there is no guarantee that virtio devices will work with other operating systems.}}<br />
<br />
=== Preparing an (Arch) Linux guest ===<br />
<br />
To use virtio devices after an Arch Linux guest has been installed, the following modules must be loaded in the guest: {{Ic|virtio}}, {{Ic|virtio_pci}}, {{Ic|virtio_blk}}, {{Ic|virtio_net}}, and {{Ic|virtio_ring}}. For 32-bit guests, the specific "virtio" module is not necessary.<br />
<br />
If you want to boot from a virtio disk, the initial ramdisk must contain the necessary modules. By default, this is handled by [[mkinitcpio]]'s {{ic|autodetect}} hook. Otherwise use the {{ic|MODULES}} array in {{ic|/etc/mkinitcpio.conf}} to include the necessary modules and rebuild the initial ramdisk.<br />
<br />
{{hc|/etc/mkinitcpio.conf|2=<br />
MODULES=(virtio virtio_blk virtio_pci virtio_net)}}<br />
<br />
Virtio disks are recognized with the prefix {{ic|'''v'''}} (e.g. {{ic|'''v'''da}}, {{ic|'''v'''db}}, etc.); therefore, changes must be made in at least {{ic|/etc/fstab}} and {{ic|/boot/grub/grub.cfg}} when booting from a virtio disk.<br />
<br />
{{Tip|When referencing disks by [[UUID]] in both {{ic|/etc/fstab}} and bootloader, nothing has to be done.}}<br />
<br />
Further information on paravirtualization with KVM can be found [http://www.linux-kvm.org/page/Boot_from_virtio_block_device here].<br />
<br />
You might also want to install {{Pkg|qemu-guest-agent}} to implement support for QMP commands that will enhance the hypervisor management capabilities. After installing the package you can enable and start the {{ic|qemu-ga.service}}.<br />
<br />
=== Preparing a Windows guest ===<br />
<br />
==== Block device drivers ====<br />
<br />
===== New Install of Windows =====<br />
<br />
Windows does not come with the virtio drivers. Therefore, you will need to load them during installation. There are basically two ways to do this: via Floppy Disk or via ISO files. Both images can be downloaded from the [https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/stable-virtio/virtio-win.iso Fedora repository].<br />
<br />
The floppy disk option is difficult because you will need to press F6 (Shift-F6 on newer Windows) at the very beginning of powering on the QEMU. This is difficult since you need time to connect your VNC console window. You can attempt to add a delay to the boot sequence. See {{man|1|qemu}} for more details about applying a delay at boot.<br />
<br />
The ISO option to load drivers is the preferred way, but it is available only on Windows Vista and Windows Server 2008 and later. The procedure is to load the image with virtio drivers in an additional cdrom device along with the primary disk device and Windows installer:<br />
<br />
$ qemu-system-x86_64 ... \<br />
-drive file=''windows_disk_image'',index=0,media=disk,if=virtio \<br />
-drive file=''windows.iso'',index=2,media=cdrom \<br />
-drive file=''virtio.iso'',index=3,media=cdrom \<br />
...<br />
<br />
During the installation, at some stage, the Windows installer will ask "Where do you want to install Windows?", it will give a warning that no disks are found. Follow the example instructions below (based on Windows Server 2012 R2 with Update).<br />
<br />
* Select the option ''Load Drivers''.<br />
* Uncheck the box for ''Hide drivers that aren't compatible with this computer's hardware''.<br />
* Click the browse button and open the CDROM for the virtio iso, usually named "virtio-win-XX".<br />
* Now browse to {{ic|E:\viostor\[your-os]\amd64}}, select it, and confirm.<br />
<br />
You should now see your virtio disk(s) listed here, ready to be selected, formatted and installed to.<br />
<br />
===== Change Existing Windows VM to use virtio =====<br />
<br />
Modifying an existing Windows guest for booting from virtio disk requires that the virtio driver is available in the guest and that it is loaded at boot time.<br />
<br />
One can find the virtio disk driver in the [https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/stable-virtio/virtio-win.iso Fedora repository].<br />
<br />
Now, create a new disk image that will be used to search for the virtio driver:<br />
<br />
$ qemu-img create -f qcow2 ''fake.qcow2'' 1G<br />
<br />
Run the original Windows guest (with the boot disk still in IDE mode) with the fake disk (in virtio mode) and a CD-ROM with the driver.<br />
<br />
$ qemu-system-x86_64 -m 512 -drive file=''windows_disk_image'',if=ide -drive file=''fake.qcow2'',if=virtio -cdrom virtio-win-0.1-81.iso<br />
<br />
Windows will detect the fake disk and look for a suitable driver. If it fails, go to ''Device Manager'', locate the SCSI drive with an exclamation mark icon (should be open), click ''Update driver'' and select the virtual CD-ROM. Do not navigate to the driver folder within the CD-ROM, simply select the CD-ROM drive and Windows will find the appropriate driver automatically (tested for Windows 7 SP1).<br />
<br />
Request Windows to boot in safe mode next time it starts up. This can be done using the ''msconfig.exe'' tool in Windows. In safe mode all the drivers will be loaded at boot time including the new virtio driver. Once Windows knows that the virtio driver is required at boot it will memorize it for future boot.<br />
<br />
Once instructed to boot in safe mode, you can turn off the virtual machine and launch it again, now with the boot disk attached in virtio mode:<br />
<br />
$ qemu-system-x86_64 -m 512 -drive file=''windows_disk_image'',if=virtio<br />
<br />
You should boot in safe mode with virtio driver loaded, you can now return to ''msconfig.exe'' disable safe mode boot and restart Windows.<br />
<br />
{{Note|If you encounter the blue screen of death using the {{ic|1=if=virtio}} parameter, it probably means the virtio disk driver is not installed or not loaded at boot time, reboot in safe mode and check your driver configuration.}}<br />
<br />
==== Network drivers ====<br />
<br />
Installing virtio network drivers is a bit easier, simply add the {{ic|-nic}} argument.<br />
<br />
$ qemu-system-x86_64 -m 512 -drive file=''windows_disk_image'',if=virtio -nic user,model=virtio-net-pci -cdrom virtio-win-0.1-74.iso<br />
<br />
Windows will detect the network adapter and try to find a driver for it. If it fails, go to the ''Device Manager'', locate the network adapter with an exclamation mark icon (should be open), click ''Update driver'' and select the virtual CD-ROM. Do not forget to select the checkbox which says to search for directories recursively.<br />
<br />
==== Balloon driver ====<br />
<br />
If you want to track you guest memory state (for example via {{ic|virsh}} command {{ic|dommemstat}}) or change guest's memory size in runtime (you still will not be able to change memory size, but can limit memory usage via inflating balloon driver) you will need to install guest balloon driver.<br />
<br />
For this you will need to go to ''Device Manager'', locate ''PCI standard RAM Controller'' in ''System devices'' (or unrecognized PCI controller from ''Other devices'') and choose ''Update driver''. In opened window you will need to choose ''Browse my computer...'' and select the CD-ROM (and do not forget the ''Include subdirectories'' checkbox). Reboot after installation. This will install the driver and you will be able to inflate the balloon (for example via hmp command {{ic|balloon ''memory_size''}}, which will cause balloon to take as much memory as possible in order to shrink the guest's available memory size to ''memory_size''). However, you still will not be able to track guest memory state. In order to do this you will need to install ''Balloon'' service properly. For that open command line as administrator, go to the CD-ROM, ''Balloon'' directory and deeper, depending on your system and architecture. Once you are in ''amd64'' (''x86'') directory, run {{ic|blnsrv.exe -i}} which will do the installation. After that {{ic|virsh}} command {{ic|dommemstat}} should be outputting all supported values.<br />
<br />
=== Preparing a FreeBSD guest ===<br />
<br />
Install the {{ic|emulators/virtio-kmod}} port if you are using FreeBSD 8.3 or later up until 10.0-CURRENT where they are included into the kernel. After installation, add the following to your {{ic|/boot/loader.conf}} file:<br />
<br />
{{bc|1=<br />
virtio_load="YES"<br />
virtio_pci_load="YES"<br />
virtio_blk_load="YES"<br />
if_vtnet_load="YES"<br />
virtio_balloon_load="YES"<br />
}}<br />
<br />
Then modify your {{ic|/etc/fstab}} by doing the following:<br />
<br />
# sed -ibak "s/ada/vtbd/g" /etc/fstab<br />
<br />
And verify that {{ic|/etc/fstab}} is consistent. If anything goes wrong, just boot into a rescue CD and copy {{ic|/etc/fstab.bak}} back to {{ic|/etc/fstab}}.<br />
<br />
== QEMU monitor ==<br />
<br />
While QEMU is running, a monitor console is provided in order to provide several ways to interact with the virtual machine running. The QEMU monitor offers interesting capabilities such as obtaining information about the current virtual machine, hotplugging devices, creating snapshots of the current state of the virtual machine, etc. To see the list of all commands, run {{ic|help}} or {{ic|?}} in the QEMU monitor console or review the relevant section of the [https://qemu.weilnetz.de/doc/qemu-doc.html#pcsys_005fmonitor official QEMU documentation].<br />
<br />
=== Accessing the monitor console ===<br />
<br />
==== Graphical view ====<br />
<br />
When using the {{ic|std}} default graphics option, one can access the QEMU monitor by pressing {{ic|Ctrl+Alt+2}} or by clicking ''View > compatmonitor0'' in the QEMU window. To return to the virtual machine graphical view either press {{ic|Ctrl+Alt+1}} or click ''View > VGA''.<br />
<br />
However, the standard method of accessing the monitor is not always convenient and does not work in all graphic outputs QEMU supports.<br />
<br />
==== Telnet ====<br />
<br />
To enable [[telnet]], run QEMU with the {{ic|-monitor telnet:127.0.0.1:''port'',server,nowait}} parameter. When the virtual machine is started you will be able to access the monitor via telnet:<br />
<br />
$ telnet 127.0.0.1 ''port''<br />
<br />
{{Note|If {{ic|127.0.0.1}} is specified as the IP to listen it will be only possible to connect to the monitor from the same host QEMU is running on. If connecting from remote hosts is desired, QEMU must be told to listen {{ic|0.0.0.0}} as follows: {{ic|-monitor telnet:0.0.0.0:''port'',server,nowait}}. Keep in mind that it is recommended to have a [[firewall]] configured in this case or make sure your local network is completely trustworthy since this connection is completely unauthenticated and unencrypted.}}<br />
<br />
==== UNIX socket ====<br />
<br />
Run QEMU with the {{ic|-monitor unix:''socketfile'',server,nowait}} parameter. Then you can connect with either {{pkg|socat}} or {{pkg|openbsd-netcat}}.<br />
<br />
For example, if QEMU is run via:<br />
<br />
$ qemu-system-x86_64 ''[...]'' -monitor unix:/tmp/monitor.sock,server,nowait ''[...]''<br />
<br />
It is possible to connect to the monitor with:<br />
<br />
$ socat - UNIX-CONNECT:/tmp/monitor.sock<br />
<br />
Or with:<br />
<br />
$ nc -U /tmp/monitor.sock<br />
<br />
==== TCP ====<br />
<br />
You can expose the monitor over TCP with the argument {{ic|-monitor tcp:127.0.0.1:''port'',server,nowait}}. Then connect with netcat, either {{pkg|openbsd-netcat}} or {{pkg|gnu-netcat}} by running:<br />
<br />
$ nc 127.0.0.1 ''port''<br />
<br />
{{Note|In order to be able to connect to the tcp socket from other devices other than the same host QEMU is being run on you need to listen to {{ic|0.0.0.0}} like explained in the telnet case. The same security warnings apply in this case as well.}}<br />
<br />
==== Standard I/O ====<br />
<br />
It is possible to access the monitor automatically from the same terminal QEMU is being run by running it with the argument {{ic|-monitor stdio}}.<br />
<br />
=== Sending keyboard presses to the virtual machine using the monitor console ===<br />
<br />
Some combinations of keys may be difficult to perform on virtual machines due to the host intercepting them instead in some configurations (a notable example is the {{ic|Ctrl+Alt+F*}} key combinations, which change the active tty). To avoid this problem, the problematic combination of keys may be sent via the monitor console instead. Switch to the monitor and use the {{ic|sendkey}} command to forward the necessary keypresses to the virtual machine. For example:<br />
<br />
(qemu) sendkey ctrl-alt-f2<br />
<br />
=== Creating and managing snapshots via the monitor console ===<br />
<br />
{{Note|This feature will '''only''' work when the virtual machine disk image is in ''qcow2'' format. It will not work with ''raw'' images.}}<br />
<br />
It is sometimes desirable to save the current state of a virtual machine and having the possibility of reverting the state of the virtual machine to that of a previously saved snapshot at any time. The QEMU monitor console provides the user with the necessary utilities to create snapshots, manage them, and revert the machine state to a saved snapshot.<br />
<br />
* Use {{ic|savevm ''name''}} in order to create a snapshot with the tag ''name''.<br />
* Use {{ic|loadvm ''name''}} to revert the virtual machine to the state of the snapshot ''name''.<br />
* Use {{ic|delvm ''name''}} to delete the snapshot tagged as ''name''.<br />
* Use {{ic|info snapshots}} to see a list of saved snapshots. Snapshots are identified by both an auto-incremented ID number and a text tag (set by the user on snapshot creation).<br />
<br />
=== Running the virtual machine in immutable mode ===<br />
<br />
It is possible to run a virtual machine in a frozen state so that all changes will be discarded when the virtual machine is powered off just by running QEMU with the {{ic|-snapshot}} parameter. When the disk image is written by the guest, changes will be saved in a temporary file in {{ic|/tmp}} and will be discarded when QEMU halts.<br />
<br />
However, if a machine is running in frozen mode it is still possible to save the changes to the disk image if it is afterwards desired by using the monitor console and running the following command:<br />
<br />
(qemu) commit all<br />
<br />
If snapshots are created when running in frozen mode they will be discarded as soon as QEMU is exited unless changes are explicitly commited to disk, as well.<br />
<br />
=== Pause and power options via the monitor console ===<br />
<br />
Some operations of a physical machine can be emulated by QEMU using some monitor commands:<br />
<br />
* {{ic|system_powerdown}} will send an ACPI shutdown request to the virtual machine. This effect is similar to the power button in a physical machine.<br />
* {{ic|system_reset}} will reset the virtual machine similarly to a reset button in a physical machine. This operation can cause data loss and file system corruption since the virtual machine is not cleanly restarted.<br />
* {{ic|stop}} will pause the virtual machine.<br />
* {{ic|cont}} will resume a virtual machine previously paused.<br />
<br />
=== Taking screenshots of the virtual machine ===<br />
<br />
Screenshots of the virtual machine graphic display can be obtained in the PPM format by running the following command in the monitor console:<br />
<br />
(qemu) screendump ''file.ppm''<br />
<br />
== QEMU machine protocol ==<br />
<br />
The QEMU machine protocol (QMP) is a JSON-based protocol which allows applications to control a QEMU instance. Similarly to the [[#QEMU monitor]] it offers ways to interact with a running machine and the JSON protocol allows to do it programmatically. The description of all the QMP commands can be found in [https://raw.githubusercontent.com/coreos/qemu/master/qmp-commands.hx qmp-commands].<br />
<br />
=== Start QMP ===<br />
<br />
The usual way to control the guest using the QMP protocol, is to open a TCP socket when launching the machine using the {{ic|-qmp}} option. Here it is using for example the TCP port 4444:<br />
<br />
$ qemu-system-x86_64 ''[...]'' -qmp tcp:localhost:4444,server,nowait<br />
<br />
Then one way to communicate with the QMP agent is to use [[netcat]]:<br />
<br />
{{hc|nc localhost 4444|{"QMP": {"version": {"qemu": {"micro": 0, "minor": 1, "major": 3}, "package": ""}, "capabilities": []} } }}<br />
<br />
At this stage, the only command that can be recognized is {{ic|qmp_capabilities}}, so that QMP enters into command mode. Type:<br />
<br />
{"execute": "qmp_capabilities"}<br />
<br />
Now, QMP is ready to receive commands, to retrieve the list of recognized commands, use:<br />
<br />
{"execute": "query-commands"}<br />
<br />
=== Live merging of child image into parent image ===<br />
<br />
It is possible to merge a running snapshot into its parent by issuing a {{ic|block-commit}} command. In its simplest form the following line will commit the child into its parent:<br />
<br />
{"execute": "block-commit", "arguments": {"device": "''devicename''"}}<br />
<br />
Upon reception of this command, the handler looks for the base image and converts it from read only to read write mode and then runs the commit job.<br />
<br />
Once the ''block-commit'' operation has completed, the event {{ic|BLOCK_JOB_READY}} will be emitted, signalling that the synchronization has finished. The job can then be gracefully completed by issuing the command {{ic|block-job-complete}}:<br />
<br />
{"execute": "block-job-complete", "arguments": {"device": "''devicename''"}}<br />
<br />
Until such a command is issued, the ''commit'' operation remains active.<br />
After successful completion, the base image remains in read write mode and becomes the new active layer. On the other hand, the child image becomes invalid and it is the responsibility of the user to clean it up.<br />
<br />
{{Tip|The list of device and their names can be retrieved by executing the command {{ic|query-block}} and parsing the results. The device name is in the {{ic|device}} field, for example {{ic|ide0-hd0}} for the hard disk in this example: {{hc|{"execute": "query-block"}|{"return": [{"io-status": "ok", "device": "'''ide0-hd0'''", "locked": false, "removable": false, "inserted": {"iops_rd": 0, "detect_zeroes": "off", "image": {"backing-image": {"virtual-size": 27074281472, "filename": "parent.qcow2", ... } }} }}<br />
<br />
=== Live creation of a new snapshot ===<br />
<br />
To create a new snapshot out of a running image, run the command:<br />
<br />
{"execute": "blockdev-snapshot-sync", "arguments": {"device": "''devicename''","snapshot-file": "''new_snapshot_name''.qcow2"}}<br />
<br />
This creates an overlay file named {{ic|''new_snapshot_name''.qcow2}} which then becomes the new active layer.<br />
<br />
== Tips and tricks ==<br />
=== Improve virtual machine performance ===<br />
<br />
There are a number of techniques that you can use to improve the performance of the virtual machine. For example:<br />
<br />
* Apply [[#Enabling KVM]]: add {{ic|-enable-kvm}} to the QEMU start command you use.<br />
* Use the {{ic|-cpu host}} option to make QEMU emulate the host's exact CPU. If you do not do this, it may be trying to emulate a more generic CPU.<br />
* Especially for Windows guests, enable [http://blog.wikichoon.com/2014/07/enabling-hyper-v-enlightenments-with-kvm.html Hyper-V enlightenments]: {{ic|1=-cpu host,hv_relaxed,hv_spinlocks=0x1fff,hv_vapic,hv_time}}.<br />
* If the host machine has multiple cores, assign the guest more cores using the {{ic|-smp}} option.<br />
* Make sure you have assigned the virtual machine enough memory. By default, QEMU only assigns 128 MiB of memory to each virtual machine. Use the {{ic|-m}} option to assign more memory. For example, {{ic|-m 1024}} runs a virtual machine with 1024 MiB of memory.<br />
* If supported by drivers in the guest operating system, use [http://wiki.libvirt.org/page/Virtio virtio] for network and/or block devices. For example:<br />
$ qemu-system-x86_64 -net nic,model=virtio -net tap,if=tap0,script=no -drive file=''disk_image'',media=disk,if=virtio<br />
* Use TAP devices instead of user-mode networking. See [[#Tap networking with QEMU]].<br />
* If the guest OS is doing heavy writing to its disk, you may benefit from certain mount options on the host's file system. For example, you can mount an [[Ext4|ext4 file system]] with the option {{ic|1=barrier=0}}. You should read the documentation for any options that you change because sometimes performance-enhancing options for file systems come at the cost of data integrity.<br />
* If you have a raw disk image, you may want to disable the cache:<br />
$ qemu-system-x86_64 -drive file=''disk_image'',if=virtio,'''cache=none'''<br />
* Use the native Linux AIO:<br />
$ qemu-system-x86_64 -drive file=''disk_image'',if=virtio''',aio=native,cache.direct=on'''<br />
* If you are running multiple virtual machines concurrently that all have the same operating system installed, you can save memory by enabling [[wikipedia:Kernel_SamePage_Merging_(KSM)|kernel same-page merging]]. See [[#Enabling KSM]].<br />
* In some cases, memory can be reclaimed from running virtual machines by running a memory ballooning driver in the guest operating system and launching QEMU using {{ic|-device virtio-balloon}}.<br />
* It is possible to use a emulation layer for an ICH-9 AHCI controller (although it may be unstable). The AHCI emulation supports [[Wikipedia:Native_Command_Queuing|NCQ]], so multiple read or write requests can be outstanding at the same time:<br />
$ qemu-system-x86_64 -drive id=disk,file=''disk_image'',if=none -device ich9-ahci,id=ahci -device ide-drive,drive=disk,bus=ahci.0<br />
<br />
See http://www.linux-kvm.org/page/Tuning_KVM for more information.<br />
<br />
=== Starting QEMU virtual machines on boot ===<br />
<br />
==== With libvirt ====<br />
<br />
If a virtual machine is set up with [[libvirt]], it can be configured with {{ic|virsh autostart}} or through the ''virt-manager'' GUI to start at host boot by going to the Boot Options for the virtual machine and selecting "Start virtual machine on host boot up".<br />
<br />
==== With systemd service ====<br />
<br />
To run QEMU VMs on boot, you can use following systemd unit and config.<br />
<br />
{{hc|/etc/systemd/system/qemu@.service|2=<br />
[Unit]<br />
Description=QEMU virtual machine<br />
<br />
[Service]<br />
Environment="haltcmd=kill -INT $MAINPID"<br />
EnvironmentFile=/etc/conf.d/qemu.d/%i<br />
ExecStart=/usr/bin/qemu-system-x86_64 -name %i -enable-kvm -m 512 -nographic $args<br />
ExecStop=/usr/bin/bash -c ${haltcmd}<br />
ExecStop=/usr/bin/bash -c 'while nc localhost 7100; do sleep 1; done'<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
}}<br />
<br />
{{Note|This service will wait for the console port to be released, which means that the VM has been shutdown, to graciously end.}}<br />
<br />
Then create per-VM configuration files, named {{ic|/etc/conf.d/qemu.d/''vm_name''}}, with the variables {{ic|args}} and {{ic|haltcmd}} set. Example configs:<br />
<br />
{{hc|/etc/conf.d/qemu.d/one|2=<br />
args="-hda /dev/vg0/vm1 -serial telnet:localhost:7000,server,nowait,nodelay \<br />
-monitor telnet:localhost:7100,server,nowait,nodelay -vnc :0"<br />
<br />
haltcmd="echo 'system_powerdown' {{!}} nc localhost 7100" # or netcat/ncat}}<br />
<br />
{{hc|/etc/conf.d/qemu.d/two|2=<br />
args="-hda /srv/kvm/vm2 -serial telnet:localhost:7001,server,nowait,nodelay -vnc :1"<br />
<br />
haltcmd="ssh powermanager@vm2 sudo poweroff"}}<br />
<br />
The description of the variables is the following:<br />
<br />
* {{ic|args}} - QEMU command line arguments to be used.<br />
* {{ic|haltcmd}} - Command to shut down a VM safely. In the first example, the QEMU monitor is exposed via telnet using {{ic|-monitor telnet:..}} and the VMs are powered off via ACPI by sending {{ic|system_powerdown}} to monitor with the {{ic|nc}} command. In the other example, SSH is used.<br />
<br />
To set which virtual machines will start on boot-up, [[enable]] the {{ic|qemu@''vm_name''.service}} systemd unit.<br />
<br />
=== Mouse integration ===<br />
<br />
To prevent the mouse from being grabbed when clicking on the guest operating system's window, add the options {{ic|-usb -device usb-tablet}}. This means QEMU is able to report the mouse position without having to grab the mouse. This also overrides PS/2 mouse emulation when activated. For example:<br />
<br />
$ qemu-system-x86_64 -hda ''disk_image'' -m 512 -usb -device usb-tablet<br />
<br />
If that does not work, try using {{ic|-vga qxl}} parameter, also look at the instructions [[#Mouse cursor is jittery or erratic]].<br />
<br />
=== Pass-through host USB device ===<br />
<br />
It is possible to access the physical device connected to a USB port of the host from the guest. The first step is to identify where the device is connected, this can be found running the {{ic|lsusb}} command. For example:<br />
<br />
{{hc|$ lsusb|<br />
...<br />
Bus '''003''' Device '''007''': ID '''0781''':'''5406''' SanDisk Corp. Cruzer Micro U3<br />
}}<br />
<br />
The outputs in bold above will be useful to identify respectively the ''host_bus'' and ''host_addr'' or the ''vendor_id'' and ''product_id''.<br />
<br />
In qemu, the idea is to emulate an EHCI (USB 2) or XHCI (USB 3) controller with the option {{ic|1=-device usb-ehci,id=ehci}} or {{ic|1=-device qemu-xhci,id=xhci}} respectively and then attach the physical device to it with the option {{ic|1=-device usb-host,..}}. We will consider that ''controller_id'' is either {{ic|ehci}} or {{ic|xhci}} for the rest of this section.<br />
<br />
Then, there are two ways to connect to the USB of the host with qemu:<br />
<br />
# Identify the device and connect to it on any bus and address it is attached to on the host, the generic syntax is: {{bc|1=-device usb-host,bus=''controller_id''.0,vendorid=0x''vendor_id'',productid=0x''product_id''}}Applied to the device used in the example above, it becomes:{{bc|1=-device usb-ehci,id=ehci -device usb-host,bus=ehci.0,vendorid=0x'''0781''',productid=0x'''5406'''}}One can also add the {{ic|1=...,port=''port_number''}} setting to the previous option to specify in which physical port of the virtual controller the device should be attached, useful in the case one wants to add multiple usb devices to the VM. Another option is to use the new {{ic|hostdevice}} property of {{ic|usb-host}} which is available since this [https://git.qemu.org/?p=qemu.git;a=commit;h=9f815e83e983d247a3cd67579d2d9c1765adc644 commit] (QEMU 5.1.0+), the syntax is: {{bc|1=-device qemu-xhci,id=xhci -device usb-host,bus=xhci.0,hostdevice=/dev/bus/usb/003/007}}<br />
# Attach whatever is connected to a given USB bus and address, the syntax is:{{bc|1=-device usb-host,bus=''controller_id''.0,hostbus=''host_bus'',host_addr=''host_addr''}}Applied to the bus and the address in the example above, it becomes:{{bc|1=-device usb-ehci,id=ehci -device usb-host,bus=ehci.0,hostbus='''3''',hostaddr='''7'''}}<br />
<br />
{{Note|If you encounter permission errors when running QEMU, see [[udev#About udev rules]] for information on how to set permissions of the device.}}<br />
<br />
=== USB redirection with SPICE ===<br />
<br />
When using [[#SPICE]] it is possible to redirect USB devices from the client to the virtual machine without needing to specify them in the QEMU command. It is possible to configure the number of USB slots available for redirected devices (the number of slots will determine the maximum number of devices which can be redirected simultaneously). The main advantages of using SPICE for redirection compared to the previously-mentioned {{ic|-usbdevice}} method is the possibility of hot-swapping USB devices after the virtual machine has started, without needing to halt it in order to remove USB devices from the redirection or adding new ones. This method of USB redirection also allows us to redirect USB devices over the network, from the client to the server. In summary, it is the most flexible method of using USB devices in a QEMU virtual machine.<br />
<br />
We need to add one EHCI/UHCI controller per available USB redirection slot desired as well as one SPICE redirection channel per slot. For example, adding the following arguments to the QEMU command you use for starting the virtual machine in SPICE mode will start the virtual machine with three available USB slots for redirection:<br />
<br />
{{bc|1=-device ich9-usb-ehci1,id=usb \<br />
-device ich9-usb-uhci1,masterbus=usb.0,firstport=0,multifunction=on \<br />
-device ich9-usb-uhci2,masterbus=usb.0,firstport=2 \<br />
-device ich9-usb-uhci3,masterbus=usb.0,firstport=4 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev1 -device usb-redir,chardev=usbredirchardev1,id=usbredirdev1 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev2 -device usb-redir,chardev=usbredirchardev2,id=usbredirdev2 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev3 -device usb-redir,chardev=usbredirchardev3,id=usbredirdev3}}<br />
See [https://www.spice-space.org/usbredir.html SPICE/usbredir] for more information.<br />
<br />
Both {{ic|spicy}} from {{Pkg|spice-gtk}} (''Input > Select USB Devices for redirection'') and {{ic|remote-viewer}} from {{pkg|virt-viewer}} (''File > USB device selection'') support this feature. Please make sure that you have installed the necessary SPICE Guest Tools on the virtual machine for this functionality to work as expected (see the [[#SPICE]] section for more information).<br />
<br />
{{Warning|Keep in mind that when a USB device is redirected from the client, it will not be usable from the client operating system itself until the redirection is stopped. It is specially important to never redirect the input devices (namely mouse and keyboard), since it will be then difficult to access the SPICE client menus to revert the situation, because the client will not respond to the input devices after being redirected to the virtual machine.}}<br />
<br />
=== Enabling KSM ===<br />
<br />
Kernel Samepage Merging (KSM) is a feature of the Linux kernel that allows for an application to register with the kernel to have its pages merged with other processes that also register to have their pages merged. The KSM mechanism allows for guest virtual machines to share pages with each other. In an environment where many of the guest operating systems are similar, this can result in significant memory savings.<br />
<br />
{{Note|Although KSM may reduce memory usage, it may increase CPU usage. Also note some security issues may occur, see [[Wikipedia:Kernel same-page merging]].}}<br />
<br />
To enable KSM:<br />
<br />
# echo 1 > /sys/kernel/mm/ksm/run<br />
<br />
To make it permanent, use [[systemd#systemd-tmpfiles - temporary files|systemd's temporary files]]:<br />
<br />
{{hc|/etc/tmpfiles.d/ksm.conf|<br />
w /sys/kernel/mm/ksm/run - - - - 1<br />
}}<br />
<br />
If KSM is running, and there are pages to be merged (i.e. at least two similar VMs are running), then {{ic|/sys/kernel/mm/ksm/pages_shared}} should be non-zero. See https://www.kernel.org/doc/html/latest/admin-guide/mm/ksm.html for more information.<br />
<br />
{{Tip|An easy way to see how well KSM is performing is to simply print the contents of all the files in that directory: {{bc|$ grep . /sys/kernel/mm/ksm/*}}}}<br />
<br />
=== Multi-monitor support ===<br />
<br />
The Linux QXL driver supports four heads (virtual screens) by default. This can be changed via the {{ic|1=qxl.heads=N}} kernel parameter.<br />
<br />
The default VGA memory size for QXL devices is 16M (VRAM size is 64M). This is not sufficient if you would like to enable two 1920x1200 monitors since that requires 2 × 1920 × 4 (color depth) × 1200 = 17.6 MiB VGA memory. This can be changed by replacing {{ic|-vga qxl}} by {{ic|<nowiki>-vga none -device qxl-vga,vgamem_mb=32</nowiki>}}. If you ever increase vgamem_mb beyond 64M, then you also have to increase the {{ic|vram_size_mb}} option.<br />
<br />
=== Copy and paste ===<br />
<br />
One way to share the clipboard between the host and the guest is to enable the SPICE remote desktop protocol and access the client with a SPICE client.<br />
One needs to follow the steps described in [[#SPICE]]. A guest run this way will support copy paste with the host.<br />
<br />
=== Windows-specific notes ===<br />
<br />
QEMU can run any version of Windows from Windows 95 through Windows 10.<br />
<br />
It is possible to run [[Windows PE]] in QEMU.<br />
<br />
==== Fast startup ====<br />
<br />
{{Note|An administrator account is required to change power settings.}}<br />
<br />
For Windows 8 (or later) guests it is better to disable "Turn on fast startup (recommended)" from the Power Options of the Control Panel as explained in the following [https://www.tenforums.com/tutorials/4189-turn-off-fast-startup-windows-10-a.html forum page], as it causes the guest to hang during every other boot.<br />
<br />
Fast Startup may also need to be disabled for changes to the {{ic|-smp}} option to be properly applied.<br />
<br />
==== Remote Desktop Protocol ====<br />
<br />
If you use a MS Windows guest, you might want to use RDP to connect to your guest VM. If you are using a VLAN or are not in the same network as the guest, use:<br />
<br />
$ qemu-system-x86_64 -nographic -net user,hostfwd=tcp::5555-:3389<br />
<br />
Then connect with either {{Pkg|rdesktop}} or {{Pkg|freerdp}} to the guest. For example:<br />
<br />
$ xfreerdp -g 2048x1152 localhost:5555 -z -x lan<br />
<br />
=== Clone Linux system installed on physical equipment ===<br />
<br />
Linux system installed on physical equipment can be cloned for running on QEMU vm. See [https://coffeebirthday.wordpress.com/2018/09/14/clone-linux-system-for-qemu-virtual-machine/ Clone Linux system from hardware for QEMU virtual machine]<br />
<br />
=== Chrooting into arm/arm64 environment from x86_64 ===<br />
<br />
Sometimes it is easier to work directly on a disk image instead of the real ARM based device. This can be achieved by mounting an SD card/storage containing the ''root'' partition and chrooting into it.<br />
<br />
Another use case for an ARM chroot is building ARM packages on an x86_64 machine - {{AUR|armutils-git}} can be used for that. Here, the chroot environment can be created from an image tarball from [https://archlinuxarm.org Arch Linux ARM] - see [https://nerdstuff.org/posts/2020/2020-003_simplest_way_to_create_an_arm_chroot/] for a detailed description of this approach.<br />
<br />
Either way, from the chroot it should be possible to run ''pacman'' and install more packages, compile large libraries etc. Since the executables are for the ARM architecture, the translation to x86 needs to be performed by [[QEMU]].<br />
<br />
Install {{AUR|binfmt-qemu-static}} and {{AUR|qemu-user-static}} from the [[AUR]] on the x86_64 machine/host. ''binfmt-qemu-static'' will take care of registering the qemu binaries to binfmt service.<br />
<br />
[[Restart]] {{ic|systemd-binfmt.service}}<br />
<br />
{{AUR|qemu-user-static}} is needed to allow the execution of compiled programs from other architectures. This is similar to what is provided by {{Pkg|qemu-arch-extra}}, but the "static" variant is required for chroot. Examples:<br />
<br />
qemu-arm-static path_to_sdcard/usr/bin/ls<br />
qemu-aarch64-static path_to_sdcard/usr/bin/ls<br />
<br />
These two lines execute the {{ic|ls}} command compiled for 32-bit ARM and 64-bit ARM respectively. Note that this will not work without chrooting, because it will look for libraries not present in the host system.<br />
<br />
{{AUR|qemu-user-static}} allows automatically prefixing the ARM exectuable with {{ic|qemu-arm-static}} or {{ic|qemu-aarch64-static}}.<br />
<br />
Make sure that the ARM executable support is active:<br />
<br />
{{hc|$ ls /proc/sys/fs/binfmt_misc|<br />
qemu-aarch64 qemu-arm qemu-cris qemu-microblaze qemu-mipsel qemu-ppc64 qemu-riscv64 qemu-sh4 qemu-sparc qemu-sparc64 status<br />
qemu-alpha qemu-armeb qemu-m68k qemu-mips qemu-ppc qemu-ppc64abi32 qemu-s390x qemu-sh4eb qemu-sparc32plus register<br />
}}<br />
<br />
Each executable must be listed.<br />
<br />
If it is not active, reinstall ''binfmt-qemu-static'' and restart ''systemd-binfmt''.<br />
<br />
Mount the SD card to {{ic|/mnt/scdard}} (the device name may be different).<br />
<br />
# mkdir -p /mnt/sdcard<br />
# mount /dev/mmcblk0p2 /mnt/sdcard<br />
<br />
Mount boot partition if needed (again, use the suitable device name):<br />
<br />
# mount /dev/mmcblk0p1 /mnt/sdcard/boot<br />
<br />
Finally ''chroot'' into the SD card root as described in [[Change root#Using chroot]]:<br />
<br />
# chroot /mnt/sdcard /bin/bash<br />
<br />
Alternatively, you can use ''arch-chroot'' from {{Pkg|arch-install-scripts}}, as it will provide an easier way to get network support:<br />
# arch-chroot /mnt/sdcard /bin/bash<br />
<br />
You can also use ''systemd-nspawn'' to chroot into the ARM environment:<br />
# systemd-nspawn -D /mnt/sdcard -M myARMMachine --bind-ro=/etc/resolv.conf<br />
<br />
{{ic|1=--bind-ro=/etc/resolv.conf}} is optional and gives a working network DNS inside the chroot<br />
<br />
== Troubleshooting ==<br />
<br />
=== Mouse cursor is jittery or erratic ===<br />
<br />
If the cursor jumps around the screen uncontrollably, entering this on the terminal before starting QEMU might help:<br />
<br />
$ export SDL_VIDEO_X11_DGAMOUSE=0<br />
<br />
If this helps, you can add this to your {{ic|~/.bashrc}} file.<br />
<br />
=== No visible Cursor ===<br />
<br />
Add {{ic|-show-cursor}} to QEMU's options to see a mouse cursor.<br />
<br />
If that still does not work, make sure you have set your display device appropriately, for example: {{ic|-vga qxl}}.<br />
<br />
Another option to try is {{ic|-usb -device usb-tablet}} as mentioned in [[#Mouse integration]]. This overrides the default PS/2 mouse emulation and synchronizes pointer location between host and guest as an added bonus.<br />
<br />
=== Two different mouse cursors are visible ===<br />
<br />
Apply the tip [[#Mouse integration]].<br />
<br />
=== Keyboard issues when using VNC ===<br />
<br />
When using VNC, you might experience keyboard problems described (in gory details) [https://www.berrange.com/posts/2010/07/04/more-than-you-or-i-ever-wanted-to-know-about-virtual-keyboard-handling/ here]. The solution is ''not'' to use the {{ic|-k}} option on QEMU, and to use {{ic|gvncviewer}} from {{Pkg|gtk-vnc}}. See also [http://www.mail-archive.com/libvir-list@redhat.com/msg13340.html this] message posted on libvirt's mailing list.<br />
<br />
=== Keyboard seems broken or the arrow keys do not work ===<br />
<br />
Should you find that some of your keys do not work or "press" the wrong key (in particular, the arrow keys), you likely need to specify your keyboard layout as an option. The keyboard layouts can be found in {{ic|/usr/share/qemu/keymaps}}.<br />
<br />
$ qemu-system-x86_64 -k ''keymap'' ''disk_image''<br />
<br />
=== Guest display stretches on window resize ===<br />
<br />
To restore default window size, press {{ic|Ctrl+Alt+u}}.<br />
<br />
=== ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy ===<br />
<br />
If an error message like this is printed when starting QEMU with {{ic|-enable-kvm}} option:<br />
<br />
ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy<br />
failed to initialize KVM: Device or resource busy<br />
<br />
that means another [[hypervisor]] is currently running. It is not recommended or possible to run several hypervisors in parallel.<br />
<br />
=== libgfapi error message ===<br />
<br />
The error message displayed at startup:<br />
<br />
Failed to open module: libgfapi.so.0: cannot open shared object file: No such file or directory<br />
<br />
[[Install]] {{pkg|glusterfs}} or ignore the error message as GlusterFS is a optional dependency.<br />
<br />
=== Kernel panic on LIVE-environments===<br />
<br />
If you start a live-environment (or better: booting a system) you may encounter this:<br />
<br />
[ end Kernel panic - not syncing: VFS: Unable to mount root fs on unknown block(0,0)<br />
<br />
or some other boot hindering process (e.g. cannot unpack initramfs, cant start service foo).<br />
Try starting the VM with the {{ic|-m VALUE}} switch and an appropriate amount of RAM, if the ram is to low you will probably encounter similar issues as above/without the memory-switch.<br />
<br />
=== Windows 7 guest suffers low-quality sound ===<br />
<br />
Using the {{ic|hda}} audio driver for Windows 7 guest may result in low-quality sound. Changing the audio driver to {{ic|ac97}} by passing the {{ic|-soundhw ac97}} arguments to QEMU and installing the AC97 driver from [https://www.realtek.com/en/component/zoo/category/pc-audio-codecs-ac-97-audio-codecs-software Realtek AC'97 Audio Codecs] in the guest may solve the problem. See [https://bugzilla.redhat.com/show_bug.cgi?id=1176761#c16 Red Hat Bugzilla – Bug 1176761] for more information.<br />
<br />
=== Could not access KVM kernel module: Permission denied ===<br />
<br />
If you encounter the following error:<br />
<br />
libvirtError: internal error: process exited while connecting to monitor: Could not access KVM kernel module: Permission denied failed to initialize KVM: Permission denied<br />
<br />
Systemd 234 assigns a dynamic ID for the {{ic|kvm}} group (see {{Bug|54943}}). To avoid this error, you need edit the file {{ic|/etc/libvirt/qemu.conf}} and change the line with {{ic|1=group = "78"}} to {{ic|1=group = "kvm"}}.<br />
<br />
=== "System Thread Exception Not Handled" when booting a Windows VM ===<br />
<br />
Windows 8 or Windows 10 guests may raise a generic compatibility exception at boot, namely "System Thread Exception Not Handled", which tends to be caused by legacy drivers acting strangely on real machines. On KVM machines this issue can generally be solved by setting the CPU model to {{ic|core2duo}}.<br />
<br />
=== Certain Windows games/applications crashing/causing a bluescreen ===<br />
<br />
Occasionally, applications running in the VM may crash unexpectedly, whereas they would run normally on a physical machine. If, while running {{ic|dmesg -wH}}, you encounter an error mentioning {{ic|MSR}}, the reason for those crashes is that KVM injects a [[wikipedia:General protection fault|General protection fault]] (GPF) when the guest tries to access unsupported [[wikipedia:Model-specific register|Model-specific registers]] (MSRs) - this often results in guest applications/OS crashing. A number of those issues can be solved by passing the {{ic|1=ignore_msrs=1}} option to the KVM module, which will ignore unimplemented MSRs.<br />
<br />
{{hc|/etc/modprobe.d/kvm.conf|2=<br />
...<br />
options kvm ignore_msrs=1<br />
...<br />
}}<br />
<br />
Cases where adding this option might help:<br />
<br />
* GeForce Experience complaining about an unsupported CPU being present.<br />
* StarCraft 2 and L.A. Noire reliably blue-screening Windows 10 with {{ic|KMODE_EXCEPTION_NOT_HANDLED}}. The blue screen information does not identify a driver file in these cases.<br />
<br />
{{Warning|While this is normally safe and some applications might not work without this, silently ignoring unknown MSR accesses could potentially break other software within the VM or other VMs.}}<br />
<br />
=== Applications in the VM experience long delays or take a long time to start ===<br />
<br />
This may be caused by insufficient available entropy in the VM. Consider allowing the guest to access the hosts's entropy pool by adding a [https://wiki.qemu.org/Features/VirtIORNG VirtIO RNG device] to the VM, or by installing an entropy generating daemon such as [[Haveged]].<br />
<br />
Anecdotally, OpenSSH takes a while to start accepting connections under insufficient entropy, without the logs revealing why.<br />
<br />
=== High interrupt latency and microstuttering ===<br />
<br />
This problem manifests itself as small pauses (stutters) and is particularly noticeable in graphics-intensive applications, such as games.<br />
<br />
* One of the causes is CPU power saving features, which are controlled by [[CPU frequency scaling]]. Change this to {{ic|performance}} for all processor cores. <br />
* Another possible cause is PS/2 inputs. Switch from PS/2 to Virtio inputs, see [[PCI passthrough via OVMF#Passing keyboard/mouse via Evdev]].<br />
<br />
=== QXL video causes low resolution ===<br />
<br />
QEMU 4.1.0 introduced a regression where QXL video can fall back to low resolutions, when being displayed through spice. [https://bugs.launchpad.net/qemu/+bug/1843151] For example, when KMS starts, text resolution may become as low as 4x10 characters. When trying to increase GUI resolution, it may go to the lowest supported resolution.<br />
<br />
As a workaround, create your device in this form:<br />
<br />
-device qxl-vga,max_outputs=1...<br />
<br />
=== Hang during VM initramfs ===<br />
<br />
Linux 5.2.11 introduced a KVM regression where under some circumstances a VM may permanently hang during the early boot phase, when the initramfs is being loaded or ran. [https://www.spinics.net/lists/kvm/msg195171.html] Linux 5.3 fixed the regression. The host shows qemu using 100% CPU * number of virtual CPUs. Reported case is with a host using hyperthreading, and a VM being given more than host's {{ic|nproc}}/2 virtual CPUs. It is unknown what exact circumstances trigger one of the threads to delete a memory region to cause this. The workarounds are:<br />
<br />
* Upgrade to Linux 5.3.<br />
* Downgrade to Linux 5.2.10<br />
* Until fixed, try giving the VM no more than the host's {{ic|nproc}}/2 virtual CPUs<br />
* Custom compile linux, reverting commit 2ad350fb4c (note this re-introduces a regression triggered when removing a memslot)<br />
<br />
=== VM does not boot when using a Secure Boot enabled OVMF ===<br />
<br />
{{ic|/usr/share/edk2-ovmf/x64/OVMF_CODE.secboot.fd}} from {{Pkg|edk2-ovmf}} is built with [[Wikipedia:System Management Mode|SMM]] support. If S3 support is not disabled in the VM, then the VM might not boot at all.<br />
<br />
Add the {{ic|1=-global ICH9-LPC.disable_s3=1}} option to the ''qemu'' command.<br />
<br />
See {{Bug|59465}} and https://github.com/tianocore/edk2/blob/master/OvmfPkg/README for more details and the required options to use Secure Boot in QEMU.<br />
<br />
=== Guest CPU interrupts are not firing ===<br />
<br />
If you are writing your own operating system by following the [https://wiki.osdev.org/ OSDev wiki], or are simply getting stepping through the guest architecture assembly code using QEMU's {{ic|gdb}} interface using the {{ic|-s}} flag, it's useful to know that many emulators, QEMU included, usually implement some CPU interrupts leaving many hardware interrupts unimplemented. One way to know if your code if firing an interrupt, is by using:<br />
<br />
-d int<br />
<br />
to enable showing interrupts/exceptions on stdout.<br />
<br />
To see what other guest debugging features QEMU has to offer, see:<br />
<br />
qemu-system-x86_64 -d help<br />
<br />
or replace {{ic|x86_64}} for your chosen guest architecture.<br />
<br />
== See also ==<br />
<br />
* [http://qemu.org Official QEMU website]<br />
* [http://www.linux-kvm.org Official KVM website]<br />
* [http://qemu.weilnetz.de/qemu-doc.html QEMU Emulator User Documentation]<br />
* [[Wikibooks:QEMU|QEMU Wikibook]]<br />
* [http://alien.slackbook.org/dokuwiki/doku.php?id=slackware:qemu Hardware virtualization with QEMU] by AlienBOB (last updated in 2008)<br />
* [http://blog.falconindy.com/articles/build-a-virtual-army.html Building a Virtual Army] by Falconindy<br />
* [http://git.qemu.org/?p=qemu.git;a=tree;f=docs Lastest docs]<br />
* [http://qemu.weilnetz.de/ QEMU on Windows]<br />
* [[wikipedia:Qemu|Wikipedia]]<br />
* [[debian:QEMU|Debian Wiki - QEMU]]<br />
* [https://people.gnome.org/~markmc/qemu-networking.html QEMU Networking on gnome.org]<br />
* [http://bsdwiki.reedmedia.net/wiki/networking_qemu_virtual_bsd_systems.html Networking QEMU Virtual BSD Systems]<br />
* [https://www.gnu.org/software/hurd/hurd/running/qemu.html QEMU on gnu.org]<br />
* [https://wiki.freebsd.org/qemu QEMU on FreeBSD as host]<br />
* [https://wiki.mikejung.biz/KVM_/_Xen KVM/QEMU Virtio Tuning and SSD VM Optimization Guide]<br />
* [https://doc.opensuse.org/documentation/leap/virtualization/html/book-virt/part-virt-qemu.html Managing Virtual Machines with QEMU - openSUSE documentation]<br />
* [https://www.ibm.com/support/knowledgecenter/en/linuxonibm/liaat/liaatkvm.htm KVM on IBM Knowledge Center]</div>Malcontenthttps://wiki.archlinux.org/index.php?title=QEMU&diff=635690QEMU2020-09-18T14:14:49Z<p>Malcontent: Provide a link to the exact commit of the hostdevice feature</p>
<hr />
<div>[[Category:Emulation]]<br />
[[Category:Hypervisors]]<br />
[[de:Qemu]]<br />
[[es:QEMU]]<br />
[[fr:Qemu]]<br />
[[ja:QEMU]]<br />
[[zh-hans:QEMU]]<br />
[[zh-hant:QEMU]]<br />
{{Related articles start}}<br />
{{Related|:Category:Hypervisors}}<br />
{{Related|Libvirt}}<br />
{{Related|QEMU/Guest graphics acceleration}}<br />
{{Related|PCI passthrough via OVMF}}<br />
{{Related articles end}}<br />
<br />
According to the [http://wiki.qemu.org/Main_Page QEMU about page], "QEMU is a generic and open source machine emulator and virtualizer."<br />
<br />
When used as a machine emulator, QEMU can run OSes and programs made for one machine (e.g. an ARM board) on a different machine (e.g. your x86 PC). By using dynamic translation, it achieves very good performance.<br />
<br />
QEMU can use other hypervisors like [[Xen]] or [[KVM]] to use CPU extensions ([[Wikipedia:Hardware-assisted virtualization|HVM]]) for virtualization. When used as a virtualizer, QEMU achieves near native performances by executing the guest code directly on the host CPU.<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|qemu}} package (or {{Pkg|qemu-headless}} for the version without GUI) and below optional packages for your needs:<br />
<br />
* {{Pkg|qemu-arch-extra}} - extra architectures support<br />
* {{Pkg|qemu-block-gluster}} - [[Glusterfs]] block support<br />
* {{Pkg|qemu-block-iscsi}} - [[iSCSI]] block support<br />
* {{Pkg|qemu-block-rbd}} - RBD block support <br />
* {{Pkg|samba}} - [[Samba|SMB/CIFS]] server support<br />
<br />
Alternatively, {{AUR|qemu-user-static}} exists as a usermode and static variant.<br />
<br />
=== QEMU variants ===<br />
<br />
QEMU is offered in several variants suited for different use cases.<br />
<br />
As a first classification, QEMU is offered in full-system and usermode emulation modes:<br />
<br />
; Full-system emulation<br />
: In this mode, QEMU emulates a full system, including one or several processors and various peripherals. It is more accurate but slower, and does not require the emulated OS to be Linux.<br />
: QEMU commands for full-system emulation are named {{ic|qemu-system-''target_architecture''}}, e.g. {{ic|qemu-system-x86_64}} for emulating intel 64-bit CPUs, {{ic|qemu-system-i386}} for intel 32 bits CPUs, {{ic|qemu-system-arm}} for ARM (32 bits), {{ic|qemu-system-aarch64}} for ARM64, etc.<br />
: If the target architecture matches the host CPU, this mode may still benefit from a significant speedup by using a hypervisor like [[#Enabling KVM|KVM]] or Xen.<br />
; [https://www.qemu.org/docs/master/user/main.html Usermode emulation]: In this mode, QEMU is able to invoke a Linux executable compiled for a (potentially) different architecture by leveraging the host system resources. There may be compatibility issues, e.g. some features may not be implemented, dynamically linked executables will not work out of the box (see [[#Chrooting into arm/arm64 environment from x86_64|the section below]] to address this) and only Linux is supported (although [https://wiki.winehq.org/Emulation Wine may be used] for running Windows executables).<br />
: QEMU commands for usermode emulation are named {{ic|qemu-''target_architecture''}}, e.g. {{ic|qemu-x86_64}} for emulating intel 64-bit CPUs.<br />
<br />
QEMU is offered in dynamically-linked and statically-linked variants:<br />
<br />
; Dynamically-linked (default): {{ic|qemu-*}} commands depend on the host OS libraries, so executables are smaller.<br />
; Statically-linked: {{ic|qemu-*}} commands can be copied to any Linux system with the same architecture.<br />
<br />
In the case of Arch Linux, full-system emulation is offered as:<br />
<br />
; Non-headless (default): This variant enables GUI features that require additional dependencies (like SDL or GTK).<br />
; Headless: This is a slimmer variant that does not require GUI (this is suitable e.g. for servers).<br />
<br />
Note that headless and non-headless versions install commands with the same name (e.g. {{ic|qemu-system-x86_64}}) and thus cannot be both installed at the same time.<br />
<br />
=== Details on packages offered in Arch Linux ===<br />
<br />
* The {{Pkg|qemu}} package provides the {{ic|x86_64}} architecture emulators for full-system emulation ({{ic|qemu-system-x86_64}}). The {{Pkg|qemu-arch-extra}} package provides the {{ic|x86_64}} usermode variant ({{ic|qemu-x86_64}}) and also for the rest of supported architectures it includes both full-system and usermode variants (e.g. {{ic|qemu-system-arm}} and {{ic|qemu-arm}}).<br />
* The headless versions of these packages (only applicable to full-system emulation) are {{Pkg|qemu-headless}} ({{ic|x86_64}}-only) and {{Pkg|qemu-headless-arch-extra}} (rest of architectures).<br />
* Full-system emulation can be expanded with some QEMU modules present in separate packages: {{Pkg|qemu-block-gluster}}, {{Pkg|qemu-block-iscsi}}, {{Pkg|qemu-block-rbd}} and {{Pkg|qemu-guest-agent}}.<br />
* The unofficial AUR package {{AUR|qemu-user-static}} provides a usermode and static variant for all target architectures supported by QEMU. A precompiled version of this package exists: {{AUR|qemu-user-static-bin}}. The installed QEMU commands are named {{ic|qemu-''target_architecture''-static}}, for example, {{ic|qemu-x86_64-static}} for intel 64-bit CPUs.<br />
<br />
{{Note|At present, Arch does not offer a full-system mode and statically linked variant (neither officially nor via AUR), as this is usually not needed.}}<br />
<br />
== Graphical front-ends for QEMU ==<br />
<br />
Unlike other virtualization programs such as [[VirtualBox]] and [[VMware]], QEMU does not provide a GUI to manage virtual machines (other than the window that appears when running a virtual machine), nor does it provide a way to create persistent virtual machines with saved settings. All parameters to run a virtual machine must be specified on the command line at every launch, unless you have created a custom script to start your virtual machine(s).<br />
<br />
[[Libvirt]] provides a convenient way to manage QEMU virtual machines. See [[Libvirt#Client|list of libvirt clients]] for available front-ends.<br />
<br />
Other GUI front-ends for QEMU:<br />
<br />
* {{App|AQEMU|QEMU GUI written in Qt5.|https://github.com/tobimensch/aqemu|{{AUR|aqemu}}}}<br />
<br />
== Creating new virtualized system ==<br />
<br />
=== Creating a hard disk image ===<br />
<br />
{{Accuracy|If I get the man page right the raw format only allocates the full size if the filesystem does not support "holes" or it is <br />
explicitly told to preallocate. See man qemu-img in section Notes.}} <br />
<br />
{{Tip|See [[Wikibooks:QEMU/Images]] for more information on QEMU images.}}<br />
<br />
To run QEMU you will need a hard disk image, unless you are booting a live system from CD-ROM or the network (and not doing so to install an operating system to a hard disk image). A hard disk image is a file which stores the contents of the emulated hard disk.<br />
<br />
A hard disk image can be ''raw'', so that it is literally byte-by-byte the same as what the guest sees, and will always use the full capacity of the guest hard drive on the host. This method provides the least I/O overhead, but can waste a lot of space, as not-used space on the guest cannot be used on the host.<br />
<br />
Alternatively, the hard disk image can be in a format such as ''qcow2'' which only allocates space to the image file when the guest operating system actually writes to those sectors on its virtual hard disk. The image appears as the full size to the guest operating system, even though it may take up only a very small amount of space on the host system. This image format also supports QEMU snapshotting functionality (see [[#Creating and managing snapshots via the monitor console]] for details). However, using this format instead of ''raw'' will likely affect performance.<br />
<br />
QEMU provides the {{ic|qemu-img}} command to create hard disk images. For example to create a 4 GB image in the ''raw'' format:<br />
<br />
$ qemu-img create -f raw ''image_file'' 4G<br />
<br />
You may use {{ic|-f qcow2}} to create a ''qcow2'' disk instead.<br />
<br />
{{Note|You can also simply create a ''raw'' image by creating a file of the needed size using {{ic|dd}} or {{ic|fallocate}}.}}<br />
<br />
{{Warning|If you store the hard disk images on a [[Btrfs]] file system, you should consider disabling [[Btrfs#Copy-on-Write (CoW)|Copy-on-Write]] for the directory before creating any images.}}<br />
<br />
==== Overlay storage images ====<br />
<br />
You can create a storage image once (the 'backing' image) and have QEMU keep mutations to this image in an overlay image. This allows you to revert to a previous state of this storage image. You could revert by creating a new overlay image at the time you wish to revert, based on the original backing image.<br />
<br />
To create an overlay image, issue a command like:<br />
<br />
$ qemu-img create -o backing_file=''img1.raw'',backing_fmt=''raw'' -f ''qcow2'' ''img1.cow''<br />
<br />
After that you can run your QEMU VM as usual (see [[#Running virtualized system]]):<br />
<br />
$ qemu-system-x86_64 ''img1.cow''<br />
<br />
The backing image will then be left intact and mutations to this storage will be recorded in the overlay image file.<br />
<br />
When the path to the backing image changes, repair is required.<br />
<br />
{{Warning|The backing image's absolute filesystem path is stored in the (binary) overlay image file. Changing the backing image's path requires some effort.}}<br />
<br />
Make sure that the original backing image's path still leads to this image. If necessary, make a symbolic link at the original path to the new path. Then issue a command like:<br />
<br />
$ qemu-img rebase -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
At your discretion, you may alternatively perform an 'unsafe' rebase where the old path to the backing image is not checked:<br />
<br />
$ qemu-img rebase -u -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
==== Resizing an image ====<br />
<br />
{{Warning|Resizing an image containing an NTFS boot file system could make the operating system installed on it unbootable. It is recommended to create a backup first.}}<br />
<br />
The {{ic|qemu-img}} executable has the {{ic|resize}} option, which enables easy resizing of a hard drive image. It works for both ''raw'' and ''qcow2''. For example, to increase image space by 10 GB, run:<br />
<br />
$ qemu-img resize ''disk_image'' +10G<br />
<br />
After enlarging the disk image, you must use file system and partitioning tools inside the virtual machine to actually begin using the new space. When shrinking a disk image, you must '''first reduce the allocated file systems and partition sizes''' using the file system and partitioning tools inside the virtual machine and then shrink the disk image accordingly, otherwise shrinking the disk image will result in data loss! For a Windows guest, open the "create and format hard disk partitions" control panel.<br />
<br />
==== Converting an image ====<br />
<br />
You can convert an image to other formats using {{ic|qemu-img convert}}. This example shows how to convert a ''raw'' image to ''qcow2'':<br />
<br />
$ qemu-img convert -f raw -O qcow2 ''input''.img ''output''.qcow2<br />
<br />
This will not remove the original input file.<br />
<br />
=== Preparing the installation media ===<br />
<br />
To install an operating system into your disk image, you need the installation medium (e.g. optical disk, USB-drive, or ISO image) for the operating system. The installation medium should not be mounted because QEMU accesses the media directly.<br />
<br />
{{Tip|If using an optical disk, it is a good idea to first dump the media to a file because this both improves performance and does not require you to have direct access to the devices (that is, you can run QEMU as a regular user without having to change access permissions on the media's device file). For example, if the CD-ROM device node is named {{ic|/dev/cdrom}}, you can dump it to a file with the command: {{bc|1=$ dd if=/dev/cdrom of=''cd_image.iso'' bs=4k}}}}<br />
<br />
=== Installing the operating system ===<br />
<br />
This is the first time you will need to start the emulator. To install the operating system on the disk image, you must attach both the disk image and the installation media to the virtual machine, and have it boot from the installation media.<br />
<br />
For example on i386 guests, to install from a bootable ISO file as CD-ROM and a raw disk image:<br />
<br />
$ qemu-system-x86_64 -cdrom ''iso_image'' -boot order=d -drive file=''disk_image'',format=raw<br />
<br />
See {{man|1|qemu}} for more information about loading other media types (such as floppy, disk images or physical drives) and [[#Running virtualized system]] for other useful options.<br />
<br />
After the operating system has finished installing, the QEMU image can be booted directly (see [[#Running virtualized system]]).<br />
<br />
{{Note|By default only 128 MB of memory is assigned to the machine. The amount of memory can be adjusted with the {{ic|-m}} switch, for example {{ic|-m 512M}} or {{ic|-m 2G}}.}}<br />
<br />
{{Tip|<br />
* Instead of specifying {{ic|1=-boot order=x}}, some users may feel more comfortable using a boot menu: {{ic|1=-boot menu=on}}, at least during configuration and experimentation.<br />
* When running QEMU in headless mode, it starts a local VNC server on port 5900 per default. You can use [[TigerVNC]] to connect to the guest OS: {{ic|vncviewer :5900}}<br />
* If you need to replace floppies or CDs as part of the installation process, you can use the QEMU machine monitor (press {{ic|Ctrl+Alt+2}} in the virtual machine's window) to remove and attach storage devices to a virtual machine. Type {{ic|info block}} to see the block devices, and use the {{ic|change}} command to swap out a device. Press {{ic|Ctrl+Alt+1}} to go back to the virtual machine.<br />
}}<br />
<br />
== Running virtualized system ==<br />
<br />
{{ic|qemu-system-*}} binaries (for example {{ic|qemu-system-i386}} or {{ic|qemu-system-x86_64}}, depending on guest's architecture) are used to run the virtualized guest. The usage is:<br />
<br />
$ qemu-system-x86_64 ''options'' ''disk_image''<br />
<br />
Options are the same for all {{ic|qemu-system-*}} binaries, see {{man|1|qemu}} for documentation of all options.<br />
<br />
By default, QEMU will show the virtual machine's video output in a window. One thing to keep in mind: when you click inside the QEMU window, the mouse pointer is grabbed. To release it, press {{ic|Ctrl+Alt+g}}.<br />
<br />
{{Warning|QEMU should never be run as root. If you must launch it in a script as root, you should use the {{ic|-runas}} option to make QEMU drop root privileges.}}<br />
<br />
=== Enabling KVM ===<br />
<br />
KVM (''Kernel-based Virtual Machine'') full virtualization must be supported by your Linux kernel and your hardware, and necessary [[kernel modules]] must be loaded. See [[KVM]] for more information.<br />
<br />
To start QEMU in KVM mode, append {{ic|-enable-kvm}} to the additional start options. To check if KVM is enabled for a running VM, enter the [[#QEMU monitor]] and type {{ic|info kvm}}.<br />
<br />
{{Note|<br />
* The argument {{ic|1=accel=kvm}} of the {{ic|-machine}} option is equivalent to the {{ic|-enable-kvm}} or the {{ic|-accel kvm}} option.<br />
* CPU model {{ic|host}} requires KVM<br />
* If you start your VM with a GUI tool and experience very bad performance, you should check for proper KVM support, as QEMU may be falling back to software emulation.<br />
* KVM needs to be enabled in order to start Windows 7 and Windows 8 properly without a ''blue screen''.<br />
}}<br />
<br />
=== Enabling IOMMU (Intel VT-d/AMD-Vi) support ===<br />
<br />
First enable IOMMU, see [[PCI passthrough via OVMF#Setting up IOMMU]].<br />
<br />
Add {{ic|-device intel-iommu}} to create the IOMMU device:<br />
<br />
$ qemu-system-x86_64 '''-enable-kvm -machine q35 -device intel-iommu''' -cpu host ..<br />
<br />
{{Note|<br />
On Intel CPU based systems creating an IOMMU device in a QEMU guest with {{ic|-device intel-iommu}} will disable PCI passthrough with an error like: {{bc|Device at bus pcie.0 addr 09.0 requires iommu notifier which is currently not supported by intel-iommu emulation}} While adding the kernel parameter {{ic|1=intel_iommu=on}} is still needed for remapping IO (e.g. [[PCI passthrough via OVMF#Isolating the GPU|PCI passthrough with vfio-pci]]), {{ic|-device intel-iommu}} should not be set if PCI PCI passthrough is required.<br />
}}<br />
<br />
== Sharing data between host and guest ==<br />
<br />
=== Network ===<br />
<br />
Data can be shared between the host and guest OS using any network protocol that can transfer files, such as [[NFS]], [[SMB]], [[Wikipedia:Network block device|NBD]], HTTP, [[Very Secure FTP Daemon|FTP]], or [[SSH]], provided that you have set up the network appropriately and enabled the appropriate services.<br />
<br />
The default user-mode networking allows the guest to access the host OS at the IP address 10.0.2.2. Any servers that you are running on your host OS, such as a SSH server or SMB server, will be accessible at this IP address. So on the guests, you can mount directories exported on the host via [[SMB]] or [[NFS]], or you can access the host's HTTP server, etc.<br />
It will not be possible for the host OS to access servers running on the guest OS, but this can be done with other network configurations (see [[#Tap networking with QEMU]]).<br />
<br />
=== QEMU's port forwarding ===<br />
<br />
QEMU can forward ports from the host to the guest to enable e.g. connecting from the host to an SSH server running on the guest.<br />
<br />
For example, to bind port 10022 on the host with port 22 (SSH) on the guest, start QEMU with a command like:<br />
<br />
$ qemu-system-x86_64 ''disk_image'' -nic user,hostfwd=tcp::10022-:22<br />
<br />
Make sure the sshd is running on the guest and connect with:<br />
<br />
$ ssh ''guest-user''@localhost -p 10022<br />
<br />
You can use [[SSHFS]] to mount the guest's file system at the host for shared read and write access.<br />
<br />
=== QEMU's built-in SMB server ===<br />
<br />
QEMU's documentation says it has a "built-in" SMB server, but actually it just starts up [[Samba]] on the host with an automatically generated {{ic|smb.conf}} file located in {{ic|/tmp/qemu-smb.''random_string''}} and makes it accessible to the guest at a different IP address (10.0.2.4 by default). This only works for user networking, and is useful when you do not want to start the normal [[Samba]] service on the host, which the guest can also access if you have set up shares on it.<br />
<br />
Only a single directory can be set as shared with the option {{ic|1=smb=}}, but adding more directories (even while the virtual machine is running) could be as easy as creating symbolic links in the shared directory if QEMU configured SMB to follow symbolic links. It does not do so, but the configuration of the running SMB server can be changed as described below.<br />
<br />
''Samba'' must be installed on the host. To enable this feature, start QEMU with a command like:<br />
<br />
$ qemu-system-x86_64 ''disk_image'' -net nic -net user,smb=''shared_dir_path''<br />
<br />
where {{ic|''shared_dir_path''}} is a directory that you want to share between the guest and host.<br />
<br />
Then, in the guest, you will be able to access the shared directory on the host 10.0.2.4 with the share name "qemu". For example, in Windows Explorer you would go to {{ic|\\10.0.2.4\qemu}}.<br />
<br />
{{Note|<br />
* If you are using sharing options multiple times like {{ic|1=-net user,smb=''shared_dir_path1'' -net user,smb=''shared_dir_path2''}} or {{ic|1=-net user,smb=''shared_dir_path1'',smb=''shared_dir_path2''}} then it will share only the last defined one.<br />
* If you cannot access the shared folder and the guest system is Windows, check that the [http://ecross.mvps.org/howto/enable-netbios-over-tcp-ip-with-windows.htm NetBIOS protocol is enabled] and that a firewall does not block [https://technet.microsoft.com/en-us/library/cc940063.aspx ports] used by the NetBIOS protocol.<br />
* If you cannot access the shared folder and the guest system is Windows 10 Enterprise or Education or Windows Server 2016, [https://support.microsoft.com/en-us/help/4046019 enable guest access].<br />
}}<br />
<br />
One way to share multiple directories and to add or remove them while the virtual machine is running, is to share an empty directory and create/remove symbolic links to the directories in the shared directory. For this to work, the configuration of the running SMB server can be changed with the following script, which also allows the execution of files on the guest that are not set executable on the host:<br />
<br />
#!/bin/bash<br />
eval $(ps h -C smbd -o pid,args | grep /tmp/qemu-smb | gawk '{print "pid="$1";conf="$6}')<br />
echo "[global]<br />
allow insecure wide links = yes<br />
[qemu]<br />
follow symlinks = yes<br />
wide links = yes<br />
acl allow execute always = yes" >> $conf<br />
# in case the change is not detected automatically:<br />
smbcontrol --configfile=$conf $pid reload-config<br />
<br />
This can be applied to the running server started by qemu only after the guest has connected to the network drive the first time. An alternative to this method is to add additional shares to the configuration file like so:<br />
<br />
echo "[''myshare'']<br />
path=''another_path''<br />
read only=no<br />
guest ok=yes<br />
force user=''username''" >> $conf<br />
<br />
This share will be available on the guest as {{ic|\\10.0.2.4\''myshare''}}.<br />
<br />
=== Using filesystem passthrough and VirtFS ===<br />
<br />
See the [https://wiki.qemu.org/Documentation/9psetup QEMU documentation].<br />
<br />
=== Mounting a partition of the guest on the host ===<br />
<br />
It can be useful to mount a drive image under the host system, it can be a way to transfer files in and out of the guest. This should be done when the virtual machine is not running.<br />
<br />
The procedure to mount the drive on the host depends on the type of qemu image, ''raw'' or ''qcow2''. We detail thereafter the steps to mount a drive in the two formats in [[#Mounting a partition from a raw image]] and [[#Mounting a partition from a qcow2 image]]. For the full documentation see [[Wikibooks:QEMU/Images#Mounting an image on the host]].<br />
<br />
{{Warning|You must make sure to unmount the partitions before running the virtual machine again. Otherwise, data corruption is very likely to occur.}}<br />
<br />
==== Mounting a partition from a raw image ====<br />
<br />
It is possible to mount partitions that are inside a raw disk image file by setting them up as loopback devices.<br />
<br />
===== With manually specifying byte offset =====<br />
<br />
One way to mount a disk image partition is to mount the disk image at a certain offset using a command like the following:<br />
<br />
# mount -o loop,offset=32256 ''disk_image'' ''mountpoint''<br />
<br />
The {{ic|1=offset=32256}} option is actually passed to the {{ic|losetup}} program to set up a loopback device that starts at byte offset 32256 of the file and continues to the end. This loopback device is then mounted. You may also use the {{ic|sizelimit}} option to specify the exact size of the partition, but this is usually unnecessary.<br />
<br />
Depending on your disk image, the needed partition may not start at offset 32256. Run {{ic|fdisk -l ''disk_image''}} to see the partitions in the image. fdisk gives the start and end offsets in 512-byte sectors, so multiply by 512 to get the correct offset to pass to {{ic|mount}}.<br />
<br />
===== With loop module autodetecting partitions =====<br />
<br />
The Linux loop driver actually supports partitions in loopback devices, but it is disabled by default. To enable it, do the following:<br />
<br />
* Get rid of all your loopback devices (unmount all mounted images, etc.).<br />
* [[Kernel_modules#Manual_module_handling|Unload]] the {{ic|loop}} kernel module, and load it with the {{ic|1=max_part=15}} parameter set. Additionally, the maximum number of loop devices can be controlled with the {{ic|max_loop}} parameter.<br />
<br />
{{Tip|You can put an entry in {{ic|/etc/modprobe.d}} to load the loop module with {{ic|1=max_part=15}} every time, or you can put {{ic|1=loop.max_part=15}} on the kernel command-line, depending on whether you have the {{ic|loop.ko}} module built into your kernel or not.}}<br />
<br />
Set up your image as a loopback device:<br />
<br />
# losetup -f -P ''disk_image''<br />
<br />
Then, if the device created was {{ic|/dev/loop0}}, additional devices {{ic|/dev/loop0pX}} will have been automatically created, where X is the number of the partition. These partition loopback devices can be mounted directly. For example:<br />
<br />
# mount /dev/loop0p1 ''mountpoint''<br />
<br />
To mount the disk image with ''udisksctl'', see [[Udisks#Mount loop devices]].<br />
<br />
===== With kpartx =====<br />
<br />
'''kpartx''' from the {{Pkg|multipath-tools}} package can read a partition table on a device and create a new device for each partition. For example:<br />
<br />
# kpartx -a ''disk_image''<br />
<br />
This will setup the loopback device and create the necessary partition(s) device(s) in {{ic|/dev/mapper/}}.<br />
<br />
==== Mounting a partition from a qcow2 image ====<br />
<br />
We will use {{ic|qemu-nbd}}, which lets use the NBD (''network block device'') protocol to share the disk image.<br />
<br />
First, we need the ''nbd'' module loaded:<br />
<br />
# modprobe nbd max_part=16<br />
<br />
Then, we can share the disk and create the device entries:<br />
<br />
# qemu-nbd -c /dev/nbd0 ''/path/to/image.qcow2''<br />
<br />
Discover the partitions:<br />
<br />
# partprobe /dev/nbd0<br />
<br />
''fdisk'' can be used to get information regarding the different partitions in {{{ic|''nbd0''}}:<br />
<br />
{{hc|# fdisk -l /dev/nbd0|2=<br />
Disk /dev/nbd0: 25.2 GiB, 27074281472 bytes, 52879456 sectors<br />
Units: sectors of 1 * 512 = 512 bytes<br />
Sector size (logical/physical): 512 bytes / 512 bytes<br />
I/O size (minimum/optimal): 512 bytes / 512 bytes<br />
Disklabel type: dos<br />
Disk identifier: 0xa6a4d542<br />
<br />
Device Boot Start End Sectors Size Id Type<br />
/dev/nbd0p1 * 2048 1026047 1024000 500M 7 HPFS/NTFS/exFAT<br />
/dev/nbd0p2 1026048 52877311 51851264 24.7G 7 HPFS/NTFS/exFAT}}<br />
<br />
Then mount any partition of the drive image, for example the partition 2:<br />
<br />
# mount /dev/nbd0'''p2''' ''mountpoint''<br />
<br />
After the usage, it is important to unmount the image and reverse previous steps, i.e. unmount the partition and disconnect the nbd device:<br />
<br />
# umount ''mountpoint''<br />
# qemu-nbd -d /dev/nbd0<br />
<br />
=== Using any real partition as the single primary partition of a hard disk image ===<br />
<br />
Sometimes, you may wish to use one of your system partitions from within QEMU. Using a raw partition for a virtual machine will improve performance, as the read and write operations do not go through the file system layer on the physical host. Such a partition also provides a way to share data between the host and guest.<br />
<br />
In Arch Linux, device files for raw partitions are, by default, owned by ''root'' and the ''disk'' group. If you would like to have a non-root user be able to read and write to a raw partition, you must either change the owner of the partition's device file to that user, add that user to the ''disk'' group, or use [[ACL]] for more fine-grained access control.<br />
<br />
{{Warning|<br />
* Although it is possible, it is not recommended to allow virtual machines to alter critical data on the host system, such as the root partition.<br />
* You must not mount a file system on a partition read-write on both the host and the guest at the same time. Otherwise, data corruption will result.<br />
}}<br />
<br />
After doing so, you can attach the partition to a QEMU virtual machine as a virtual disk.<br />
<br />
However, things are a little more complicated if you want to have the ''entire'' virtual machine contained in a partition. In that case, there would be no disk image file to actually boot the virtual machine since you cannot install a bootloader to a partition that is itself formatted as a file system and not as a partitioned device with an MBR. Such a virtual machine can be booted either by specifying the [[kernel]] and [[initrd]] manually, or by simulating a disk with an MBR by using the [https://www.kernel.org/doc/html/latest/admin-guide/device-mapper/index.html Device-mapper], linear [[RAID]], or a [https://www.kernel.org/doc/html/latest/admin-guide/blockdev/nbd.html Linux Network Block Device].<br />
<br />
==== By specifying kernel and initrd manually ====<br />
<br />
QEMU supports loading [[Kernels|Linux kernels]] and [[initramfs|init ramdisks]] directly, thereby circumventing bootloaders such as [[GRUB]]. It then can be launched with the physical partition containing the root file system as the virtual disk, which will not appear to be partitioned. This is done by issuing a command similar to the following:<br />
<br />
{{Note|In this example, it is the '''host's''' images that are being used, not the guest's. If you wish to use the guest's images, either mount {{ic|/dev/sda3}} read-only (to protect the file system from the host) and specify the {{ic|/full/path/to/images}} or use some kexec hackery in the guest to reload the guest's kernel (extends boot time). }}<br />
<br />
$ qemu-system-x86_64 -kernel /boot/vmlinuz-linux -initrd /boot/initramfs-linux.img -append root=/dev/sda /dev/sda3<br />
<br />
In the above example, the physical partition being used for the guest's root file system is {{ic|/dev/sda3}} on the host, but it shows up as {{ic|/dev/sda}} on the guest.<br />
<br />
You may, of course, specify any kernel and initrd that you want, and not just the ones that come with Arch Linux.<br />
<br />
When there are multiple [[kernel parameters]] to be passed to the {{ic|-append}} option, they need to be quoted using single or double quotes. For example:<br />
<br />
... -append 'root=/dev/sda1 console=ttyS0'<br />
<br />
==== Simulate a virtual disk with MBR ====<br />
<br />
A more complicated way to have a virtual machine use a physical partition, while keeping that partition formatted as a file system and not just having the guest partition the partition as if it were a disk, is to simulate an MBR for it so that it can boot using a bootloader such as GRUB.<br />
<br />
For the following, suppose you have a plain, unmounted {{ic|/dev/hda''N''}} partition with some file system on it you wish to make part of a QEMU disk image. The trick is to dynamically prepend a master boot record (MBR) to the real partition you wish to embed in a QEMU raw disk image. More generally, the partition can be any part of a larger simulated disk, in particular a block device that simulates the original physical disk but only exposes {{ic|/dev/hda''N''}} to the virtual machine.<br />
<br />
A virtual disk of this type can be represented by a VMDK file that contains references to (a copy of) the MBR and the partition, but QEMU does not support this VMDK format. For instance, a virtual disk [https://www.virtualbox.org/manual/ch09.html#rawdisk created by]<br />
<br />
$ VBoxManage internalcommands createrawvmdk -filename ''/path/to/file.vmdk'' -rawdisk /dev/hda<br />
<br />
will be rejected by QEMU with the error message<br />
<br />
Unsupported image type 'partitionedDevice'<br />
<br />
Note that {{ic|VBoxManage}} creates two files, {{ic|''file.vmdk''}} and {{ic|''file-pt.vmdk''}}, the latter being a copy of the MBR, to which the text file {{ic|file.vmdk}} points. Read operations outside the target partition or the MBR would give zeros, while written data would be discarded.<br />
<br />
===== Device Mapper =====<br />
<br />
A method that is similar to the use of a VMDK descriptor file uses the device mapper to prepend a loop device attached to the MBR file to the target partition. In case we do not need our virtual disk to have the same size as the original, we first create a file to hold the MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=2048<br />
<br />
Here, a 1 MB (2048 * 512 bytes) file is created in accordance with partition alignment policies used by modern disk partitioning tools. For compatibility with older partitioning software, 63 sectors instead of 2048 might be required. The MBR only needs a single 512 bytes block, the additional free space can be used for a BIOS boot partition and, in the case of a hybrid partitioning scheme, for a GUID Partition Table. Then, we attach a loop device to the MBR file:<br />
<br />
# losetup --show -f ''/path/to/mbr''<br />
/dev/loop0<br />
<br />
In this example, the resulting device is {{ic|/dev/loop0}}. The device mapper is now used to join the MBR and the partition:<br />
<br />
# echo "0 2048 linear /dev/loop0 0<br />
2048 `blockdev --getsz /dev/hda''N''` linear /dev/hda''N'' 0" | dmsetup create qemu<br />
<br />
The resulting {{ic|/dev/mapper/qemu}} is what we will use as a QEMU raw disk image. Additional steps are required to create a partition table (see the section that describes the use of a linear RAID for an example) and boot loader code on the virtual disk (which will be stored in {{ic|''/path/to/mbr''}}).<br />
<br />
The following setup is an example where the position of {{ic|/dev/hda''N''}} on the virtual disk is to be the same as on the physical disk and the rest of the disk is hidden, except for the MBR, which is provided as a copy:<br />
<br />
# dd if=/dev/hda count=1 of=''/path/to/mbr''<br />
# loop=`losetup --show -f ''/path/to/mbr''`<br />
# start=`blockdev --report /dev/hda''N'' | tail -1 | awk '{print $5}'`<br />
# size=`blockdev --getsz /dev/hda''N''`<br />
# disksize=`blockdev --getsz /dev/hda`<br />
# echo "0 1 linear $loop 0<br />
1 $((start-1)) zero<br />
$start $size linear /dev/hda''N'' 0<br />
$((start+size)) $((disksize-start-size)) zero" | dmsetup create qemu<br />
<br />
The table provided as standard input to {{ic|dmsetup}} has a similar format as the table in a VDMK descriptor file produced by {{ic|VBoxManage}} and can alternatively be loaded from a file with {{ic|dmsetup create qemu --table ''table_file''}}. To the virtual machine, only {{ic|/dev/hda''N''}} is accessible, while the rest of the hard disk reads as zeros and discards written data, except for the first sector. We can print the table for {{ic|/dev/mapper/qemu}} with {{ic|dmsetup table qemu}} (use {{ic|udevadm info -rq name /sys/dev/block/''major'':''minor''}} to translate {{ic|''major'':''minor''}} to the corresponding {{ic|/dev/''blockdevice''}} name). Use {{ic|dmsetup remove qemu}} and {{ic|losetup -d $loop}} to delete the created devices.<br />
<br />
A situation where this example would be useful is an existing Windows XP installation in a multi-boot configuration and maybe a hybrid partitioning scheme (on the physical hardware, Windows XP could be the only operating system that uses the MBR partition table, while more modern operating systems installed on the same computer could use the GUID Partition Table). Windows XP supports hardware profiles, so that that the same installation can be used with different hardware configurations alternatingly (in this case bare metal vs. virtual) with Windows needing to install drivers for newly detected hardware only once for every profile. Note that in this example the boot loader code in the copied MBR needs to be updated to directly load Windows XP from {{ic|/dev/hda''N''}} instead of trying to start the multi-boot capable boot loader (like GRUB) present in the original system. Alternatively, a copy of the boot partition containing the boot loader installation can be included in the virtual disk the same way as the MBR.<br />
<br />
===== Linear RAID =====<br />
<br />
You can also do this using software [[RAID]] in linear mode (you need the {{ic|linear.ko}} kernel driver) and a loopback device: <br />
<br />
First, you create some small file to hold the MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=32<br />
<br />
Here, a 16 KB (32 * 512 bytes) file is created. It is important not to make it too small (even if the MBR only needs a single 512 bytes block), since the smaller it will be, the smaller the chunk size of the software RAID device will have to be, which could have an impact on performance. Then, you setup a loopback device to the MBR file:<br />
<br />
# losetup -f ''/path/to/mbr''<br />
<br />
Let us assume the resulting device is {{ic|/dev/loop0}}, because we would not already have been using other loopbacks. Next step is to create the "merged" MBR + {{ic|/dev/hda''N''}} disk image using software RAID:<br />
<br />
# modprobe linear<br />
# mdadm --build --verbose /dev/md0 --chunk=16 --level=linear --raid-devices=2 /dev/loop0 /dev/hda''N''<br />
<br />
The resulting {{ic|/dev/md0}} is what you will use as a QEMU raw disk image (do not forget to set the permissions so that the emulator can access it). The last (and somewhat tricky) step is to set the disk configuration (disk geometry and partitions table) so that the primary partition start point in the MBR matches the one of {{ic|/dev/hda''N''}} inside {{ic|/dev/md0}} (an offset of exactly 16 * 512 = 16384 bytes in this example). Do this using {{ic|fdisk}} on the host machine, not in the emulator: the default raw disc detection routine from QEMU often results in non-kilobyte-roundable offsets (such as 31.5 KB, as in the previous section) that cannot be managed by the software RAID code. Hence, from the the host:<br />
<br />
# fdisk /dev/md0<br />
<br />
Press {{ic|X}} to enter the expert menu. Set number of 's'ectors per track so that the size of one cylinder matches the size of your MBR file. For two heads and a sector size of 512, the number of sectors per track should be 16, so we get cylinders of size 2x16x512=16k.<br />
<br />
Now, press {{ic|R}} to return to the main menu.<br />
<br />
Press {{ic|P}} and check that the cylinder size is now 16k.<br />
<br />
Now, create a single primary partition corresponding to {{ic|/dev/hda''N''}}. It should start at cylinder 2 and end at the end of the disk (note that the number of cylinders now differs from what it was when you entered fdisk.<br />
<br />
Finally, 'w'rite the result to the file: you are done. You now have a partition you can mount directly from your host, as well as part of a QEMU disk image:<br />
<br />
$ qemu-system-x86_64 -hdc /dev/md0 ''[...]''<br />
<br />
You can, of course, safely set any bootloader on this disk image using QEMU, provided the original {{ic|/dev/hda''N''}} partition contains the necessary tools.<br />
<br />
===== Network Block Device =====<br />
<br />
Instead of the methods decribed above, you may use {{ic|nbd-server}} (from the {{pkg|nbd}} package) to create an MBR wrapper for QEMU.<br />
<br />
Assuming you have already set up your MBR wrapper file like above, rename it to {{ic|wrapper.img.0}}. Then create a symbolic link named {{ic|wrapper.img.1}} in the same directory, pointing to your partition. Then put the following script in the same directory:<br />
<br />
#!/bin/sh<br />
dir="$(realpath "$(dirname "$0")")"<br />
cat >wrapper.conf <<EOF<br />
[generic]<br />
allowlist = true<br />
listenaddr = 127.713705<br />
port = 10809<br />
<br />
[wrap]<br />
exportname = $dir/wrapper.img<br />
multifile = true<br />
EOF<br />
<br />
nbd-server \<br />
-C wrapper.conf \<br />
-p wrapper.pid \<br />
"$@"<br />
<br />
The {{ic|.0}} and {{ic|.1}} suffixes are essential; the rest can be changed. After running the above script (which you may need to do as root to make sure nbd-server is able to access the partition), you can launch QEMU with:<br />
<br />
qemu-system-x86_64 -drive file=nbd:127.713705:10809:exportname=wrap ''[...]''<br />
<br />
== Networking ==<br />
<br />
{{Style|Network topologies (sections [[#Host-only networking]], [[#Internal networking]] and info spread out across other sections) should not be described alongside the various virtual interfaces implementations, such as [[#User-mode networking]], [[#Tap networking with QEMU]], [[#Networking with VDE2]].}}<br />
<br />
The performance of virtual networking should be better with tap devices and bridges than with user-mode networking or vde because tap devices and bridges are implemented in-kernel.<br />
<br />
In addition, networking performance can be improved by assigning virtual machines a [http://wiki.libvirt.org/page/Virtio virtio] network device rather than the default emulation of an e1000 NIC. See [[#Installing virtio drivers]] for more information.<br />
<br />
=== Link-level address caveat ===<br />
<br />
By giving the {{ic|-net nic}} argument to QEMU, it will, by default, assign a virtual machine a network interface with the link-level address {{ic|52:54:00:12:34:56}}. However, when using bridged networking with multiple virtual machines, it is essential that each virtual machine has a unique link-level (MAC) address on the virtual machine side of the tap device. Otherwise, the bridge will not work correctly, because it will receive packets from multiple sources that have the same link-level address. This problem occurs even if the tap devices themselves have unique link-level addresses because the source link-level address is not rewritten as packets pass through the tap device.<br />
<br />
Make sure that each virtual machine has a unique link-level address, but it should always start with {{ic|52:54:}}. Use the following option, replace ''X'' with arbitrary hexadecimal digit:<br />
<br />
$ qemu-system-x86_64 -net nic,macaddr=52:54:''XX:XX:XX:XX'' -net vde ''disk_image''<br />
<br />
Generating unique link-level addresses can be done in several ways:<br />
<br />
* Manually specify unique link-level address for each NIC. The benefit is that the DHCP server will assign the same IP address each time the virtual machine is run, but it is unusable for large number of virtual machines.<br />
* Generate random link-level address each time the virtual machine is run. Practically zero probability of collisions, but the downside is that the DHCP server will assign a different IP address each time. You can use the following command in a script to generate random link-level address in a {{ic|macaddr}} variable:<br />
<br />
{{bc|1=<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
qemu-system-x86_64 -net nic,macaddr="$macaddr" -net vde ''disk_image''<br />
}}<br />
<br />
* Use the following script {{ic|qemu-mac-hasher.py}} to generate the link-level address from the virtual machine name using a hashing function. Given that the names of virtual machines are unique, this method combines the benefits of the aforementioned methods: it generates the same link-level address each time the script is run, yet it preserves the practically zero probability of collisions.<br />
<br />
{{hc|qemu-mac-hasher.py|<nowiki><br />
#!/usr/bin/env python<br />
<br />
import sys<br />
import zlib<br />
<br />
if len(sys.argv) != 2:<br />
print("usage: %s <VM Name>" % sys.argv[0])<br />
sys.exit(1)<br />
<br />
crc = zlib.crc32(sys.argv[1].encode("utf-8")) & 0xffffffff<br />
crc = str(hex(crc))[2:]<br />
print("52:54:%s%s:%s%s:%s%s:%s%s" % tuple(crc))<br />
</nowiki>}}<br />
<br />
In a script, you can use for example:<br />
<br />
vm_name="''VM Name''"<br />
qemu-system-x86_64 -name "$vm_name" -net nic,macaddr=$(qemu-mac-hasher.py "$vm_name") -net vde ''disk_image''<br />
<br />
=== User-mode networking ===<br />
<br />
By default, without any {{ic|-netdev}} arguments, QEMU will use user-mode networking with a built-in DHCP server. Your virtual machines will be assigned an IP address when they run their DHCP client, and they will be able to access the physical host's network through IP masquerading done by QEMU.<br />
<br />
{{warning|This only works with the TCP and UDP protocols, so ICMP, including {{ic|ping}}, will not work. Do not use {{ic|ping}} to test network connectivity. To make ping work in the guest see [[Sysctl#Allow unprivileged users to create IPPROTO_ICMP sockets]].}}<br />
<br />
This default configuration allows your virtual machines to easily access the Internet, provided that the host is connected to it, but the virtual machines will not be directly visible on the external network, nor will virtual machines be able to talk to each other if you start up more than one concurrently.<br />
<br />
QEMU's user-mode networking can offer more capabilities such as built-in TFTP or SMB servers, redirecting host ports to the guest (for example to allow SSH connections to the guest) or attaching guests to VLANs so that they can talk to each other. See the QEMU documentation on the {{ic|-net user}} flag for more details.<br />
<br />
However, user-mode networking has limitations in both utility and performance. More advanced network configurations require the use of tap devices or other methods.<br />
<br />
{{Note|If the host system uses [[systemd-networkd]], make sure to symlink the {{ic|/etc/resolv.conf}} file as described in [[systemd-networkd#Required services and setup]], otherwise the DNS lookup in the guest system will not work.}}<br />
<br />
=== Tap networking with QEMU ===<br />
<br />
[[wikipedia:TUN/TAP|Tap devices]] are a Linux kernel feature that allows you to create virtual network interfaces that appear as real network interfaces. Packets sent to a tap interface are delivered to a userspace program, such as QEMU, that has bound itself to the interface.<br />
<br />
QEMU can use tap networking for a virtual machine so that packets sent to the tap interface will be sent to the virtual machine and appear as coming from a network interface (usually an Ethernet interface) in the virtual machine. Conversely, everything that the virtual machine sends through its network interface will appear on the tap interface.<br />
<br />
Tap devices are supported by the Linux bridge drivers, so it is possible to bridge together tap devices with each other and possibly with other host interfaces such as {{ic|eth0}}. This is desirable if you want your virtual machines to be able to talk to each other, or if you want other machines on your LAN to be able to talk to the virtual machines.<br />
<br />
{{Warning|If you bridge together tap device and some host interface, such as {{ic|eth0}}, your virtual machines will appear directly on the external network, which will expose them to possible attack. Depending on what resources your virtual machines have access to, you may need to take all the [[Firewalls|precautions]] you normally would take in securing a computer to secure your virtual machines. If the risk is too great, virtual machines have little resources or you set up multiple virtual machines, a better solution might be to use [[#Host-only networking|host-only networking]] and set up NAT. In this case you only need one firewall on the host instead of multiple firewalls for each guest.}}<br />
<br />
As indicated in the user-mode networking section, tap devices offer higher networking performance than user-mode. If the guest OS supports virtio network driver, then the networking performance will be increased considerably as well. Supposing the use of the tap0 device, that the virtio driver is used on the guest, and that no scripts are used to help start/stop networking, next is part of the qemu command one should see:<br />
<br />
-device virtio-net,netdev=network0 -netdev tap,id=network0,ifname=tap0,script=no,downscript=no<br />
<br />
But if already using a tap device with virtio networking driver, one can even boost the networking performance by enabling vhost, like:<br />
<br />
-device virtio-net,netdev=network0 -netdev tap,id=network0,ifname=tap0,script=no,downscript=no,vhost=on<br />
<br />
See [https://web.archive.org/web/20160222161955/http://www.linux-kvm.com:80/content/how-maximize-virtio-net-performance-vhost-net] for more information.<br />
<br />
==== Host-only networking ====<br />
<br />
If the bridge is given an IP address and traffic destined for it is allowed, but no real interface (e.g. {{ic|eth0}}) is connected to the bridge, then the virtual machines will be able to talk to each other and the host system. However, they will not be able to talk to anything on the external network, provided that you do not set up IP masquerading on the physical host. This configuration is called ''host-only networking'' by other virtualization software such as [[VirtualBox]].<br />
<br />
{{Tip|<br />
* If you want to set up IP masquerading, e.g. NAT for virtual machines, see the [[Internet sharing#Enable NAT]] page.<br />
* See [[Network bridge]] for information on creating bridge.<br />
* You may want to have a DHCP server running on the bridge interface to service the virtual network. For example, to use the {{ic|172.20.0.1/16}} subnet with [[dnsmasq]] as the DHCP server:<br />
<br />
{{bc|1=<br />
# ip addr add 172.20.0.1/16 dev br0<br />
# ip link set br0 up<br />
# dnsmasq --interface=br0 --bind-interfaces --dhcp-range=172.20.0.2,172.20.255.254<br />
}}<br />
}}<br />
<br />
==== Internal networking ====<br />
<br />
If you do not give the bridge an IP address and add an [[iptables]] rule to drop all traffic to the bridge in the INPUT chain, then the virtual machines will be able to talk to each other, but not to the physical host or to the outside network. This configuration is called ''internal networking'' by other virtualization software such as [[VirtualBox]]. You will need to either assign static IP addresses to the virtual machines or run a DHCP server on one of them.<br />
<br />
By default iptables would drop packets in the bridge network. You may need to use such iptables rule to allow packets in a bridged network:<br />
<br />
# iptables -I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Bridged networking using qemu-bridge-helper ====<br />
<br />
{{Note|This method is available since QEMU 1.1, see http://wiki.qemu.org/Features/HelperNetworking.}}<br />
<br />
This method does not require a start-up script and readily accommodates multiple taps and multiple bridges. It uses {{ic|/usr/lib/qemu/qemu-bridge-helper}} binary, which allows creating tap devices on an existing bridge.<br />
<br />
{{Tip|See [[Network bridge]] for information on creating bridge.}}<br />
<br />
First, create a configuration file containing the names of all bridges to be used by QEMU:<br />
<br />
{{hc|/etc/qemu/bridge.conf|<br />
allow ''bridge0''<br />
allow ''bridge1''<br />
...}}<br />
<br />
Now start the VM. The most basic usage would be:<br />
<br />
$ qemu-system-x86_64 -net nic -net bridge,br=''bridge0'' ''[...]''<br />
<br />
With multiple taps, the most basic usage requires specifying the VLAN for all additional NICs:<br />
<br />
$ qemu-system-x86_64 -net nic -net bridge,br=''bridge0'' -net nic,vlan=1 -net bridge,vlan=1,br=''bridge1'' ''[...]''<br />
<br />
==== Creating bridge manually ====<br />
<br />
{{Style|This section needs serious cleanup and may contain out-of-date information.}}<br />
<br />
{{Tip|Since QEMU 1.1, the [http://wiki.qemu.org/Features/HelperNetworking network bridge helper] can set tun/tap up for you without the need for additional scripting. See [[#Bridged networking using qemu-bridge-helper]].}}<br />
<br />
The following describes how to bridge a virtual machine to a host interface such as {{ic|eth0}}, which is probably the most common configuration. This configuration makes it appear that the virtual machine is located directly on the external network, on the same Ethernet segment as the physical host machine.<br />
<br />
We will replace the normal Ethernet adapter with a bridge adapter and bind the normal Ethernet adapter to it.<br />
<br />
* Install {{Pkg|bridge-utils}}, which provides {{ic|brctl}} to manipulate bridges.<br />
<br />
* Enable IPv4 forwarding:<br />
# sysctl -w net.ipv4.ip_forward=1<br />
<br />
To make the change permanent, change {{ic|1=net.ipv4.ip_forward = 0}} to {{ic|1=net.ipv4.ip_forward = 1}} in {{ic|/etc/sysctl.d/99-sysctl.conf}}.<br />
<br />
* Load the {{ic|tun}} module and configure it to be loaded on boot. See [[Kernel modules]] for details.<br />
<br />
* Now create the bridge. See [[Bridge with netctl]] for details. Remember to name your bridge as {{ic|br0}}, or change the scripts below to your bridge's name.<br />
<br />
* Create the script that QEMU uses to bring up the tap adapter with {{ic|root:kvm}} 750 permissions:<br />
<br />
{{hc|/etc/qemu-ifup|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifup"<br />
echo "Bringing up $1 for bridged mode..."<br />
sudo /usr/bin/ip link set $1 up promisc on<br />
echo "Adding $1 to br0..."<br />
sudo /usr/bin/brctl addif br0 $1<br />
sleep 2<br />
</nowiki>}}<br />
<br />
* Create the script that QEMU uses to bring down the tap adapter in {{ic|/etc/qemu-ifdown}} with {{ic|root:kvm}} 750 permissions:<br />
{{hc|/etc/qemu-ifdown|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifdown"<br />
sudo /usr/bin/ip link set $1 down<br />
sudo /usr/bin/brctl delif br0 $1<br />
sudo /usr/bin/ip link delete dev $1<br />
</nowiki>}}<br />
<br />
* Use {{ic|visudo}} to add the following to your {{ic|sudoers}} file:<br />
<br />
{{bc|<nowiki><br />
Cmnd_Alias QEMU=/usr/bin/ip,/usr/bin/modprobe,/usr/bin/brctl<br />
%kvm ALL=NOPASSWD: QEMU<br />
</nowiki>}}<br />
<br />
* You launch QEMU using the following {{ic|run-qemu}} script:<br />
<br />
{{hc|run-qemu|<nowiki><br />
#!/bin/bash<br />
USERID=$(whoami)<br />
<br />
# Get name of newly created TAP device; see https://bbs.archlinux.org/viewtopic.php?pid=1285079#p1285079<br />
precreationg=$(/usr/bin/ip tuntap list | /usr/bin/cut -d: -f1 | /usr/bin/sort)<br />
sudo /usr/bin/ip tuntap add user $USERID mode tap<br />
postcreation=$(/usr/bin/ip tuntap list | /usr/bin/cut -d: -f1 | /usr/bin/sort)<br />
IFACE=$(comm -13 <(echo "$precreationg") <(echo "$postcreation"))<br />
<br />
# This line creates a random MAC address. The downside is the DHCP server will assign a different IP address each time<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
# Instead, uncomment and edit this line to set a static MAC address. The benefit is that the DHCP server will assign the same IP address.<br />
# macaddr='52:54:be:36:42:a9'<br />
<br />
qemu-system-x86_64 -net nic,macaddr=$macaddr -net tap,ifname="$IFACE" $*<br />
<br />
sudo ip link set dev $IFACE down &> /dev/null<br />
sudo ip tuntap del $IFACE mode tap &> /dev/null<br />
</nowiki>}}<br />
<br />
Then to launch a VM, do something like this<br />
<br />
$ run-qemu -hda ''myvm.img'' -m 512<br />
<br />
* It is recommended for performance and security reasons to disable the [http://ebtables.netfilter.org/documentation/bridge-nf.html firewall on the bridge]:<br />
<br />
{{hc|/etc/sysctl.d/10-disable-firewall-on-bridge.conf|<nowiki><br />
net.bridge.bridge-nf-call-ip6tables = 0<br />
net.bridge.bridge-nf-call-iptables = 0<br />
net.bridge.bridge-nf-call-arptables = 0<br />
</nowiki>}}<br />
<br />
Run {{ic|sysctl -p /etc/sysctl.d/10-disable-firewall-on-bridge.conf}} to apply the changes immediately.<br />
<br />
See the [http://wiki.libvirt.org/page/Networking#Creating_network_initscripts libvirt wiki] and [https://bugzilla.redhat.com/show_bug.cgi?id=512206 Fedora bug 512206]. If you get errors by sysctl during boot about non-existing files, make the {{ic|bridge}} module load at boot. See [[Kernel modules#Automatic module loading with systemd]].<br />
<br />
Alternatively, you can configure [[iptables]] to allow all traffic to be forwarded across the bridge by adding a rule like this:<br />
<br />
-I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Network sharing between physical device and a Tap device through iptables ====<br />
<br />
{{Merge|Internet_sharing|Duplication, not specific to QEMU.}}<br />
<br />
Bridged networking works fine between a wired interface (Eg. eth0), and it is easy to setup. However if the host gets connected to the network through a wireless device, then bridging is not possible.<br />
<br />
See [[Network bridge#Wireless interface on a bridge]] as a reference.<br />
<br />
One way to overcome that is to setup a tap device with a static IP, making linux automatically handle the routing for it, and then forward traffic between the tap interface and the device connected to the network through iptables rules.<br />
<br />
See [[Internet sharing]] as a reference.<br />
<br />
There you can find what is needed to share the network between devices, included tap and tun ones. The following just hints further on some of the host configurations required. As indicated in the reference above, the client needs to be configured for a static IP, using the IP assigned to the tap interface as the gateway. The caveat is that the DNS servers on the client might need to be manually edited if they change when changing from one host device connected to the network to another.<br />
<br />
To allow IP forwarding on every boot, one need to add the following lines to sysctl configuration file inside {{ic|/etc/sysctl.d}}:<br />
<br />
net.ipv4.ip_forward = 1<br />
net.ipv6.conf.default.forwarding = 1<br />
net.ipv6.conf.all.forwarding = 1<br />
<br />
The iptables rules can look like:<br />
<br />
# Forwarding from/to outside<br />
iptables -A FORWARD -i ${INT} -o ${EXT_0} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_1} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_2} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_0} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_1} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_2} -o ${INT} -j ACCEPT<br />
# NAT/Masquerade (network address translation)<br />
iptables -t nat -A POSTROUTING -o ${EXT_0} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_1} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_2} -j MASQUERADE<br />
<br />
The prior supposes there are 3 devices connected to the network sharing traffic with one internal device, where for example:<br />
<br />
INT=tap0<br />
EXT_0=eth0<br />
EXT_1=wlan0<br />
EXT_2=tun0<br />
<br />
The prior shows a forwarding that would allow sharing wired and wireless connections with the tap device.<br />
<br />
The forwarding rules shown are stateless, and for pure forwarding. One could think of restricting specific traffic, putting a firewall in place to protect the guest and others. However those would decrease the networking performance, while a simple bridge does not include any of that.<br />
<br />
Bonus: Whether the connection is wired or wireless, if one gets connected through VPN to a remote site with a tun device, supposing the tun device opened for that connection is tun0, and the prior iptables rules are applied, then the remote connection gets also shared with the guest. This avoids the need for the guest to also open a VPN connection. Again, as the guest networking needs to be static, then if connecting the host remotely this way, one most probably will need to edit the DNS servers on the guest.<br />
<br />
=== Networking with VDE2 ===<br />
<br />
{{Style|This section needs serious cleanup and may contain out-of-date information.}}<br />
<br />
==== What is VDE? ====<br />
<br />
VDE stands for Virtual Distributed Ethernet. It started as an enhancement of [[User-mode Linux|uml]]_switch. It is a toolbox to manage virtual networks.<br />
<br />
The idea is to create virtual switches, which are basically sockets, and to "plug" both physical and virtual machines in them. The configuration we show here is quite simple; However, VDE is much more powerful than this, it can plug virtual switches together, run them on different hosts and monitor the traffic in the switches. You are invited to read [https://wiki.virtualsquare.org/ the documentation of the project].<br />
<br />
The advantage of this method is you do not have to add sudo privileges to your users. Regular users should not be allowed to run modprobe.<br />
<br />
==== Basics ====<br />
<br />
VDE support can be [[pacman|installed]] via the {{Pkg|vde2}} package.<br />
<br />
In our config, we use tun/tap to create a virtual interface on my host. Load the {{ic|tun}} module (see [[Kernel modules]] for details):<br />
<br />
# modprobe tun<br />
<br />
Now create the virtual switch:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
<br />
This line creates the switch, creates {{ic|tap0}}, "plugs" it, and allows the users of the group {{ic|users}} to use it.<br />
<br />
The interface is plugged in but not configured yet. To configure it, run this command:<br />
<br />
# ip addr add 192.168.100.254/24 dev tap0<br />
<br />
Now, you just have to run KVM with these {{ic|-net}} options as a normal user:<br />
<br />
$ qemu-system-x86_64 -net nic -net vde -hda ''[...]''<br />
<br />
Configure networking for your guest as you would do in a physical network.<br />
<br />
{{Tip|You might want to set up NAT on tap device to access the internet from the virtual machine. See [[Internet sharing#Enable NAT]] for more information.}}<br />
<br />
==== Startup scripts ====<br />
<br />
Example of main script starting VDE:<br />
<br />
{{hc|/etc/systemd/scripts/qemu-network-env|<nowiki><br />
#!/bin/sh<br />
# QEMU/VDE network environment preparation script<br />
<br />
# The IP configuration for the tap device that will be used for<br />
# the virtual machine network:<br />
<br />
TAP_DEV=tap0<br />
TAP_IP=192.168.100.254<br />
TAP_MASK=24<br />
TAP_NETWORK=192.168.100.0<br />
<br />
# Host interface<br />
NIC=eth0<br />
<br />
case "$1" in<br />
start)<br />
echo -n "Starting VDE network for QEMU: "<br />
<br />
# If you want tun kernel module to be loaded by script uncomment here<br />
#modprobe tun 2>/dev/null<br />
## Wait for the module to be loaded<br />
#while ! lsmod | grep -q "^tun"; do echo "Waiting for tun device"; sleep 1; done<br />
<br />
# Start tap switch<br />
vde_switch -tap "$TAP_DEV" -daemon -mod 660 -group users<br />
<br />
# Bring tap interface up<br />
ip address add "$TAP_IP"/"$TAP_MASK" dev "$TAP_DEV"<br />
ip link set "$TAP_DEV" up<br />
<br />
# Start IP Forwarding<br />
echo "1" > /proc/sys/net/ipv4/ip_forward<br />
iptables -t nat -A POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
;;<br />
stop)<br />
echo -n "Stopping VDE network for QEMU: "<br />
# Delete the NAT rules<br />
iptables -t nat -D POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
<br />
# Bring tap interface down<br />
ip link set "$TAP_DEV" down<br />
<br />
# Kill VDE switch<br />
pgrep vde_switch | xargs kill -TERM<br />
;;<br />
restart|reload)<br />
$0 stop<br />
sleep 1<br />
$0 start<br />
;;<br />
*)<br />
echo "Usage: $0 {start|stop|restart|reload}"<br />
exit 1<br />
esac<br />
exit 0<br />
</nowiki>}}<br />
<br />
Example of systemd service using the above script:<br />
<br />
{{hc|/etc/systemd/system/qemu-network-env.service|<nowiki><br />
[Unit]<br />
Description=Manage VDE Switch<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/etc/systemd/scripts/qemu-network-env start<br />
ExecStop=/etc/systemd/scripts/qemu-network-env stop<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
Change permissions for {{ic|qemu-network-env}} to be executable<br />
<br />
# chmod u+x /etc/systemd/scripts/qemu-network-env<br />
<br />
You can [[start]] {{ic|qemu-network-env.service}} as usual.<br />
<br />
====Alternative method====<br />
<br />
If the above method does not work or you do not want to mess with kernel configs, TUN, dnsmasq, and iptables you can do the following for the same result.<br />
<br />
# vde_switch -daemon -mod 660 -group users<br />
# slirpvde --dhcp --daemon<br />
<br />
Then, to start the VM with a connection to the network of the host:<br />
<br />
$ qemu-system-x86_64 -net nic,macaddr=52:54:00:00:EE:03 -net vde ''disk_image''<br />
<br />
=== VDE2 Bridge ===<br />
<br />
Based on [https://selamatpagicikgu.wordpress.com/2011/06/08/quickhowto-qemu-networking-using-vde-tuntap-and-bridge/ quickhowto: qemu networking using vde, tun/tap, and bridge] graphic. Any virtual machine connected to vde is externally exposed. For example, each virtual machine can receive DHCP configuration directly from your ADSL router.<br />
<br />
==== Basics ====<br />
<br />
Remember that you need {{ic|tun}} module and {{Pkg|bridge-utils}} package.<br />
<br />
Create the vde2/tap device:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
# ip link set tap0 up<br />
<br />
Create bridge:<br />
<br />
# brctl addbr br0<br />
<br />
Add devices:<br />
<br />
# brctl addif br0 eth0<br />
# brctl addif br0 tap0<br />
<br />
And configure bridge interface:<br />
<br />
# dhcpcd br0<br />
<br />
==== Startup scripts ====<br />
<br />
All devices must be set up. And only the bridge needs an IP address. For physical devices on the bridge (e.g. {{ic|eth0}}), this can be done with [[netctl]] using a custom Ethernet profile with:<br />
<br />
{{hc|/etc/netctl/ethernet-noip|2=<br />
Description='A more versatile static Ethernet connection'<br />
Interface=eth0<br />
Connection=ethernet<br />
IP=no<br />
}}<br />
<br />
The following custom systemd service can be used to create and activate a VDE2 tap interface for use in the {{ic|users}} user group.<br />
<br />
{{hc|/etc/systemd/system/vde2@.service|2=<br />
[Unit]<br />
Description=Network Connectivity for %i<br />
Wants=network.target<br />
Before=network.target<br />
<br />
[Service]<br />
Type=oneshot<br />
RemainAfterExit=yes<br />
ExecStart=/usr/bin/vde_switch -tap %i -daemon -mod 660 -group users<br />
ExecStart=/usr/bin/ip link set dev %i up<br />
ExecStop=/usr/bin/ip addr flush dev %i<br />
ExecStop=/usr/bin/ip link set dev %i down<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
}}<br />
<br />
And finally, you can create the [[Bridge with netctl|bridge interface with netctl]].<br />
<br />
=== Shorthand configuration ===<br />
<br />
If you are using QEMU with various networking options a lot, you probably have created a lot of {{ic|-netdev}} and {{ic|-device}} argument pairs, which gets quite repetitive. You can instead use the {{ic|-nic}} argument to combine {{ic|-netdev}} and {{ic|-device}} together, so that, for example, these arguments:<br />
<br />
-netdev tap,id=network0,ifname=tap0,script=no,downscript=no,vhost=on -device virtio-net-pci,netdev=network0<br />
<br />
become:<br />
<br />
-nic tap,script=no,downscript=no,vhost=on,model=virtio-net-pci<br />
<br />
Notice the lack of network IDs, and that the device was created with {{ic|1=model=}}. The first half of the {{ic|-nic}} parameters are {{ic|-netdev}} parameters, whereas the second half (after {{ic|1=model=}}) are related with the device. The same parameters (for example, {{ic|1=smb=}}) are used. To completely disable the networking use {{ic|-nic none}}.<br />
<br />
See [https://qemu.weilnetz.de/doc/qemu-doc.html#Network-options QEMU networking documentation] for more information on parameters you can use.<br />
<br />
== Graphic card ==<br />
<br />
QEMU can emulate a standard graphic card text mode using {{ic|-curses}} command line option. This allows to type text and see text output directly inside a text terminal.<br />
<br />
QEMU can emulate several types of VGA card. The card type is passed in the {{ic|-vga ''type''}} command line option and can be {{ic|std}}, {{ic|qxl}}, {{ic|vmware}}, {{ic|virtio}}, {{ic|cirrus}} or {{ic|none}}.<br />
<br />
=== std ===<br />
<br />
With {{ic|-vga std}} you can get a resolution of up to 2560 x 1600 pixels without requiring guest drivers. This is the default since QEMU 2.2.<br />
<br />
=== qxl ===<br />
<br />
QXL is a paravirtual graphics driver with 2D support. To use it, pass the {{ic|-vga qxl}} option and install drivers in the guest. You may want to use [[#SPICE]] for improved graphical performance when using QXL.<br />
<br />
On Linux guests, the {{ic|qxl}} and {{ic|bochs_drm}} kernel modules must be loaded in order to gain a decent performance.<br />
<br />
Default VGA memory size for QXL devices is 16M which is sufficient to drive resolutions approximately up to QHD (2560x1440). To enable higher resolutions, [[#Multi-monitor support|increase vga_memmb]].<br />
<br />
=== vmware ===<br />
<br />
Although it is a bit buggy, it performs better than std and cirrus. Install the VMware drivers {{Pkg|xf86-video-vmware}} and {{Pkg|xf86-input-vmmouse}} for Arch Linux guests.<br />
<br />
=== virtio ===<br />
<br />
{{ic|virtio-vga}} / {{ic|virtio-gpu}} is a paravirtual 3D graphics driver based on [https://virgil3d.github.io/ virgl]. Currently a work in progress, supporting only very recent (>= 4.4) Linux guests with {{Pkg|mesa}} (>=11.2) compiled with the option {{ic|1=gallium-drivers=virgl}}.<br />
<br />
To enable 3D acceleration on the guest system select this vga with {{ic|-vga virtio}} and enable the opengl context in the display device with {{ic|1=-display sdl,gl=on}} or {{ic|1=-display gtk,gl=on}} for the sdl and gtk display output respectively. Successful configuration can be confirmed looking at the kernel log in the guest:<br />
<br />
{{hc|$ dmesg {{!}} grep drm |<br />
[drm] pci: virtio-vga detected<br />
[drm] virgl 3d acceleration enabled<br />
}}<br />
<br />
=== cirrus ===<br />
<br />
The cirrus graphical adapter was the default [http://wiki.qemu.org/ChangeLog/2.2#VGA before 2.2]. It [https://www.kraxel.org/blog/2014/10/qemu-using-cirrus-considered-harmful/ should not] be used on modern systems.<br />
<br />
=== none ===<br />
<br />
This is like a PC that has no VGA card at all. You would not even be able to access it with the {{ic|-vnc}} option. Also, this is different from the {{ic|-nographic}} option which lets QEMU emulate a VGA card, but disables the SDL display.<br />
<br />
== SPICE ==<br />
The [http://spice-space.org/ SPICE project] aims to provide a complete open source solution for remote access to virtual machines in a seamless way.<br />
=== Enabling SPICE support on the host ===<br />
The following is an example of booting with SPICE as the remote desktop protocol, including the support for copy and paste from host:<br />
<br />
$ qemu-system-x86_64 -vga qxl -device virtio-serial-pci -spice port=5930,disable-ticketing -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
The parameters have the following meaning:<br />
<br />
# {{ic|-device virtio-serial-pci}} adds a virtio-serial device<br />
# {{ic|1=-spice port=5930,disable-ticketing}} set TCP port {{ic|5930}} for spice channels listening and allow client to connect without authentication{{Tip|Using [[wikipedia:Unix_socket|Unix sockets]] instead of TCP ports does not involve using network stack on the host system. It does not imply that packets are encapsulated and decapsulated to use the network and the related protocol. The sockets are identified solely by the inodes on the hard drive. It is therefore considered better for performance. Use instead {{ic|1=-spice unix,addr=/tmp/vm_spice.socket,disable-ticketing}}.}}<br />
# {{ic|1=-device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0}} opens a port for spice vdagent in the virtio-serial device,<br />
# {{ic|1=-chardev spicevmc,id=spicechannel0,name=vdagent}} adds a spicevmc chardev for that port. It is important that the {{ic|1=chardev=}} option of the {{ic|virtserialport}} device matches the {{ic|1=id=}} option given to the {{ic|chardev}} option ({{ic|spicechannel0}} in this example). It is also important that the port name is {{ic|com.redhat.spice.0}}, because that is the namespace where vdagent is looking for in the guest. And finally, specify {{ic|1=name=vdagent}} so that spice knows what this channel is for.<br />
<br />
=== Connecting to the guest with a SPICE client ===<br />
<br />
A SPICE client is necessary to connect to the guest. In Arch, the following clients are available:<br />
<br />
{{App|virt-viewer|SPICE client recommended by the protocol developers, a subset of the virt-manager project.|https://virt-manager.org/|{{Pkg|virt-viewer}}}}<br />
<br />
{{App|spice-gtk|SPICE GTK client, a subset of the SPICE project. Embedded into other applications as a widget.|https://www.spice-space.org/|{{Pkg|spice-gtk}}}}<br />
<br />
For clients that run on smartphone or on other platforms, refer to the ''Other clients'' section in [http://www.spice-space.org/download.html spice-space download].<br />
<br />
==== Manually running a SPICE client ====<br />
<br />
One way of connecting to a guest listening on Unix socket {{ic|/tmp/vm_spice.socket}} is to manually run the SPICE client using {{ic|$ remote-viewer spice+unix:///tmp/vm_spice.socket}} or {{ic|1=$ spicy --uri="spice+unix:///tmp/vm_spice.socket"}}, depending on the desired client. Since QEMU in SPICE mode acts similarly to a remote desktop server, it may be more convenient to run QEMU in daemon mode with the {{ic|-daemonize}} parameter.<br />
<br />
{{Tip|To connect to the guest through SSH tunelling, the following type of command can be used: {{bc|$ ssh -fL 5999:localhost:5930 ''my.domain.org'' sleep 10; spicy -h 127.0.0.1 -p 5999}}<br />
This example connects ''spicy'' to the local port {{ic|5999}} which is forwarded through SSH to the guest's SPICE server located at the address ''my.domain.org'', port {{ic|5930}}.<br />
Note the {{ic|-f}} option that requests ssh to execute the command {{ic|sleep 10}} in the background. This way, the ssh session runs while the client is active and auto-closes once the client ends.<br />
}}<br />
<br />
==== Running a SPICE client with QEMU ====<br />
<br />
QEMU can automatically start a SPICE client with an appropriate socket, if the display is set to SPICE with the {{ic|-display spice-app}} parameter. This will use the system's default SPICE client as the viewer, determined by your [[XDG_MIME_Applications#mimeapps.list|mimeapps.list]] files.<br />
<br />
=== Enabling SPICE support on the guest ===<br />
<br />
For '''Arch Linux guests''', for improved support for multiple monitors or clipboard sharing, the following packages should be installed:<br />
* {{Pkg|spice-vdagent}}: Spice agent xorg client that enables copy and paste between client and X-session and more.<br />
* {{Pkg|xf86-video-qxl}}: Xorg X11 qxl video driver<br />
For guests under '''other operating systems''', refer to the ''Guest'' section in [http://www.spice-space.org/download.html spice-space download].<br />
<br />
=== Password authentication with SPICE ===<br />
<br />
If you want to enable password authentication with SPICE you need to remove {{ic|disable-ticketing}} from the {{ic|-spice}} argument and instead add {{ic|1=password=''yourpassword''}}. For example:<br />
<br />
$ qemu-system-x86_64 -vga qxl -spice port=5900,password=''yourpassword'' -device virtio-serial-pci -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
Your SPICE client should now ask for the password to be able to connect to the SPICE server.<br />
<br />
=== TLS encrypted communication with SPICE ===<br />
<br />
You can also configure TLS encryption for communicating with the SPICE server. First, you need to have a directory which contains the following files (the names must be exactly as indicated):<br />
<br />
* {{ic|ca-cert.pem}}: the CA master certificate.<br />
* {{ic|server-cert.pem}}: the server certificate signed with {{ic|ca-cert.pem}}.<br />
* {{ic|server-key.pem}}: the server private key.<br />
<br />
An example of generation of self-signed certificates with your own generated CA for your server is shown in the [https://www.spice-space.org/spice-user-manual.html#_generating_self_signed_certificates Spice User Manual].<br />
<br />
Afterwards, you can run QEMU with SPICE as explained above but using the following {{ic|-spice}} argument: {{ic|1=-spice tls-port=5901,password=''yourpassword'',x509-dir=''/path/to/pki_certs''}}, where {{ic|''/path/to/pki_certs''}} is the directory path that contains the three needed files shown earlier.<br />
<br />
It is now possible to connect to the server using {{pkg|virt-viewer}}:<br />
<br />
$ remote-viewer spice://''hostname''?tls-port=5901 --spice-ca-file=''/path/to/ca-cert.pem'' --spice-host-subject="C=''XX'',L=''city'',O=''organization'',CN=''hostname''" --spice-secure-channels=all<br />
<br />
Keep in mind that the {{ic|--spice-host-subject}} parameter needs to be set according to your {{ic|server-cert.pem}} subject. You also need to copy {{ic|ca-cert.pem}} to every client to verify the server certificate.<br />
<br />
{{Tip|You can get the subject line of the server certificate in the correct format for {{ic|--spice-host-subject}} (with entries separated by commas) using the following command: {{bc|<nowiki>$ openssl x509 -noout -subject -in server-cert.pem | cut -d' ' -f2- | sed 's/\///' | sed 's/\//,/g'</nowiki>}}<br />
}}<br />
<br />
The equivalent {{Pkg|spice-gtk}} command is:<br />
<br />
$ spicy -h ''hostname'' -s 5901 --spice-ca-file=ca-cert.pem --spice-host-subject="C=''XX'',L=''city'',O=''organization'',CN=''hostname''" --spice-secure-channels=all<br />
<br />
== VNC ==<br />
<br />
One can add the {{ic|-vnc :''X''}} option to have QEMU redirect the VGA display to the VNC session. Substitute {{ic|''X''}} for the number of the display (0 will then listen on 5900, 1 on 5901...).<br />
<br />
$ qemu-system-x86_64 -vnc :0<br />
<br />
An example is also provided in the [[#Starting QEMU virtual machines on boot]] section.<br />
{{Warning|The default VNC server setup does not use any form of authentication. Any user can connect from any host.}}<br />
<br />
=== Basic password authentication ===<br />
<br />
An access password can be setup easily by using the {{ic|password}} option. The password must be indicated in the QEMU monitor and connection is only possible once the password is provided.<br />
<br />
$ qemu-system-x86_64 -vnc :0,password -monitor stdio<br />
<br />
In the QEMU monitor, password is set using the command {{ic|change vnc password}} and then indicating the password.<br />
<br />
The following command line directly runs vnc with a password:<br />
<br />
$ printf "change vnc password\n%s\n" MYPASSWORD | qemu-system-x86_64 -vnc :0,password -monitor stdio<br />
<br />
{{Note|The password is limited to 8 characters and can be guessed through brute force attack. More elaborated protection is strongly recommended for public network.}}<br />
<br />
== Audio ==<br />
<br />
=== Host ===<br />
<br />
The {{ic|-audiodev}} flag sets the audio backend driver and its options. The list of available audio backend drivers and their optional settings is detailed in the {{man|1|qemu}}. man page.<br />
<br />
At the bare minimum, you need to choose a driver and set an id.<br />
<br />
-audiodev pa,id=snd0<br />
<br />
=== Guest ===<br />
<br />
==== With audiodev ====<br />
<br />
===== Intel HD Audio =====<br />
<br />
For Intel HD Audio emulation add both controller and codec devices. To list the available Intel HDA Audio devices:<br />
<br />
$ qemu-system-x86_64 -device help | grep hda<br />
<br />
Add the audio controller<br />
<br />
-device ich9-intel-hda<br />
<br />
Add the audio codec and map it to a host audio backend id<br />
<br />
-device hda-output,audiodev=snd0<br />
<br />
===== Intel 82801AA AC97 =====<br />
<br />
For AC97 emulation just add the audio card device and map it to a host audio backend id<br />
<br />
-device AC97,audiodev=snd0<br />
<br />
==== Without audiodev ====<br />
<br />
To get list of the supported emulation audio drivers:<br />
$ qemu-system-x86_64 -soundhw help<br />
<br />
To use e.g. {{ic|hda}} driver for the guest use the {{ic|-device intel-hda -device hda-duplex}} command with QEMU.<br />
<br />
{{Note|Video graphic card emulated drivers for the guest machine may also cause a problem with the sound quality. Test one by one to make it work. You can list possible options with {{ic|<nowiki>qemu-system-x86_64 -h | grep vga</nowiki>}}.}}<br />
<br />
== Installing virtio drivers ==<br />
<br />
QEMU offers guests the ability to use paravirtualized block and network devices using the [http://wiki.libvirt.org/page/Virtio virtio] drivers, which provide better performance and lower overhead.<br />
<br />
* A virtio block device requires the option {{Ic|-drive}} for passing a disk image, with parameter {{Ic|1=if=virtio}}:<br />
$ qemu-system-x86_64 -boot order=c -drive file=''disk_image'',if=virtio<br />
<br />
* Almost the same goes for the network:<br />
$ qemu-system-x86_64 -nic user,model=virtio-net-pci<br />
<br />
{{Note|This will only work if the guest machine has drivers for virtio devices. Linux does, and the required drivers are included in Arch Linux, but there is no guarantee that virtio devices will work with other operating systems.}}<br />
<br />
=== Preparing an (Arch) Linux guest ===<br />
<br />
To use virtio devices after an Arch Linux guest has been installed, the following modules must be loaded in the guest: {{Ic|virtio}}, {{Ic|virtio_pci}}, {{Ic|virtio_blk}}, {{Ic|virtio_net}}, and {{Ic|virtio_ring}}. For 32-bit guests, the specific "virtio" module is not necessary.<br />
<br />
If you want to boot from a virtio disk, the initial ramdisk must contain the necessary modules. By default, this is handled by [[mkinitcpio]]'s {{ic|autodetect}} hook. Otherwise use the {{ic|MODULES}} array in {{ic|/etc/mkinitcpio.conf}} to include the necessary modules and rebuild the initial ramdisk.<br />
<br />
{{hc|/etc/mkinitcpio.conf|2=<br />
MODULES=(virtio virtio_blk virtio_pci virtio_net)}}<br />
<br />
Virtio disks are recognized with the prefix {{ic|'''v'''}} (e.g. {{ic|'''v'''da}}, {{ic|'''v'''db}}, etc.); therefore, changes must be made in at least {{ic|/etc/fstab}} and {{ic|/boot/grub/grub.cfg}} when booting from a virtio disk.<br />
<br />
{{Tip|When referencing disks by [[UUID]] in both {{ic|/etc/fstab}} and bootloader, nothing has to be done.}}<br />
<br />
Further information on paravirtualization with KVM can be found [http://www.linux-kvm.org/page/Boot_from_virtio_block_device here].<br />
<br />
You might also want to install {{Pkg|qemu-guest-agent}} to implement support for QMP commands that will enhance the hypervisor management capabilities. After installing the package you can enable and start the {{ic|qemu-ga.service}}.<br />
<br />
=== Preparing a Windows guest ===<br />
<br />
==== Block device drivers ====<br />
<br />
===== New Install of Windows =====<br />
<br />
Windows does not come with the virtio drivers. Therefore, you will need to load them during installation. There are basically two ways to do this: via Floppy Disk or via ISO files. Both images can be downloaded from the [https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/stable-virtio/virtio-win.iso Fedora repository].<br />
<br />
The floppy disk option is difficult because you will need to press F6 (Shift-F6 on newer Windows) at the very beginning of powering on the QEMU. This is difficult since you need time to connect your VNC console window. You can attempt to add a delay to the boot sequence. See {{man|1|qemu}} for more details about applying a delay at boot.<br />
<br />
The ISO option to load drivers is the preferred way, but it is available only on Windows Vista and Windows Server 2008 and later. The procedure is to load the image with virtio drivers in an additional cdrom device along with the primary disk device and Windows installer:<br />
<br />
$ qemu-system-x86_64 ... \<br />
-drive file=''windows_disk_image'',index=0,media=disk,if=virtio \<br />
-drive file=''windows.iso'',index=2,media=cdrom \<br />
-drive file=''virtio.iso'',index=3,media=cdrom \<br />
...<br />
<br />
During the installation, at some stage, the Windows installer will ask "Where do you want to install Windows?", it will give a warning that no disks are found. Follow the example instructions below (based on Windows Server 2012 R2 with Update).<br />
<br />
* Select the option ''Load Drivers''.<br />
* Uncheck the box for ''Hide drivers that aren't compatible with this computer's hardware''.<br />
* Click the browse button and open the CDROM for the virtio iso, usually named "virtio-win-XX".<br />
* Now browse to {{ic|E:\viostor\[your-os]\amd64}}, select it, and confirm.<br />
<br />
You should now see your virtio disk(s) listed here, ready to be selected, formatted and installed to.<br />
<br />
===== Change Existing Windows VM to use virtio =====<br />
<br />
Modifying an existing Windows guest for booting from virtio disk requires that the virtio driver is available in the guest and that it is loaded at boot time.<br />
<br />
One can find the virtio disk driver in the [https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/stable-virtio/virtio-win.iso Fedora repository].<br />
<br />
Now, create a new disk image that will be used to search for the virtio driver:<br />
<br />
$ qemu-img create -f qcow2 ''fake.qcow2'' 1G<br />
<br />
Run the original Windows guest (with the boot disk still in IDE mode) with the fake disk (in virtio mode) and a CD-ROM with the driver.<br />
<br />
$ qemu-system-x86_64 -m 512 -drive file=''windows_disk_image'',if=ide -drive file=''fake.qcow2'',if=virtio -cdrom virtio-win-0.1-81.iso<br />
<br />
Windows will detect the fake disk and look for a suitable driver. If it fails, go to ''Device Manager'', locate the SCSI drive with an exclamation mark icon (should be open), click ''Update driver'' and select the virtual CD-ROM. Do not navigate to the driver folder within the CD-ROM, simply select the CD-ROM drive and Windows will find the appropriate driver automatically (tested for Windows 7 SP1).<br />
<br />
Request Windows to boot in safe mode next time it starts up. This can be done using the ''msconfig.exe'' tool in Windows. In safe mode all the drivers will be loaded at boot time including the new virtio driver. Once Windows knows that the virtio driver is required at boot it will memorize it for future boot.<br />
<br />
Once instructed to boot in safe mode, you can turn off the virtual machine and launch it again, now with the boot disk attached in virtio mode:<br />
<br />
$ qemu-system-x86_64 -m 512 -drive file=''windows_disk_image'',if=virtio<br />
<br />
You should boot in safe mode with virtio driver loaded, you can now return to ''msconfig.exe'' disable safe mode boot and restart Windows.<br />
<br />
{{Note|If you encounter the blue screen of death using the {{ic|1=if=virtio}} parameter, it probably means the virtio disk driver is not installed or not loaded at boot time, reboot in safe mode and check your driver configuration.}}<br />
<br />
==== Network drivers ====<br />
<br />
Installing virtio network drivers is a bit easier, simply add the {{ic|-nic}} argument.<br />
<br />
$ qemu-system-x86_64 -m 512 -drive file=''windows_disk_image'',if=virtio -nic user,model=virtio-net-pci -cdrom virtio-win-0.1-74.iso<br />
<br />
Windows will detect the network adapter and try to find a driver for it. If it fails, go to the ''Device Manager'', locate the network adapter with an exclamation mark icon (should be open), click ''Update driver'' and select the virtual CD-ROM. Do not forget to select the checkbox which says to search for directories recursively.<br />
<br />
==== Balloon driver ====<br />
<br />
If you want to track you guest memory state (for example via {{ic|virsh}} command {{ic|dommemstat}}) or change guest's memory size in runtime (you still will not be able to change memory size, but can limit memory usage via inflating balloon driver) you will need to install guest balloon driver.<br />
<br />
For this you will need to go to ''Device Manager'', locate ''PCI standard RAM Controller'' in ''System devices'' (or unrecognized PCI controller from ''Other devices'') and choose ''Update driver''. In opened window you will need to choose ''Browse my computer...'' and select the CD-ROM (and do not forget the ''Include subdirectories'' checkbox). Reboot after installation. This will install the driver and you will be able to inflate the balloon (for example via hmp command {{ic|balloon ''memory_size''}}, which will cause balloon to take as much memory as possible in order to shrink the guest's available memory size to ''memory_size''). However, you still will not be able to track guest memory state. In order to do this you will need to install ''Balloon'' service properly. For that open command line as administrator, go to the CD-ROM, ''Balloon'' directory and deeper, depending on your system and architecture. Once you are in ''amd64'' (''x86'') directory, run {{ic|blnsrv.exe -i}} which will do the installation. After that {{ic|virsh}} command {{ic|dommemstat}} should be outputting all supported values.<br />
<br />
=== Preparing a FreeBSD guest ===<br />
<br />
Install the {{ic|emulators/virtio-kmod}} port if you are using FreeBSD 8.3 or later up until 10.0-CURRENT where they are included into the kernel. After installation, add the following to your {{ic|/boot/loader.conf}} file:<br />
<br />
{{bc|1=<br />
virtio_load="YES"<br />
virtio_pci_load="YES"<br />
virtio_blk_load="YES"<br />
if_vtnet_load="YES"<br />
virtio_balloon_load="YES"<br />
}}<br />
<br />
Then modify your {{ic|/etc/fstab}} by doing the following:<br />
<br />
# sed -ibak "s/ada/vtbd/g" /etc/fstab<br />
<br />
And verify that {{ic|/etc/fstab}} is consistent. If anything goes wrong, just boot into a rescue CD and copy {{ic|/etc/fstab.bak}} back to {{ic|/etc/fstab}}.<br />
<br />
== QEMU monitor ==<br />
<br />
While QEMU is running, a monitor console is provided in order to provide several ways to interact with the virtual machine running. The QEMU monitor offers interesting capabilities such as obtaining information about the current virtual machine, hotplugging devices, creating snapshots of the current state of the virtual machine, etc. To see the list of all commands, run {{ic|help}} or {{ic|?}} in the QEMU monitor console or review the relevant section of the [https://qemu.weilnetz.de/doc/qemu-doc.html#pcsys_005fmonitor official QEMU documentation].<br />
<br />
=== Accessing the monitor console ===<br />
<br />
==== Graphical view ====<br />
<br />
When using the {{ic|std}} default graphics option, one can access the QEMU monitor by pressing {{ic|Ctrl+Alt+2}} or by clicking ''View > compatmonitor0'' in the QEMU window. To return to the virtual machine graphical view either press {{ic|Ctrl+Alt+1}} or click ''View > VGA''.<br />
<br />
However, the standard method of accessing the monitor is not always convenient and does not work in all graphic outputs QEMU supports.<br />
<br />
==== Telnet ====<br />
<br />
To enable [[telnet]], run QEMU with the {{ic|-monitor telnet:127.0.0.1:''port'',server,nowait}} parameter. When the virtual machine is started you will be able to access the monitor via telnet:<br />
<br />
$ telnet 127.0.0.1 ''port''<br />
<br />
{{Note|If {{ic|127.0.0.1}} is specified as the IP to listen it will be only possible to connect to the monitor from the same host QEMU is running on. If connecting from remote hosts is desired, QEMU must be told to listen {{ic|0.0.0.0}} as follows: {{ic|-monitor telnet:0.0.0.0:''port'',server,nowait}}. Keep in mind that it is recommended to have a [[firewall]] configured in this case or make sure your local network is completely trustworthy since this connection is completely unauthenticated and unencrypted.}}<br />
<br />
==== UNIX socket ====<br />
<br />
Run QEMU with the {{ic|-monitor unix:''socketfile'',server,nowait}} parameter. Then you can connect with either {{pkg|socat}} or {{pkg|openbsd-netcat}}.<br />
<br />
For example, if QEMU is run via:<br />
<br />
$ qemu-system-x86_64 ''[...]'' -monitor unix:/tmp/monitor.sock,server,nowait ''[...]''<br />
<br />
It is possible to connect to the monitor with:<br />
<br />
$ socat - UNIX-CONNECT:/tmp/monitor.sock<br />
<br />
Or with:<br />
<br />
$ nc -U /tmp/monitor.sock<br />
<br />
==== TCP ====<br />
<br />
You can expose the monitor over TCP with the argument {{ic|-monitor tcp:127.0.0.1:''port'',server,nowait}}. Then connect with netcat, either {{pkg|openbsd-netcat}} or {{pkg|gnu-netcat}} by running:<br />
<br />
$ nc 127.0.0.1 ''port''<br />
<br />
{{Note|In order to be able to connect to the tcp socket from other devices other than the same host QEMU is being run on you need to listen to {{ic|0.0.0.0}} like explained in the telnet case. The same security warnings apply in this case as well.}}<br />
<br />
==== Standard I/O ====<br />
<br />
It is possible to access the monitor automatically from the same terminal QEMU is being run by running it with the argument {{ic|-monitor stdio}}.<br />
<br />
=== Sending keyboard presses to the virtual machine using the monitor console ===<br />
<br />
Some combinations of keys may be difficult to perform on virtual machines due to the host intercepting them instead in some configurations (a notable example is the {{ic|Ctrl+Alt+F*}} key combinations, which change the active tty). To avoid this problem, the problematic combination of keys may be sent via the monitor console instead. Switch to the monitor and use the {{ic|sendkey}} command to forward the necessary keypresses to the virtual machine. For example:<br />
<br />
(qemu) sendkey ctrl-alt-f2<br />
<br />
=== Creating and managing snapshots via the monitor console ===<br />
<br />
{{Note|This feature will '''only''' work when the virtual machine disk image is in ''qcow2'' format. It will not work with ''raw'' images.}}<br />
<br />
It is sometimes desirable to save the current state of a virtual machine and having the possibility of reverting the state of the virtual machine to that of a previously saved snapshot at any time. The QEMU monitor console provides the user with the necessary utilities to create snapshots, manage them, and revert the machine state to a saved snapshot.<br />
<br />
* Use {{ic|savevm ''name''}} in order to create a snapshot with the tag ''name''.<br />
* Use {{ic|loadvm ''name''}} to revert the virtual machine to the state of the snapshot ''name''.<br />
* Use {{ic|delvm ''name''}} to delete the snapshot tagged as ''name''.<br />
* Use {{ic|info snapshots}} to see a list of saved snapshots. Snapshots are identified by both an auto-incremented ID number and a text tag (set by the user on snapshot creation).<br />
<br />
=== Running the virtual machine in immutable mode ===<br />
<br />
It is possible to run a virtual machine in a frozen state so that all changes will be discarded when the virtual machine is powered off just by running QEMU with the {{ic|-snapshot}} parameter. When the disk image is written by the guest, changes will be saved in a temporary file in {{ic|/tmp}} and will be discarded when QEMU halts.<br />
<br />
However, if a machine is running in frozen mode it is still possible to save the changes to the disk image if it is afterwards desired by using the monitor console and running the following command:<br />
<br />
(qemu) commit all<br />
<br />
If snapshots are created when running in frozen mode they will be discarded as soon as QEMU is exited unless changes are explicitly commited to disk, as well.<br />
<br />
=== Pause and power options via the monitor console ===<br />
<br />
Some operations of a physical machine can be emulated by QEMU using some monitor commands:<br />
<br />
* {{ic|system_powerdown}} will send an ACPI shutdown request to the virtual machine. This effect is similar to the power button in a physical machine.<br />
* {{ic|system_reset}} will reset the virtual machine similarly to a reset button in a physical machine. This operation can cause data loss and file system corruption since the virtual machine is not cleanly restarted.<br />
* {{ic|stop}} will pause the virtual machine.<br />
* {{ic|cont}} will resume a virtual machine previously paused.<br />
<br />
=== Taking screenshots of the virtual machine ===<br />
<br />
Screenshots of the virtual machine graphic display can be obtained in the PPM format by running the following command in the monitor console:<br />
<br />
(qemu) screendump ''file.ppm''<br />
<br />
== QEMU machine protocol ==<br />
<br />
The QEMU machine protocol (QMP) is a JSON-based protocol which allows applications to control a QEMU instance. Similarly to the [[#QEMU monitor]] it offers ways to interact with a running machine and the JSON protocol allows to do it programmatically. The description of all the QMP commands can be found in [https://raw.githubusercontent.com/coreos/qemu/master/qmp-commands.hx qmp-commands].<br />
<br />
=== Start QMP ===<br />
<br />
The usual way to control the guest using the QMP protocol, is to open a TCP socket when launching the machine using the {{ic|-qmp}} option. Here it is using for example the TCP port 4444:<br />
<br />
$ qemu-system-x86_64 ''[...]'' -qmp tcp:localhost:4444,server,nowait<br />
<br />
Then one way to communicate with the QMP agent is to use [[netcat]]:<br />
<br />
{{hc|nc localhost 4444|{"QMP": {"version": {"qemu": {"micro": 0, "minor": 1, "major": 3}, "package": ""}, "capabilities": []} } }}<br />
<br />
At this stage, the only command that can be recognized is {{ic|qmp_capabilities}}, so that QMP enters into command mode. Type:<br />
<br />
{"execute": "qmp_capabilities"}<br />
<br />
Now, QMP is ready to receive commands, to retrieve the list of recognized commands, use:<br />
<br />
{"execute": "query-commands"}<br />
<br />
=== Live merging of child image into parent image ===<br />
<br />
It is possible to merge a running snapshot into its parent by issuing a {{ic|block-commit}} command. In its simplest form the following line will commit the child into its parent:<br />
<br />
{"execute": "block-commit", "arguments": {"device": "''devicename''"}}<br />
<br />
Upon reception of this command, the handler looks for the base image and converts it from read only to read write mode and then runs the commit job.<br />
<br />
Once the ''block-commit'' operation has completed, the event {{ic|BLOCK_JOB_READY}} will be emitted, signalling that the synchronization has finished. The job can then be gracefully completed by issuing the command {{ic|block-job-complete}}:<br />
<br />
{"execute": "block-job-complete", "arguments": {"device": "''devicename''"}}<br />
<br />
Until such a command is issued, the ''commit'' operation remains active.<br />
After successful completion, the base image remains in read write mode and becomes the new active layer. On the other hand, the child image becomes invalid and it is the responsibility of the user to clean it up.<br />
<br />
{{Tip|The list of device and their names can be retrieved by executing the command {{ic|query-block}} and parsing the results. The device name is in the {{ic|device}} field, for example {{ic|ide0-hd0}} for the hard disk in this example: {{hc|{"execute": "query-block"}|{"return": [{"io-status": "ok", "device": "'''ide0-hd0'''", "locked": false, "removable": false, "inserted": {"iops_rd": 0, "detect_zeroes": "off", "image": {"backing-image": {"virtual-size": 27074281472, "filename": "parent.qcow2", ... } }} }}<br />
<br />
=== Live creation of a new snapshot ===<br />
<br />
To create a new snapshot out of a running image, run the command:<br />
<br />
{"execute": "blockdev-snapshot-sync", "arguments": {"device": "''devicename''","snapshot-file": "''new_snapshot_name''.qcow2"}}<br />
<br />
This creates an overlay file named {{ic|''new_snapshot_name''.qcow2}} which then becomes the new active layer.<br />
<br />
== Tips and tricks ==<br />
=== Improve virtual machine performance ===<br />
<br />
There are a number of techniques that you can use to improve the performance of the virtual machine. For example:<br />
<br />
* Apply [[#Enabling KVM]]: add {{ic|-enable-kvm}} to the QEMU start command you use.<br />
* Use the {{ic|-cpu host}} option to make QEMU emulate the host's exact CPU. If you do not do this, it may be trying to emulate a more generic CPU.<br />
* Especially for Windows guests, enable [http://blog.wikichoon.com/2014/07/enabling-hyper-v-enlightenments-with-kvm.html Hyper-V enlightenments]: {{ic|1=-cpu host,hv_relaxed,hv_spinlocks=0x1fff,hv_vapic,hv_time}}.<br />
* If the host machine has multiple cores, assign the guest more cores using the {{ic|-smp}} option.<br />
* Make sure you have assigned the virtual machine enough memory. By default, QEMU only assigns 128 MiB of memory to each virtual machine. Use the {{ic|-m}} option to assign more memory. For example, {{ic|-m 1024}} runs a virtual machine with 1024 MiB of memory.<br />
* If supported by drivers in the guest operating system, use [http://wiki.libvirt.org/page/Virtio virtio] for network and/or block devices. For example:<br />
$ qemu-system-x86_64 -net nic,model=virtio -net tap,if=tap0,script=no -drive file=''disk_image'',media=disk,if=virtio<br />
* Use TAP devices instead of user-mode networking. See [[#Tap networking with QEMU]].<br />
* If the guest OS is doing heavy writing to its disk, you may benefit from certain mount options on the host's file system. For example, you can mount an [[Ext4|ext4 file system]] with the option {{ic|1=barrier=0}}. You should read the documentation for any options that you change because sometimes performance-enhancing options for file systems come at the cost of data integrity.<br />
* If you have a raw disk image, you may want to disable the cache:<br />
$ qemu-system-x86_64 -drive file=''disk_image'',if=virtio,'''cache=none'''<br />
* Use the native Linux AIO:<br />
$ qemu-system-x86_64 -drive file=''disk_image'',if=virtio''',aio=native,cache.direct=on'''<br />
* If you are running multiple virtual machines concurrently that all have the same operating system installed, you can save memory by enabling [[wikipedia:Kernel_SamePage_Merging_(KSM)|kernel same-page merging]]. See [[#Enabling KSM]].<br />
* In some cases, memory can be reclaimed from running virtual machines by running a memory ballooning driver in the guest operating system and launching QEMU using {{ic|-device virtio-balloon}}.<br />
* It is possible to use a emulation layer for an ICH-9 AHCI controller (although it may be unstable). The AHCI emulation supports [[Wikipedia:Native_Command_Queuing|NCQ]], so multiple read or write requests can be outstanding at the same time:<br />
$ qemu-system-x86_64 -drive id=disk,file=''disk_image'',if=none -device ich9-ahci,id=ahci -device ide-drive,drive=disk,bus=ahci.0<br />
<br />
See http://www.linux-kvm.org/page/Tuning_KVM for more information.<br />
<br />
=== Starting QEMU virtual machines on boot ===<br />
<br />
==== With libvirt ====<br />
<br />
If a virtual machine is set up with [[libvirt]], it can be configured with {{ic|virsh autostart}} or through the ''virt-manager'' GUI to start at host boot by going to the Boot Options for the virtual machine and selecting "Start virtual machine on host boot up".<br />
<br />
==== With systemd service ====<br />
<br />
To run QEMU VMs on boot, you can use following systemd unit and config.<br />
<br />
{{hc|/etc/systemd/system/qemu@.service|2=<br />
[Unit]<br />
Description=QEMU virtual machine<br />
<br />
[Service]<br />
Environment="haltcmd=kill -INT $MAINPID"<br />
EnvironmentFile=/etc/conf.d/qemu.d/%i<br />
ExecStart=/usr/bin/qemu-system-x86_64 -name %i -enable-kvm -m 512 -nographic $args<br />
ExecStop=/usr/bin/bash -c ${haltcmd}<br />
ExecStop=/usr/bin/bash -c 'while nc localhost 7100; do sleep 1; done'<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
}}<br />
<br />
{{Note|This service will wait for the console port to be released, which means that the VM has been shutdown, to graciously end.}}<br />
<br />
Then create per-VM configuration files, named {{ic|/etc/conf.d/qemu.d/''vm_name''}}, with the variables {{ic|args}} and {{ic|haltcmd}} set. Example configs:<br />
<br />
{{hc|/etc/conf.d/qemu.d/one|2=<br />
args="-hda /dev/vg0/vm1 -serial telnet:localhost:7000,server,nowait,nodelay \<br />
-monitor telnet:localhost:7100,server,nowait,nodelay -vnc :0"<br />
<br />
haltcmd="echo 'system_powerdown' {{!}} nc localhost 7100" # or netcat/ncat}}<br />
<br />
{{hc|/etc/conf.d/qemu.d/two|2=<br />
args="-hda /srv/kvm/vm2 -serial telnet:localhost:7001,server,nowait,nodelay -vnc :1"<br />
<br />
haltcmd="ssh powermanager@vm2 sudo poweroff"}}<br />
<br />
The description of the variables is the following:<br />
<br />
* {{ic|args}} - QEMU command line arguments to be used.<br />
* {{ic|haltcmd}} - Command to shut down a VM safely. In the first example, the QEMU monitor is exposed via telnet using {{ic|-monitor telnet:..}} and the VMs are powered off via ACPI by sending {{ic|system_powerdown}} to monitor with the {{ic|nc}} command. In the other example, SSH is used.<br />
<br />
To set which virtual machines will start on boot-up, [[enable]] the {{ic|qemu@''vm_name''.service}} systemd unit.<br />
<br />
=== Mouse integration ===<br />
<br />
To prevent the mouse from being grabbed when clicking on the guest operating system's window, add the options {{ic|-usb -device usb-tablet}}. This means QEMU is able to report the mouse position without having to grab the mouse. This also overrides PS/2 mouse emulation when activated. For example:<br />
<br />
$ qemu-system-x86_64 -hda ''disk_image'' -m 512 -usb -device usb-tablet<br />
<br />
If that does not work, try using {{ic|-vga qxl}} parameter, also look at the instructions [[#Mouse cursor is jittery or erratic]].<br />
<br />
=== Pass-through host USB device ===<br />
<br />
It is possible to access the physical device connected to a USB port of the host from the guest. The first step is to identify where the device is connected, this can be found running the {{ic|lsusb}} command. For example:<br />
<br />
{{hc|$ lsusb|<br />
...<br />
Bus '''003''' Device '''007''': ID '''0781''':'''5406''' SanDisk Corp. Cruzer Micro U3<br />
}}<br />
<br />
The outputs in bold above will be useful to identify respectively the ''host_bus'' and ''host_addr'' or the ''vendor_id'' and ''product_id''.<br />
<br />
In qemu, the idea is to emulate an EHCI (USB 2) or XHCI (USB 3) controller with the option {{ic|1=-device usb-ehci,id=ehci}} or {{ic|1=-device qemu-xhci,id=xhci}} respectively and then attach the physical device to it with the option {{ic|1=-device usb-host,..}}. We will consider that ''controller_id'' is either {{ic|ehci}} or {{ic|xhci}} for the rest of this section.<br />
<br />
Then, there are two ways to connect to the USB of the host with qemu:<br />
<br />
# Identify the device and connect to it on any bus and address it is attached to on the host, the generic syntax is: {{bc|1=-device usb-host,bus=''controller_id''.0,vendorid=0x''vendor_id'',productid=0x''product_id''}}Applied to the device used in the example above, it becomes:{{bc|1=-device usb-ehci,id=ehci -device usb-host,bus=ehci.0,vendorid=0x'''0781''',productid=0x'''5406'''}}One can also add the {{ic|1=...,port=''port_number''}} setting to the previous option to specify in which physical port of the virtual controller the device should be attached, useful in the case one wants to add multiple usb devices to the VM. Another option is to use the new {{ic|usb-host}} {{ic|hostdevice}} property which is available since this [https://git.qemu.org/?p=qemu.git;a=commit;h=9f815e83e983d247a3cd67579d2d9c1765adc644 commit] (QEMU 5.1.0+), the syntax is: {{bc|1=-device qemu-xhci,id=xhci -device usb-host,bus=xhci.0,hostdevice=/dev/bus/usb/003/007}}<br />
# Attach whatever is connected to a given USB bus and address, the syntax is:{{bc|1=-device usb-host,bus=''controller_id''.0,hostbus=''host_bus'',host_addr=''host_addr''}}Applied to the bus and the address in the example above, it becomes:{{bc|1=-device usb-ehci,id=ehci -device usb-host,bus=ehci.0,hostbus='''3''',hostaddr='''7'''}}<br />
<br />
{{Note|If you encounter permission errors when running QEMU, see [[udev#About udev rules]] for information on how to set permissions of the device.}}<br />
<br />
=== USB redirection with SPICE ===<br />
<br />
When using [[#SPICE]] it is possible to redirect USB devices from the client to the virtual machine without needing to specify them in the QEMU command. It is possible to configure the number of USB slots available for redirected devices (the number of slots will determine the maximum number of devices which can be redirected simultaneously). The main advantages of using SPICE for redirection compared to the previously-mentioned {{ic|-usbdevice}} method is the possibility of hot-swapping USB devices after the virtual machine has started, without needing to halt it in order to remove USB devices from the redirection or adding new ones. This method of USB redirection also allows us to redirect USB devices over the network, from the client to the server. In summary, it is the most flexible method of using USB devices in a QEMU virtual machine.<br />
<br />
We need to add one EHCI/UHCI controller per available USB redirection slot desired as well as one SPICE redirection channel per slot. For example, adding the following arguments to the QEMU command you use for starting the virtual machine in SPICE mode will start the virtual machine with three available USB slots for redirection:<br />
<br />
{{bc|1=-device ich9-usb-ehci1,id=usb \<br />
-device ich9-usb-uhci1,masterbus=usb.0,firstport=0,multifunction=on \<br />
-device ich9-usb-uhci2,masterbus=usb.0,firstport=2 \<br />
-device ich9-usb-uhci3,masterbus=usb.0,firstport=4 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev1 -device usb-redir,chardev=usbredirchardev1,id=usbredirdev1 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev2 -device usb-redir,chardev=usbredirchardev2,id=usbredirdev2 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev3 -device usb-redir,chardev=usbredirchardev3,id=usbredirdev3}}<br />
See [https://www.spice-space.org/usbredir.html SPICE/usbredir] for more information.<br />
<br />
Both {{ic|spicy}} from {{Pkg|spice-gtk}} (''Input > Select USB Devices for redirection'') and {{ic|remote-viewer}} from {{pkg|virt-viewer}} (''File > USB device selection'') support this feature. Please make sure that you have installed the necessary SPICE Guest Tools on the virtual machine for this functionality to work as expected (see the [[#SPICE]] section for more information).<br />
<br />
{{Warning|Keep in mind that when a USB device is redirected from the client, it will not be usable from the client operating system itself until the redirection is stopped. It is specially important to never redirect the input devices (namely mouse and keyboard), since it will be then difficult to access the SPICE client menus to revert the situation, because the client will not respond to the input devices after being redirected to the virtual machine.}}<br />
<br />
=== Enabling KSM ===<br />
<br />
Kernel Samepage Merging (KSM) is a feature of the Linux kernel that allows for an application to register with the kernel to have its pages merged with other processes that also register to have their pages merged. The KSM mechanism allows for guest virtual machines to share pages with each other. In an environment where many of the guest operating systems are similar, this can result in significant memory savings.<br />
<br />
{{Note|Although KSM may reduce memory usage, it may increase CPU usage. Also note some security issues may occur, see [[Wikipedia:Kernel same-page merging]].}}<br />
<br />
To enable KSM:<br />
<br />
# echo 1 > /sys/kernel/mm/ksm/run<br />
<br />
To make it permanent, use [[systemd#systemd-tmpfiles - temporary files|systemd's temporary files]]:<br />
<br />
{{hc|/etc/tmpfiles.d/ksm.conf|<br />
w /sys/kernel/mm/ksm/run - - - - 1<br />
}}<br />
<br />
If KSM is running, and there are pages to be merged (i.e. at least two similar VMs are running), then {{ic|/sys/kernel/mm/ksm/pages_shared}} should be non-zero. See https://www.kernel.org/doc/html/latest/admin-guide/mm/ksm.html for more information.<br />
<br />
{{Tip|An easy way to see how well KSM is performing is to simply print the contents of all the files in that directory: {{bc|$ grep . /sys/kernel/mm/ksm/*}}}}<br />
<br />
=== Multi-monitor support ===<br />
<br />
The Linux QXL driver supports four heads (virtual screens) by default. This can be changed via the {{ic|1=qxl.heads=N}} kernel parameter.<br />
<br />
The default VGA memory size for QXL devices is 16M (VRAM size is 64M). This is not sufficient if you would like to enable two 1920x1200 monitors since that requires 2 × 1920 × 4 (color depth) × 1200 = 17.6 MiB VGA memory. This can be changed by replacing {{ic|-vga qxl}} by {{ic|<nowiki>-vga none -device qxl-vga,vgamem_mb=32</nowiki>}}. If you ever increase vgamem_mb beyond 64M, then you also have to increase the {{ic|vram_size_mb}} option.<br />
<br />
=== Copy and paste ===<br />
<br />
One way to share the clipboard between the host and the guest is to enable the SPICE remote desktop protocol and access the client with a SPICE client.<br />
One needs to follow the steps described in [[#SPICE]]. A guest run this way will support copy paste with the host.<br />
<br />
=== Windows-specific notes ===<br />
<br />
QEMU can run any version of Windows from Windows 95 through Windows 10.<br />
<br />
It is possible to run [[Windows PE]] in QEMU.<br />
<br />
==== Fast startup ====<br />
<br />
{{Note|An administrator account is required to change power settings.}}<br />
<br />
For Windows 8 (or later) guests it is better to disable "Turn on fast startup (recommended)" from the Power Options of the Control Panel as explained in the following [https://www.tenforums.com/tutorials/4189-turn-off-fast-startup-windows-10-a.html forum page], as it causes the guest to hang during every other boot.<br />
<br />
Fast Startup may also need to be disabled for changes to the {{ic|-smp}} option to be properly applied.<br />
<br />
==== Remote Desktop Protocol ====<br />
<br />
If you use a MS Windows guest, you might want to use RDP to connect to your guest VM. If you are using a VLAN or are not in the same network as the guest, use:<br />
<br />
$ qemu-system-x86_64 -nographic -net user,hostfwd=tcp::5555-:3389<br />
<br />
Then connect with either {{Pkg|rdesktop}} or {{Pkg|freerdp}} to the guest. For example:<br />
<br />
$ xfreerdp -g 2048x1152 localhost:5555 -z -x lan<br />
<br />
=== Clone Linux system installed on physical equipment ===<br />
<br />
Linux system installed on physical equipment can be cloned for running on QEMU vm. See [https://coffeebirthday.wordpress.com/2018/09/14/clone-linux-system-for-qemu-virtual-machine/ Clone Linux system from hardware for QEMU virtual machine]<br />
<br />
=== Chrooting into arm/arm64 environment from x86_64 ===<br />
<br />
Sometimes it is easier to work directly on a disk image instead of the real ARM based device. This can be achieved by mounting an SD card/storage containing the ''root'' partition and chrooting into it.<br />
<br />
Another use case for an ARM chroot is building ARM packages on an x86_64 machine - {{AUR|armutils-git}} can be used for that. Here, the chroot environment can be created from an image tarball from [https://archlinuxarm.org Arch Linux ARM] - see [https://nerdstuff.org/posts/2020/2020-003_simplest_way_to_create_an_arm_chroot/] for a detailed description of this approach.<br />
<br />
Either way, from the chroot it should be possible to run ''pacman'' and install more packages, compile large libraries etc. Since the executables are for the ARM architecture, the translation to x86 needs to be performed by [[QEMU]].<br />
<br />
Install {{AUR|binfmt-qemu-static}} and {{AUR|qemu-user-static}} from the [[AUR]] on the x86_64 machine/host. ''binfmt-qemu-static'' will take care of registering the qemu binaries to binfmt service.<br />
<br />
[[Restart]] {{ic|systemd-binfmt.service}}<br />
<br />
{{AUR|qemu-user-static}} is needed to allow the execution of compiled programs from other architectures. This is similar to what is provided by {{Pkg|qemu-arch-extra}}, but the "static" variant is required for chroot. Examples:<br />
<br />
qemu-arm-static path_to_sdcard/usr/bin/ls<br />
qemu-aarch64-static path_to_sdcard/usr/bin/ls<br />
<br />
These two lines execute the {{ic|ls}} command compiled for 32-bit ARM and 64-bit ARM respectively. Note that this will not work without chrooting, because it will look for libraries not present in the host system.<br />
<br />
{{AUR|qemu-user-static}} allows automatically prefixing the ARM exectuable with {{ic|qemu-arm-static}} or {{ic|qemu-aarch64-static}}.<br />
<br />
Make sure that the ARM executable support is active:<br />
<br />
{{hc|$ ls /proc/sys/fs/binfmt_misc|<br />
qemu-aarch64 qemu-arm qemu-cris qemu-microblaze qemu-mipsel qemu-ppc64 qemu-riscv64 qemu-sh4 qemu-sparc qemu-sparc64 status<br />
qemu-alpha qemu-armeb qemu-m68k qemu-mips qemu-ppc qemu-ppc64abi32 qemu-s390x qemu-sh4eb qemu-sparc32plus register<br />
}}<br />
<br />
Each executable must be listed.<br />
<br />
If it is not active, reinstall ''binfmt-qemu-static'' and restart ''systemd-binfmt''.<br />
<br />
Mount the SD card to {{ic|/mnt/scdard}} (the device name may be different).<br />
<br />
# mkdir -p /mnt/sdcard<br />
# mount /dev/mmcblk0p2 /mnt/sdcard<br />
<br />
Mount boot partition if needed (again, use the suitable device name):<br />
<br />
# mount /dev/mmcblk0p1 /mnt/sdcard/boot<br />
<br />
Finally ''chroot'' into the SD card root as described in [[Change root#Using chroot]]:<br />
<br />
# chroot /mnt/sdcard /bin/bash<br />
<br />
Alternatively, you can use ''arch-chroot'' from {{Pkg|arch-install-scripts}}, as it will provide an easier way to get network support:<br />
# arch-chroot /mnt/sdcard /bin/bash<br />
<br />
You can also use ''systemd-nspawn'' to chroot into the ARM environment:<br />
# systemd-nspawn -D /mnt/sdcard -M myARMMachine --bind-ro=/etc/resolv.conf<br />
<br />
{{ic|1=--bind-ro=/etc/resolv.conf}} is optional and gives a working network DNS inside the chroot<br />
<br />
== Troubleshooting ==<br />
<br />
=== Mouse cursor is jittery or erratic ===<br />
<br />
If the cursor jumps around the screen uncontrollably, entering this on the terminal before starting QEMU might help:<br />
<br />
$ export SDL_VIDEO_X11_DGAMOUSE=0<br />
<br />
If this helps, you can add this to your {{ic|~/.bashrc}} file.<br />
<br />
=== No visible Cursor ===<br />
<br />
Add {{ic|-show-cursor}} to QEMU's options to see a mouse cursor.<br />
<br />
If that still does not work, make sure you have set your display device appropriately, for example: {{ic|-vga qxl}}.<br />
<br />
Another option to try is {{ic|-usb -device usb-tablet}} as mentioned in [[#Mouse integration]]. This overrides the default PS/2 mouse emulation and synchronizes pointer location between host and guest as an added bonus.<br />
<br />
=== Two different mouse cursors are visible ===<br />
<br />
Apply the tip [[#Mouse integration]].<br />
<br />
=== Keyboard issues when using VNC ===<br />
<br />
When using VNC, you might experience keyboard problems described (in gory details) [https://www.berrange.com/posts/2010/07/04/more-than-you-or-i-ever-wanted-to-know-about-virtual-keyboard-handling/ here]. The solution is ''not'' to use the {{ic|-k}} option on QEMU, and to use {{ic|gvncviewer}} from {{Pkg|gtk-vnc}}. See also [http://www.mail-archive.com/libvir-list@redhat.com/msg13340.html this] message posted on libvirt's mailing list.<br />
<br />
=== Keyboard seems broken or the arrow keys do not work ===<br />
<br />
Should you find that some of your keys do not work or "press" the wrong key (in particular, the arrow keys), you likely need to specify your keyboard layout as an option. The keyboard layouts can be found in {{ic|/usr/share/qemu/keymaps}}.<br />
<br />
$ qemu-system-x86_64 -k ''keymap'' ''disk_image''<br />
<br />
=== Guest display stretches on window resize ===<br />
<br />
To restore default window size, press {{ic|Ctrl+Alt+u}}.<br />
<br />
=== ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy ===<br />
<br />
If an error message like this is printed when starting QEMU with {{ic|-enable-kvm}} option:<br />
<br />
ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy<br />
failed to initialize KVM: Device or resource busy<br />
<br />
that means another [[hypervisor]] is currently running. It is not recommended or possible to run several hypervisors in parallel.<br />
<br />
=== libgfapi error message ===<br />
<br />
The error message displayed at startup:<br />
<br />
Failed to open module: libgfapi.so.0: cannot open shared object file: No such file or directory<br />
<br />
[[Install]] {{pkg|glusterfs}} or ignore the error message as GlusterFS is a optional dependency.<br />
<br />
=== Kernel panic on LIVE-environments===<br />
<br />
If you start a live-environment (or better: booting a system) you may encounter this:<br />
<br />
[ end Kernel panic - not syncing: VFS: Unable to mount root fs on unknown block(0,0)<br />
<br />
or some other boot hindering process (e.g. cannot unpack initramfs, cant start service foo).<br />
Try starting the VM with the {{ic|-m VALUE}} switch and an appropriate amount of RAM, if the ram is to low you will probably encounter similar issues as above/without the memory-switch.<br />
<br />
=== Windows 7 guest suffers low-quality sound ===<br />
<br />
Using the {{ic|hda}} audio driver for Windows 7 guest may result in low-quality sound. Changing the audio driver to {{ic|ac97}} by passing the {{ic|-soundhw ac97}} arguments to QEMU and installing the AC97 driver from [https://www.realtek.com/en/component/zoo/category/pc-audio-codecs-ac-97-audio-codecs-software Realtek AC'97 Audio Codecs] in the guest may solve the problem. See [https://bugzilla.redhat.com/show_bug.cgi?id=1176761#c16 Red Hat Bugzilla – Bug 1176761] for more information.<br />
<br />
=== Could not access KVM kernel module: Permission denied ===<br />
<br />
If you encounter the following error:<br />
<br />
libvirtError: internal error: process exited while connecting to monitor: Could not access KVM kernel module: Permission denied failed to initialize KVM: Permission denied<br />
<br />
Systemd 234 assigns a dynamic ID for the {{ic|kvm}} group (see {{Bug|54943}}). To avoid this error, you need edit the file {{ic|/etc/libvirt/qemu.conf}} and change the line with {{ic|1=group = "78"}} to {{ic|1=group = "kvm"}}.<br />
<br />
=== "System Thread Exception Not Handled" when booting a Windows VM ===<br />
<br />
Windows 8 or Windows 10 guests may raise a generic compatibility exception at boot, namely "System Thread Exception Not Handled", which tends to be caused by legacy drivers acting strangely on real machines. On KVM machines this issue can generally be solved by setting the CPU model to {{ic|core2duo}}.<br />
<br />
=== Certain Windows games/applications crashing/causing a bluescreen ===<br />
<br />
Occasionally, applications running in the VM may crash unexpectedly, whereas they would run normally on a physical machine. If, while running {{ic|dmesg -wH}}, you encounter an error mentioning {{ic|MSR}}, the reason for those crashes is that KVM injects a [[wikipedia:General protection fault|General protection fault]] (GPF) when the guest tries to access unsupported [[wikipedia:Model-specific register|Model-specific registers]] (MSRs) - this often results in guest applications/OS crashing. A number of those issues can be solved by passing the {{ic|1=ignore_msrs=1}} option to the KVM module, which will ignore unimplemented MSRs.<br />
<br />
{{hc|/etc/modprobe.d/kvm.conf|2=<br />
...<br />
options kvm ignore_msrs=1<br />
...<br />
}}<br />
<br />
Cases where adding this option might help:<br />
<br />
* GeForce Experience complaining about an unsupported CPU being present.<br />
* StarCraft 2 and L.A. Noire reliably blue-screening Windows 10 with {{ic|KMODE_EXCEPTION_NOT_HANDLED}}. The blue screen information does not identify a driver file in these cases.<br />
<br />
{{Warning|While this is normally safe and some applications might not work without this, silently ignoring unknown MSR accesses could potentially break other software within the VM or other VMs.}}<br />
<br />
=== Applications in the VM experience long delays or take a long time to start ===<br />
<br />
This may be caused by insufficient available entropy in the VM. Consider allowing the guest to access the hosts's entropy pool by adding a [https://wiki.qemu.org/Features/VirtIORNG VirtIO RNG device] to the VM, or by installing an entropy generating daemon such as [[Haveged]].<br />
<br />
Anecdotally, OpenSSH takes a while to start accepting connections under insufficient entropy, without the logs revealing why.<br />
<br />
=== High interrupt latency and microstuttering ===<br />
<br />
This problem manifests itself as small pauses (stutters) and is particularly noticeable in graphics-intensive applications, such as games.<br />
<br />
* One of the causes is CPU power saving features, which are controlled by [[CPU frequency scaling]]. Change this to {{ic|performance}} for all processor cores. <br />
* Another possible cause is PS/2 inputs. Switch from PS/2 to Virtio inputs, see [[PCI passthrough via OVMF#Passing keyboard/mouse via Evdev]].<br />
<br />
=== QXL video causes low resolution ===<br />
<br />
QEMU 4.1.0 introduced a regression where QXL video can fall back to low resolutions, when being displayed through spice. [https://bugs.launchpad.net/qemu/+bug/1843151] For example, when KMS starts, text resolution may become as low as 4x10 characters. When trying to increase GUI resolution, it may go to the lowest supported resolution.<br />
<br />
As a workaround, create your device in this form:<br />
<br />
-device qxl-vga,max_outputs=1...<br />
<br />
=== Hang during VM initramfs ===<br />
<br />
Linux 5.2.11 introduced a KVM regression where under some circumstances a VM may permanently hang during the early boot phase, when the initramfs is being loaded or ran. [https://www.spinics.net/lists/kvm/msg195171.html] Linux 5.3 fixed the regression. The host shows qemu using 100% CPU * number of virtual CPUs. Reported case is with a host using hyperthreading, and a VM being given more than host's {{ic|nproc}}/2 virtual CPUs. It is unknown what exact circumstances trigger one of the threads to delete a memory region to cause this. The workarounds are:<br />
<br />
* Upgrade to Linux 5.3.<br />
* Downgrade to Linux 5.2.10<br />
* Until fixed, try giving the VM no more than the host's {{ic|nproc}}/2 virtual CPUs<br />
* Custom compile linux, reverting commit 2ad350fb4c (note this re-introduces a regression triggered when removing a memslot)<br />
<br />
=== VM does not boot when using a Secure Boot enabled OVMF ===<br />
<br />
{{ic|/usr/share/edk2-ovmf/x64/OVMF_CODE.secboot.fd}} from {{Pkg|edk2-ovmf}} is built with [[Wikipedia:System Management Mode|SMM]] support. If S3 support is not disabled in the VM, then the VM might not boot at all.<br />
<br />
Add the {{ic|1=-global ICH9-LPC.disable_s3=1}} option to the ''qemu'' command.<br />
<br />
See {{Bug|59465}} and https://github.com/tianocore/edk2/blob/master/OvmfPkg/README for more details and the required options to use Secure Boot in QEMU.<br />
<br />
=== Guest CPU interrupts are not firing ===<br />
<br />
If you are writing your own operating system by following the [https://wiki.osdev.org/ OSDev wiki], or are simply getting stepping through the guest architecture assembly code using QEMU's {{ic|gdb}} interface using the {{ic|-s}} flag, it's useful to know that many emulators, QEMU included, usually implement some CPU interrupts leaving many hardware interrupts unimplemented. One way to know if your code if firing an interrupt, is by using:<br />
<br />
-d int<br />
<br />
to enable showing interrupts/exceptions on stdout.<br />
<br />
To see what other guest debugging features QEMU has to offer, see:<br />
<br />
qemu-system-x86_64 -d help<br />
<br />
or replace {{ic|x86_64}} for your chosen guest architecture.<br />
<br />
== See also ==<br />
<br />
* [http://qemu.org Official QEMU website]<br />
* [http://www.linux-kvm.org Official KVM website]<br />
* [http://qemu.weilnetz.de/qemu-doc.html QEMU Emulator User Documentation]<br />
* [[Wikibooks:QEMU|QEMU Wikibook]]<br />
* [http://alien.slackbook.org/dokuwiki/doku.php?id=slackware:qemu Hardware virtualization with QEMU] by AlienBOB (last updated in 2008)<br />
* [http://blog.falconindy.com/articles/build-a-virtual-army.html Building a Virtual Army] by Falconindy<br />
* [http://git.qemu.org/?p=qemu.git;a=tree;f=docs Lastest docs]<br />
* [http://qemu.weilnetz.de/ QEMU on Windows]<br />
* [[wikipedia:Qemu|Wikipedia]]<br />
* [[debian:QEMU|Debian Wiki - QEMU]]<br />
* [https://people.gnome.org/~markmc/qemu-networking.html QEMU Networking on gnome.org]<br />
* [http://bsdwiki.reedmedia.net/wiki/networking_qemu_virtual_bsd_systems.html Networking QEMU Virtual BSD Systems]<br />
* [https://www.gnu.org/software/hurd/hurd/running/qemu.html QEMU on gnu.org]<br />
* [https://wiki.freebsd.org/qemu QEMU on FreeBSD as host]<br />
* [https://wiki.mikejung.biz/KVM_/_Xen KVM/QEMU Virtio Tuning and SSD VM Optimization Guide]<br />
* [https://doc.opensuse.org/documentation/leap/virtualization/html/book-virt/part-virt-qemu.html Managing Virtual Machines with QEMU - openSUSE documentation]<br />
* [https://www.ibm.com/support/knowledgecenter/en/linuxonibm/liaat/liaatkvm.htm KVM on IBM Knowledge Center]</div>Malcontenthttps://wiki.archlinux.org/index.php?title=QEMU&diff=634813QEMU2020-09-09T15:53:49Z<p>Malcontent: -soundhw still calls it hda</p>
<hr />
<div>[[Category:Emulation]]<br />
[[Category:Hypervisors]]<br />
[[de:Qemu]]<br />
[[es:QEMU]]<br />
[[fr:Qemu]]<br />
[[ja:QEMU]]<br />
[[zh-hans:QEMU]]<br />
[[zh-hant:QEMU]]<br />
{{Related articles start}}<br />
{{Related|:Category:Hypervisors}}<br />
{{Related|Libvirt}}<br />
{{Related|QEMU/Guest graphics acceleration}}<br />
{{Related|PCI passthrough via OVMF}}<br />
{{Related articles end}}<br />
<br />
According to the [http://wiki.qemu.org/Main_Page QEMU about page], "QEMU is a generic and open source machine emulator and virtualizer."<br />
<br />
When used as a machine emulator, QEMU can run OSes and programs made for one machine (e.g. an ARM board) on a different machine (e.g. your x86 PC). By using dynamic translation, it achieves very good performance.<br />
<br />
QEMU can use other hypervisors like [[Xen]] or [[KVM]] to use CPU extensions ([[Wikipedia:Hardware-assisted virtualization|HVM]]) for virtualization. When used as a virtualizer, QEMU achieves near native performances by executing the guest code directly on the host CPU.<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|qemu}} package (or {{Pkg|qemu-headless}} for the version without GUI) and below optional packages for your needs:<br />
<br />
* {{Pkg|qemu-arch-extra}} - extra architectures support<br />
* {{Pkg|qemu-block-gluster}} - [[Glusterfs]] block support<br />
* {{Pkg|qemu-block-iscsi}} - [[iSCSI]] block support<br />
* {{Pkg|qemu-block-rbd}} - RBD block support <br />
* {{Pkg|samba}} - [[Samba|SMB/CIFS]] server support<br />
<br />
Alternatively, {{AUR|qemu-user-static}} exists as a usermode and static variant.<br />
<br />
=== QEMU variants ===<br />
<br />
QEMU is offered in several variants suited for different use cases.<br />
<br />
As a first classification, QEMU is offered in full-system and usermode emulation modes:<br />
<br />
; Full-system emulation<br />
: In this mode, QEMU emulates a full system, including one or several processors and various peripherals. It is more accurate but slower, and does not require the emulated OS to be Linux.<br />
: QEMU commands for full-system emulation are named {{ic|qemu-system-''target_architecture''}}, e.g. {{ic|qemu-system-x86_64}} for emulating intel 64-bit CPUs, {{ic|qemu-system-i386}} for intel 32 bits CPUs, {{ic|qemu-system-arm}} for ARM (32 bits), {{ic|qemu-system-aarch64}} for ARM64, etc.<br />
: If the target architecture matches the host CPU, this mode may still benefit from a significant speedup by using a hypervisor like [[#Enabling KVM|KVM]] or Xen.<br />
; [https://www.qemu.org/docs/master/user/main.html Usermode emulation]: In this mode, QEMU is able to invoke a Linux executable compiled for a (potentially) different architecture by leveraging the host system resources. There may be compatibility issues, e.g. some features may not be implemented, dynamically linked executables will not work out of the box (see [[#Chrooting into arm/arm64 environment from x86_64|the section below]] to address this) and only Linux is supported (although [https://wiki.winehq.org/Emulation Wine may be used] for running Windows executables).<br />
: QEMU commands for usermode emulation are named {{ic|qemu-''target_architecture''}}, e.g. {{ic|qemu-x86_64}} for emulating intel 64-bit CPUs.<br />
<br />
QEMU is offered in dynamically-linked and statically-linked variants:<br />
<br />
; Dynamically-linked (default): {{ic|qemu-*}} commands depend on the host OS libraries, so executables are smaller.<br />
; Statically-linked: {{ic|qemu-*}} commands can be copied to any Linux system with the same architecture.<br />
<br />
In the case of Arch Linux, full-system emulation is offered as:<br />
<br />
; Non-headless (default): This variant enables GUI features that require additional dependencies (like SDL or GTK).<br />
; Headless: This is a slimmer variant that does not require GUI (this is suitable e.g. for servers).<br />
<br />
Note that headless and non-headless versions install commands with the same name (e.g. {{ic|qemu-system-x86_64}}) and thus cannot be both installed at the same time.<br />
<br />
=== Details on packages offered in Arch Linux ===<br />
<br />
* The {{Pkg|qemu}} package provides the {{ic|x86_64}} architecture emulators for full-system emulation ({{ic|qemu-system-x86_64}}). The {{Pkg|qemu-arch-extra}} package provides the {{ic|x86_64}} usermode variant ({{ic|qemu-x86_64}}) and also for the rest of supported architectures it includes both full-system and usermode variants (e.g. {{ic|qemu-system-arm}} and {{ic|qemu-arm}}).<br />
* The headless versions of these packages (only applicable to full-system emulation) are {{Pkg|qemu-headless}} ({{ic|x86_64}}-only) and {{Pkg|qemu-headless-arch-extra}} (rest of architectures).<br />
* Full-system emulation can be expanded with some QEMU modules present in separate packages: {{Pkg|qemu-block-gluster}}, {{Pkg|qemu-block-iscsi}}, {{Pkg|qemu-block-rbd}} and {{Pkg|qemu-guest-agent}}.<br />
* The unofficial AUR package {{AUR|qemu-user-static}} provides a usermode and static variant for all target architectures supported by QEMU. A precompiled version of this package exists: {{AUR|qemu-user-static-bin}}. The installed QEMU commands are named {{ic|qemu-''target_architecture''-static}}, for example, {{ic|qemu-x86_64-static}} for intel 64-bit CPUs.<br />
<br />
{{Note|At present, Arch does not offer a full-system mode and statically linked variant (neither officially nor via AUR), as this is usually not needed.}}<br />
<br />
== Graphical front-ends for QEMU ==<br />
<br />
Unlike other virtualization programs such as [[VirtualBox]] and [[VMware]], QEMU does not provide a GUI to manage virtual machines (other than the window that appears when running a virtual machine), nor does it provide a way to create persistent virtual machines with saved settings. All parameters to run a virtual machine must be specified on the command line at every launch, unless you have created a custom script to start your virtual machine(s).<br />
<br />
[[Libvirt]] provides a convenient way to manage QEMU virtual machines. See [[Libvirt#Client|list of libvirt clients]] for available front-ends.<br />
<br />
Other GUI front-ends for QEMU:<br />
<br />
* {{App|AQEMU|QEMU GUI written in Qt5.|https://github.com/tobimensch/aqemu|{{AUR|aqemu}}}}<br />
<br />
== Creating new virtualized system ==<br />
<br />
=== Creating a hard disk image ===<br />
<br />
{{Accuracy|If I get the man page right the raw format only allocates the full size if the filesystem does not support "holes" or it is <br />
explicitly told to preallocate. See man qemu-img in section Notes.}} <br />
<br />
{{Tip|See [[Wikibooks:QEMU/Images]] for more information on QEMU images.}}<br />
<br />
To run QEMU you will need a hard disk image, unless you are booting a live system from CD-ROM or the network (and not doing so to install an operating system to a hard disk image). A hard disk image is a file which stores the contents of the emulated hard disk.<br />
<br />
A hard disk image can be ''raw'', so that it is literally byte-by-byte the same as what the guest sees, and will always use the full capacity of the guest hard drive on the host. This method provides the least I/O overhead, but can waste a lot of space, as not-used space on the guest cannot be used on the host.<br />
<br />
Alternatively, the hard disk image can be in a format such as ''qcow2'' which only allocates space to the image file when the guest operating system actually writes to those sectors on its virtual hard disk. The image appears as the full size to the guest operating system, even though it may take up only a very small amount of space on the host system. This image format also supports QEMU snapshotting functionality (see [[#Creating and managing snapshots via the monitor console]] for details). However, using this format instead of ''raw'' will likely affect performance.<br />
<br />
QEMU provides the {{ic|qemu-img}} command to create hard disk images. For example to create a 4 GB image in the ''raw'' format:<br />
<br />
$ qemu-img create -f raw ''image_file'' 4G<br />
<br />
You may use {{ic|-f qcow2}} to create a ''qcow2'' disk instead.<br />
<br />
{{Note|You can also simply create a ''raw'' image by creating a file of the needed size using {{ic|dd}} or {{ic|fallocate}}.}}<br />
<br />
{{Warning|If you store the hard disk images on a [[Btrfs]] file system, you should consider disabling [[Btrfs#Copy-on-Write (CoW)|Copy-on-Write]] for the directory before creating any images.}}<br />
<br />
==== Overlay storage images ====<br />
<br />
You can create a storage image once (the 'backing' image) and have QEMU keep mutations to this image in an overlay image. This allows you to revert to a previous state of this storage image. You could revert by creating a new overlay image at the time you wish to revert, based on the original backing image.<br />
<br />
To create an overlay image, issue a command like:<br />
<br />
$ qemu-img create -o backing_file=''img1.raw'',backing_fmt=''raw'' -f ''qcow2'' ''img1.cow''<br />
<br />
After that you can run your QEMU VM as usual (see [[#Running virtualized system]]):<br />
<br />
$ qemu-system-x86_64 ''img1.cow''<br />
<br />
The backing image will then be left intact and mutations to this storage will be recorded in the overlay image file.<br />
<br />
When the path to the backing image changes, repair is required.<br />
<br />
{{Warning|The backing image's absolute filesystem path is stored in the (binary) overlay image file. Changing the backing image's path requires some effort.}}<br />
<br />
Make sure that the original backing image's path still leads to this image. If necessary, make a symbolic link at the original path to the new path. Then issue a command like:<br />
<br />
$ qemu-img rebase -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
At your discretion, you may alternatively perform an 'unsafe' rebase where the old path to the backing image is not checked:<br />
<br />
$ qemu-img rebase -u -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
==== Resizing an image ====<br />
<br />
{{Warning|Resizing an image containing an NTFS boot file system could make the operating system installed on it unbootable. It is recommended to create a backup first.}}<br />
<br />
The {{ic|qemu-img}} executable has the {{ic|resize}} option, which enables easy resizing of a hard drive image. It works for both ''raw'' and ''qcow2''. For example, to increase image space by 10 GB, run:<br />
<br />
$ qemu-img resize ''disk_image'' +10G<br />
<br />
After enlarging the disk image, you must use file system and partitioning tools inside the virtual machine to actually begin using the new space. When shrinking a disk image, you must '''first reduce the allocated file systems and partition sizes''' using the file system and partitioning tools inside the virtual machine and then shrink the disk image accordingly, otherwise shrinking the disk image will result in data loss! For a Windows guest, open the "create and format hard disk partitions" control panel.<br />
<br />
==== Converting an image ====<br />
<br />
You can convert an image to other formats using {{ic|qemu-img convert}}. This example shows how to convert a ''raw'' image to ''qcow2'':<br />
<br />
$ qemu-img convert -f raw -O qcow2 ''input''.img ''output''.qcow2<br />
<br />
This will not remove the original input file.<br />
<br />
=== Preparing the installation media ===<br />
<br />
To install an operating system into your disk image, you need the installation medium (e.g. optical disk, USB-drive, or ISO image) for the operating system. The installation medium should not be mounted because QEMU accesses the media directly.<br />
<br />
{{Tip|If using an optical disk, it is a good idea to first dump the media to a file because this both improves performance and does not require you to have direct access to the devices (that is, you can run QEMU as a regular user without having to change access permissions on the media's device file). For example, if the CD-ROM device node is named {{ic|/dev/cdrom}}, you can dump it to a file with the command: {{bc|1=$ dd if=/dev/cdrom of=''cd_image.iso'' bs=4k}}}}<br />
<br />
=== Installing the operating system ===<br />
<br />
This is the first time you will need to start the emulator. To install the operating system on the disk image, you must attach both the disk image and the installation media to the virtual machine, and have it boot from the installation media.<br />
<br />
For example on i386 guests, to install from a bootable ISO file as CD-ROM and a raw disk image:<br />
<br />
$ qemu-system-x86_64 -cdrom ''iso_image'' -boot order=d -drive file=''disk_image'',format=raw<br />
<br />
See {{man|1|qemu}} for more information about loading other media types (such as floppy, disk images or physical drives) and [[#Running virtualized system]] for other useful options.<br />
<br />
After the operating system has finished installing, the QEMU image can be booted directly (see [[#Running virtualized system]]).<br />
<br />
{{Note|By default only 128 MB of memory is assigned to the machine. The amount of memory can be adjusted with the {{ic|-m}} switch, for example {{ic|-m 512M}} or {{ic|-m 2G}}.}}<br />
<br />
{{Tip|<br />
* Instead of specifying {{ic|1=-boot order=x}}, some users may feel more comfortable using a boot menu: {{ic|1=-boot menu=on}}, at least during configuration and experimentation.<br />
* When running QEMU in headless mode, it starts a local VNC server on port 5900 per default. You can use [[TigerVNC]] to connect to the guest OS: {{ic|vncviewer :5900}}<br />
* If you need to replace floppies or CDs as part of the installation process, you can use the QEMU machine monitor (press {{ic|Ctrl+Alt+2}} in the virtual machine's window) to remove and attach storage devices to a virtual machine. Type {{ic|info block}} to see the block devices, and use the {{ic|change}} command to swap out a device. Press {{ic|Ctrl+Alt+1}} to go back to the virtual machine.<br />
}}<br />
<br />
== Running virtualized system ==<br />
<br />
{{ic|qemu-system-*}} binaries (for example {{ic|qemu-system-i386}} or {{ic|qemu-system-x86_64}}, depending on guest's architecture) are used to run the virtualized guest. The usage is:<br />
<br />
$ qemu-system-x86_64 ''options'' ''disk_image''<br />
<br />
Options are the same for all {{ic|qemu-system-*}} binaries, see {{man|1|qemu}} for documentation of all options.<br />
<br />
By default, QEMU will show the virtual machine's video output in a window. One thing to keep in mind: when you click inside the QEMU window, the mouse pointer is grabbed. To release it, press {{ic|Ctrl+Alt+g}}.<br />
<br />
{{Warning|QEMU should never be run as root. If you must launch it in a script as root, you should use the {{ic|-runas}} option to make QEMU drop root privileges.}}<br />
<br />
=== Enabling KVM ===<br />
<br />
KVM (''Kernel-based Virtual Machine'') full virtualization must be supported by your Linux kernel and your hardware, and necessary [[kernel modules]] must be loaded. See [[KVM]] for more information.<br />
<br />
To start QEMU in KVM mode, append {{ic|-enable-kvm}} to the additional start options. To check if KVM is enabled for a running VM, enter the [[#QEMU monitor]] and type {{ic|info kvm}}.<br />
<br />
{{Note|<br />
* The argument {{ic|1=accel=kvm}} of the {{ic|-machine}} option is equivalent to the {{ic|-enable-kvm}} or the {{ic|-accel kvm}} option.<br />
* CPU model {{ic|host}} requires KVM<br />
* If you start your VM with a GUI tool and experience very bad performance, you should check for proper KVM support, as QEMU may be falling back to software emulation.<br />
* KVM needs to be enabled in order to start Windows 7 and Windows 8 properly without a ''blue screen''.<br />
}}<br />
<br />
=== Enabling IOMMU (Intel VT-d/AMD-Vi) support ===<br />
<br />
First enable IOMMU, see [[PCI passthrough via OVMF#Setting up IOMMU]].<br />
<br />
Add {{ic|-device intel-iommu}} to create the IOMMU device:<br />
<br />
$ qemu-system-x86_64 '''-enable-kvm -machine q35 -device intel-iommu''' -cpu host ..<br />
<br />
{{Note|<br />
On Intel CPU based systems creating an IOMMU device in a QEMU guest with {{ic|-device intel-iommu}} will disable PCI passthrough with an error like: {{bc|Device at bus pcie.0 addr 09.0 requires iommu notifier which is currently not supported by intel-iommu emulation}} While adding the kernel parameter {{ic|1=intel_iommu=on}} is still needed for remapping IO (e.g. [[PCI passthrough via OVMF#Isolating the GPU|PCI passthrough with vfio-pci]]), {{ic|-device intel-iommu}} should not be set if PCI PCI passthrough is required.<br />
}}<br />
<br />
== Sharing data between host and guest ==<br />
<br />
=== Network ===<br />
<br />
Data can be shared between the host and guest OS using any network protocol that can transfer files, such as [[NFS]], [[SMB]], [[Wikipedia:Network block device|NBD]], HTTP, [[Very Secure FTP Daemon|FTP]], or [[SSH]], provided that you have set up the network appropriately and enabled the appropriate services.<br />
<br />
The default user-mode networking allows the guest to access the host OS at the IP address 10.0.2.2. Any servers that you are running on your host OS, such as a SSH server or SMB server, will be accessible at this IP address. So on the guests, you can mount directories exported on the host via [[SMB]] or [[NFS]], or you can access the host's HTTP server, etc.<br />
It will not be possible for the host OS to access servers running on the guest OS, but this can be done with other network configurations (see [[#Tap networking with QEMU]]).<br />
<br />
=== QEMU's port forwarding ===<br />
<br />
QEMU can forward ports from the host to the guest to enable e.g. connecting from the host to an SSH server running on the guest.<br />
<br />
For example, to bind port 10022 on the host with port 22 (SSH) on the guest, start QEMU with a command like:<br />
<br />
$ qemu-system-x86_64 ''disk_image'' -nic user,hostfwd=tcp::10022-:22<br />
<br />
Make sure the sshd is running on the guest and connect with:<br />
<br />
$ ssh ''guest-user''@localhost -p 10022<br />
<br />
You can use [[SSHFS]] to mount the guest's file system at the host for shared read and write access.<br />
<br />
=== QEMU's built-in SMB server ===<br />
<br />
QEMU's documentation says it has a "built-in" SMB server, but actually it just starts up [[Samba]] on the host with an automatically generated {{ic|smb.conf}} file located in {{ic|/tmp/qemu-smb.''random_string''}} and makes it accessible to the guest at a different IP address (10.0.2.4 by default). This only works for user networking, and is useful when you do not want to start the normal [[Samba]] service on the host, which the guest can also access if you have set up shares on it.<br />
<br />
Only a single directory can be set as shared with the option {{ic|1=smb=}}, but adding more directories (even while the virtual machine is running) could be as easy as creating symbolic links in the shared directory if QEMU configured SMB to follow symbolic links. It does not do so, but the configuration of the running SMB server can be changed as described below.<br />
<br />
''Samba'' must be installed on the host. To enable this feature, start QEMU with a command like:<br />
<br />
$ qemu-system-x86_64 ''disk_image'' -net nic -net user,smb=''shared_dir_path''<br />
<br />
where {{ic|''shared_dir_path''}} is a directory that you want to share between the guest and host.<br />
<br />
Then, in the guest, you will be able to access the shared directory on the host 10.0.2.4 with the share name "qemu". For example, in Windows Explorer you would go to {{ic|\\10.0.2.4\qemu}}.<br />
<br />
{{Note|<br />
* If you are using sharing options multiple times like {{ic|1=-net user,smb=''shared_dir_path1'' -net user,smb=''shared_dir_path2''}} or {{ic|1=-net user,smb=''shared_dir_path1'',smb=''shared_dir_path2''}} then it will share only the last defined one.<br />
* If you cannot access the shared folder and the guest system is Windows, check that the [http://ecross.mvps.org/howto/enable-netbios-over-tcp-ip-with-windows.htm NetBIOS protocol is enabled] and that a firewall does not block [https://technet.microsoft.com/en-us/library/cc940063.aspx ports] used by the NetBIOS protocol.<br />
* If you cannot access the shared folder and the guest system is Windows 10 Enterprise or Education or Windows Server 2016, [https://support.microsoft.com/en-us/help/4046019 enable guest access].<br />
}}<br />
<br />
One way to share multiple directories and to add or remove them while the virtual machine is running, is to share an empty directory and create/remove symbolic links to the directories in the shared directory. For this to work, the configuration of the running SMB server can be changed with the following script, which also allows the execution of files on the guest that are not set executable on the host:<br />
<br />
#!/bin/bash<br />
eval $(ps h -C smbd -o pid,args | grep /tmp/qemu-smb | gawk '{print "pid="$1";conf="$6}')<br />
echo "[global]<br />
allow insecure wide links = yes<br />
[qemu]<br />
follow symlinks = yes<br />
wide links = yes<br />
acl allow execute always = yes" >> $conf<br />
# in case the change is not detected automatically:<br />
smbcontrol --configfile=$conf $pid reload-config<br />
<br />
This can be applied to the running server started by qemu only after the guest has connected to the network drive the first time. An alternative to this method is to add additional shares to the configuration file like so:<br />
<br />
echo "[''myshare'']<br />
path=''another_path''<br />
read only=no<br />
guest ok=yes<br />
force user=''username''" >> $conf<br />
<br />
This share will be available on the guest as {{ic|\\10.0.2.4\''myshare''}}.<br />
<br />
=== Using filesystem passthrough and VirtFS ===<br />
<br />
See the [https://wiki.qemu.org/Documentation/9psetup QEMU documentation].<br />
<br />
=== Mounting a partition of the guest on the host ===<br />
<br />
It can be useful to mount a drive image under the host system, it can be a way to transfer files in and out of the guest. This should be done when the virtual machine is not running.<br />
<br />
The procedure to mount the drive on the host depends on the type of qemu image, ''raw'' or ''qcow2''. We detail thereafter the steps to mount a drive in the two formats in [[#Mounting a partition from a raw image]] and [[#Mounting a partition from a qcow2 image]]. For the full documentation see [[Wikibooks:QEMU/Images#Mounting an image on the host]].<br />
<br />
{{Warning|You must make sure to unmount the partitions before running the virtual machine again. Otherwise, data corruption is very likely to occur.}}<br />
<br />
==== Mounting a partition from a raw image ====<br />
<br />
It is possible to mount partitions that are inside a raw disk image file by setting them up as loopback devices.<br />
<br />
===== With manually specifying byte offset =====<br />
<br />
One way to mount a disk image partition is to mount the disk image at a certain offset using a command like the following:<br />
<br />
# mount -o loop,offset=32256 ''disk_image'' ''mountpoint''<br />
<br />
The {{ic|1=offset=32256}} option is actually passed to the {{ic|losetup}} program to set up a loopback device that starts at byte offset 32256 of the file and continues to the end. This loopback device is then mounted. You may also use the {{ic|sizelimit}} option to specify the exact size of the partition, but this is usually unnecessary.<br />
<br />
Depending on your disk image, the needed partition may not start at offset 32256. Run {{ic|fdisk -l ''disk_image''}} to see the partitions in the image. fdisk gives the start and end offsets in 512-byte sectors, so multiply by 512 to get the correct offset to pass to {{ic|mount}}.<br />
<br />
===== With loop module autodetecting partitions =====<br />
<br />
The Linux loop driver actually supports partitions in loopback devices, but it is disabled by default. To enable it, do the following:<br />
<br />
* Get rid of all your loopback devices (unmount all mounted images, etc.).<br />
* [[Kernel_modules#Manual_module_handling|Unload]] the {{ic|loop}} kernel module, and load it with the {{ic|1=max_part=15}} parameter set. Additionally, the maximum number of loop devices can be controlled with the {{ic|max_loop}} parameter.<br />
<br />
{{Tip|You can put an entry in {{ic|/etc/modprobe.d}} to load the loop module with {{ic|1=max_part=15}} every time, or you can put {{ic|1=loop.max_part=15}} on the kernel command-line, depending on whether you have the {{ic|loop.ko}} module built into your kernel or not.}}<br />
<br />
Set up your image as a loopback device:<br />
<br />
# losetup -f -P ''disk_image''<br />
<br />
Then, if the device created was {{ic|/dev/loop0}}, additional devices {{ic|/dev/loop0pX}} will have been automatically created, where X is the number of the partition. These partition loopback devices can be mounted directly. For example:<br />
<br />
# mount /dev/loop0p1 ''mountpoint''<br />
<br />
To mount the disk image with ''udisksctl'', see [[Udisks#Mount loop devices]].<br />
<br />
===== With kpartx =====<br />
<br />
'''kpartx''' from the {{Pkg|multipath-tools}} package can read a partition table on a device and create a new device for each partition. For example:<br />
<br />
# kpartx -a ''disk_image''<br />
<br />
This will setup the loopback device and create the necessary partition(s) device(s) in {{ic|/dev/mapper/}}.<br />
<br />
==== Mounting a partition from a qcow2 image ====<br />
<br />
We will use {{ic|qemu-nbd}}, which lets use the NBD (''network block device'') protocol to share the disk image.<br />
<br />
First, we need the ''nbd'' module loaded:<br />
<br />
# modprobe nbd max_part=16<br />
<br />
Then, we can share the disk and create the device entries:<br />
<br />
# qemu-nbd -c /dev/nbd0 ''/path/to/image.qcow2''<br />
<br />
Discover the partitions:<br />
<br />
# partprobe /dev/nbd0<br />
<br />
''fdisk'' can be used to get information regarding the different partitions in {{{ic|''nbd0''}}:<br />
<br />
{{hc|# fdisk -l /dev/nbd0|2=<br />
Disk /dev/nbd0: 25.2 GiB, 27074281472 bytes, 52879456 sectors<br />
Units: sectors of 1 * 512 = 512 bytes<br />
Sector size (logical/physical): 512 bytes / 512 bytes<br />
I/O size (minimum/optimal): 512 bytes / 512 bytes<br />
Disklabel type: dos<br />
Disk identifier: 0xa6a4d542<br />
<br />
Device Boot Start End Sectors Size Id Type<br />
/dev/nbd0p1 * 2048 1026047 1024000 500M 7 HPFS/NTFS/exFAT<br />
/dev/nbd0p2 1026048 52877311 51851264 24.7G 7 HPFS/NTFS/exFAT}}<br />
<br />
Then mount any partition of the drive image, for example the partition 2:<br />
<br />
# mount /dev/nbd0'''p2''' ''mountpoint''<br />
<br />
After the usage, it is important to unmount the image and reverse previous steps, i.e. unmount the partition and disconnect the nbd device:<br />
<br />
# umount ''mountpoint''<br />
# qemu-nbd -d /dev/nbd0<br />
<br />
=== Using any real partition as the single primary partition of a hard disk image ===<br />
<br />
Sometimes, you may wish to use one of your system partitions from within QEMU. Using a raw partition for a virtual machine will improve performance, as the read and write operations do not go through the file system layer on the physical host. Such a partition also provides a way to share data between the host and guest.<br />
<br />
In Arch Linux, device files for raw partitions are, by default, owned by ''root'' and the ''disk'' group. If you would like to have a non-root user be able to read and write to a raw partition, you must either change the owner of the partition's device file to that user, add that user to the ''disk'' group, or use [[ACL]] for more fine-grained access control.<br />
<br />
{{Warning|<br />
* Although it is possible, it is not recommended to allow virtual machines to alter critical data on the host system, such as the root partition.<br />
* You must not mount a file system on a partition read-write on both the host and the guest at the same time. Otherwise, data corruption will result.<br />
}}<br />
<br />
After doing so, you can attach the partition to a QEMU virtual machine as a virtual disk.<br />
<br />
However, things are a little more complicated if you want to have the ''entire'' virtual machine contained in a partition. In that case, there would be no disk image file to actually boot the virtual machine since you cannot install a bootloader to a partition that is itself formatted as a file system and not as a partitioned device with an MBR. Such a virtual machine can be booted either by specifying the [[kernel]] and [[initrd]] manually, or by simulating a disk with an MBR by using the [https://www.kernel.org/doc/html/latest/admin-guide/device-mapper/index.html Device-mapper], linear [[RAID]], or a [https://www.kernel.org/doc/html/latest/admin-guide/blockdev/nbd.html Linux Network Block Device].<br />
<br />
==== By specifying kernel and initrd manually ====<br />
<br />
QEMU supports loading [[Kernels|Linux kernels]] and [[initramfs|init ramdisks]] directly, thereby circumventing bootloaders such as [[GRUB]]. It then can be launched with the physical partition containing the root file system as the virtual disk, which will not appear to be partitioned. This is done by issuing a command similar to the following:<br />
<br />
{{Note|In this example, it is the '''host's''' images that are being used, not the guest's. If you wish to use the guest's images, either mount {{ic|/dev/sda3}} read-only (to protect the file system from the host) and specify the {{ic|/full/path/to/images}} or use some kexec hackery in the guest to reload the guest's kernel (extends boot time). }}<br />
<br />
$ qemu-system-x86_64 -kernel /boot/vmlinuz-linux -initrd /boot/initramfs-linux.img -append root=/dev/sda /dev/sda3<br />
<br />
In the above example, the physical partition being used for the guest's root file system is {{ic|/dev/sda3}} on the host, but it shows up as {{ic|/dev/sda}} on the guest.<br />
<br />
You may, of course, specify any kernel and initrd that you want, and not just the ones that come with Arch Linux.<br />
<br />
When there are multiple [[kernel parameters]] to be passed to the {{ic|-append}} option, they need to be quoted using single or double quotes. For example:<br />
<br />
... -append 'root=/dev/sda1 console=ttyS0'<br />
<br />
==== Simulate a virtual disk with MBR ====<br />
<br />
A more complicated way to have a virtual machine use a physical partition, while keeping that partition formatted as a file system and not just having the guest partition the partition as if it were a disk, is to simulate an MBR for it so that it can boot using a bootloader such as GRUB.<br />
<br />
For the following, suppose you have a plain, unmounted {{ic|/dev/hda''N''}} partition with some file system on it you wish to make part of a QEMU disk image. The trick is to dynamically prepend a master boot record (MBR) to the real partition you wish to embed in a QEMU raw disk image. More generally, the partition can be any part of a larger simulated disk, in particular a block device that simulates the original physical disk but only exposes {{ic|/dev/hda''N''}} to the virtual machine.<br />
<br />
A virtual disk of this type can be represented by a VMDK file that contains references to (a copy of) the MBR and the partition, but QEMU does not support this VMDK format. For instance, a virtual disk [https://www.virtualbox.org/manual/ch09.html#rawdisk created by]<br />
<br />
$ VBoxManage internalcommands createrawvmdk -filename ''/path/to/file.vmdk'' -rawdisk /dev/hda<br />
<br />
will be rejected by QEMU with the error message<br />
<br />
Unsupported image type 'partitionedDevice'<br />
<br />
Note that {{ic|VBoxManage}} creates two files, {{ic|''file.vmdk''}} and {{ic|''file-pt.vmdk''}}, the latter being a copy of the MBR, to which the text file {{ic|file.vmdk}} points. Read operations outside the target partition or the MBR would give zeros, while written data would be discarded.<br />
<br />
===== Device Mapper =====<br />
<br />
A method that is similar to the use of a VMDK descriptor file uses the device mapper to prepend a loop device attached to the MBR file to the target partition. In case we do not need our virtual disk to have the same size as the original, we first create a file to hold the MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=2048<br />
<br />
Here, a 1 MB (2048 * 512 bytes) file is created in accordance with partition alignment policies used by modern disk partitioning tools. For compatibility with older partitioning software, 63 sectors instead of 2048 might be required. The MBR only needs a single 512 bytes block, the additional free space can be used for a BIOS boot partition and, in the case of a hybrid partitioning scheme, for a GUID Partition Table. Then, we attach a loop device to the MBR file:<br />
<br />
# losetup --show -f ''/path/to/mbr''<br />
/dev/loop0<br />
<br />
In this example, the resulting device is {{ic|/dev/loop0}}. The device mapper is now used to join the MBR and the partition:<br />
<br />
# echo "0 2048 linear /dev/loop0 0<br />
2048 `blockdev --getsz /dev/hda''N''` linear /dev/hda''N'' 0" | dmsetup create qemu<br />
<br />
The resulting {{ic|/dev/mapper/qemu}} is what we will use as a QEMU raw disk image. Additional steps are required to create a partition table (see the section that describes the use of a linear RAID for an example) and boot loader code on the virtual disk (which will be stored in {{ic|''/path/to/mbr''}}).<br />
<br />
The following setup is an example where the position of {{ic|/dev/hda''N''}} on the virtual disk is to be the same as on the physical disk and the rest of the disk is hidden, except for the MBR, which is provided as a copy:<br />
<br />
# dd if=/dev/hda count=1 of=''/path/to/mbr''<br />
# loop=`losetup --show -f ''/path/to/mbr''`<br />
# start=`blockdev --report /dev/hda''N'' | tail -1 | awk '{print $5}'`<br />
# size=`blockdev --getsz /dev/hda''N''`<br />
# disksize=`blockdev --getsz /dev/hda`<br />
# echo "0 1 linear $loop 0<br />
1 $((start-1)) zero<br />
$start $size linear /dev/hda''N'' 0<br />
$((start+size)) $((disksize-start-size)) zero" | dmsetup create qemu<br />
<br />
The table provided as standard input to {{ic|dmsetup}} has a similar format as the table in a VDMK descriptor file produced by {{ic|VBoxManage}} and can alternatively be loaded from a file with {{ic|dmsetup create qemu --table ''table_file''}}. To the virtual machine, only {{ic|/dev/hda''N''}} is accessible, while the rest of the hard disk reads as zeros and discards written data, except for the first sector. We can print the table for {{ic|/dev/mapper/qemu}} with {{ic|dmsetup table qemu}} (use {{ic|udevadm info -rq name /sys/dev/block/''major'':''minor''}} to translate {{ic|''major'':''minor''}} to the corresponding {{ic|/dev/''blockdevice''}} name). Use {{ic|dmsetup remove qemu}} and {{ic|losetup -d $loop}} to delete the created devices.<br />
<br />
A situation where this example would be useful is an existing Windows XP installation in a multi-boot configuration and maybe a hybrid partitioning scheme (on the physical hardware, Windows XP could be the only operating system that uses the MBR partition table, while more modern operating systems installed on the same computer could use the GUID Partition Table). Windows XP supports hardware profiles, so that that the same installation can be used with different hardware configurations alternatingly (in this case bare metal vs. virtual) with Windows needing to install drivers for newly detected hardware only once for every profile. Note that in this example the boot loader code in the copied MBR needs to be updated to directly load Windows XP from {{ic|/dev/hda''N''}} instead of trying to start the multi-boot capable boot loader (like GRUB) present in the original system. Alternatively, a copy of the boot partition containing the boot loader installation can be included in the virtual disk the same way as the MBR.<br />
<br />
===== Linear RAID =====<br />
<br />
You can also do this using software [[RAID]] in linear mode (you need the {{ic|linear.ko}} kernel driver) and a loopback device: <br />
<br />
First, you create some small file to hold the MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=32<br />
<br />
Here, a 16 KB (32 * 512 bytes) file is created. It is important not to make it too small (even if the MBR only needs a single 512 bytes block), since the smaller it will be, the smaller the chunk size of the software RAID device will have to be, which could have an impact on performance. Then, you setup a loopback device to the MBR file:<br />
<br />
# losetup -f ''/path/to/mbr''<br />
<br />
Let us assume the resulting device is {{ic|/dev/loop0}}, because we would not already have been using other loopbacks. Next step is to create the "merged" MBR + {{ic|/dev/hda''N''}} disk image using software RAID:<br />
<br />
# modprobe linear<br />
# mdadm --build --verbose /dev/md0 --chunk=16 --level=linear --raid-devices=2 /dev/loop0 /dev/hda''N''<br />
<br />
The resulting {{ic|/dev/md0}} is what you will use as a QEMU raw disk image (do not forget to set the permissions so that the emulator can access it). The last (and somewhat tricky) step is to set the disk configuration (disk geometry and partitions table) so that the primary partition start point in the MBR matches the one of {{ic|/dev/hda''N''}} inside {{ic|/dev/md0}} (an offset of exactly 16 * 512 = 16384 bytes in this example). Do this using {{ic|fdisk}} on the host machine, not in the emulator: the default raw disc detection routine from QEMU often results in non-kilobyte-roundable offsets (such as 31.5 KB, as in the previous section) that cannot be managed by the software RAID code. Hence, from the the host:<br />
<br />
# fdisk /dev/md0<br />
<br />
Press {{ic|X}} to enter the expert menu. Set number of 's'ectors per track so that the size of one cylinder matches the size of your MBR file. For two heads and a sector size of 512, the number of sectors per track should be 16, so we get cylinders of size 2x16x512=16k.<br />
<br />
Now, press {{ic|R}} to return to the main menu.<br />
<br />
Press {{ic|P}} and check that the cylinder size is now 16k.<br />
<br />
Now, create a single primary partition corresponding to {{ic|/dev/hda''N''}}. It should start at cylinder 2 and end at the end of the disk (note that the number of cylinders now differs from what it was when you entered fdisk.<br />
<br />
Finally, 'w'rite the result to the file: you are done. You now have a partition you can mount directly from your host, as well as part of a QEMU disk image:<br />
<br />
$ qemu-system-x86_64 -hdc /dev/md0 ''[...]''<br />
<br />
You can, of course, safely set any bootloader on this disk image using QEMU, provided the original {{ic|/dev/hda''N''}} partition contains the necessary tools.<br />
<br />
===== Network Block Device =====<br />
<br />
Instead of the methods decribed above, you may use {{ic|nbd-server}} (from the {{pkg|nbd}} package) to create an MBR wrapper for QEMU.<br />
<br />
Assuming you have already set up your MBR wrapper file like above, rename it to {{ic|wrapper.img.0}}. Then create a symbolic link named {{ic|wrapper.img.1}} in the same directory, pointing to your partition. Then put the following script in the same directory:<br />
<br />
#!/bin/sh<br />
dir="$(realpath "$(dirname "$0")")"<br />
cat >wrapper.conf <<EOF<br />
[generic]<br />
allowlist = true<br />
listenaddr = 127.713705<br />
port = 10809<br />
<br />
[wrap]<br />
exportname = $dir/wrapper.img<br />
multifile = true<br />
EOF<br />
<br />
nbd-server \<br />
-C wrapper.conf \<br />
-p wrapper.pid \<br />
"$@"<br />
<br />
The {{ic|.0}} and {{ic|.1}} suffixes are essential; the rest can be changed. After running the above script (which you may need to do as root to make sure nbd-server is able to access the partition), you can launch QEMU with:<br />
<br />
qemu-system-x86_64 -drive file=nbd:127.713705:10809:exportname=wrap ''[...]''<br />
<br />
== Networking ==<br />
<br />
{{Style|Network topologies (sections [[#Host-only networking]], [[#Internal networking]] and info spread out across other sections) should not be described alongside the various virtual interfaces implementations, such as [[#User-mode networking]], [[#Tap networking with QEMU]], [[#Networking with VDE2]].}}<br />
<br />
The performance of virtual networking should be better with tap devices and bridges than with user-mode networking or vde because tap devices and bridges are implemented in-kernel.<br />
<br />
In addition, networking performance can be improved by assigning virtual machines a [http://wiki.libvirt.org/page/Virtio virtio] network device rather than the default emulation of an e1000 NIC. See [[#Installing virtio drivers]] for more information.<br />
<br />
=== Link-level address caveat ===<br />
<br />
By giving the {{ic|-net nic}} argument to QEMU, it will, by default, assign a virtual machine a network interface with the link-level address {{ic|52:54:00:12:34:56}}. However, when using bridged networking with multiple virtual machines, it is essential that each virtual machine has a unique link-level (MAC) address on the virtual machine side of the tap device. Otherwise, the bridge will not work correctly, because it will receive packets from multiple sources that have the same link-level address. This problem occurs even if the tap devices themselves have unique link-level addresses because the source link-level address is not rewritten as packets pass through the tap device.<br />
<br />
Make sure that each virtual machine has a unique link-level address, but it should always start with {{ic|52:54:}}. Use the following option, replace ''X'' with arbitrary hexadecimal digit:<br />
<br />
$ qemu-system-x86_64 -net nic,macaddr=52:54:''XX:XX:XX:XX'' -net vde ''disk_image''<br />
<br />
Generating unique link-level addresses can be done in several ways:<br />
<br />
* Manually specify unique link-level address for each NIC. The benefit is that the DHCP server will assign the same IP address each time the virtual machine is run, but it is unusable for large number of virtual machines.<br />
* Generate random link-level address each time the virtual machine is run. Practically zero probability of collisions, but the downside is that the DHCP server will assign a different IP address each time. You can use the following command in a script to generate random link-level address in a {{ic|macaddr}} variable:<br />
<br />
{{bc|1=<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
qemu-system-x86_64 -net nic,macaddr="$macaddr" -net vde ''disk_image''<br />
}}<br />
<br />
* Use the following script {{ic|qemu-mac-hasher.py}} to generate the link-level address from the virtual machine name using a hashing function. Given that the names of virtual machines are unique, this method combines the benefits of the aforementioned methods: it generates the same link-level address each time the script is run, yet it preserves the practically zero probability of collisions.<br />
<br />
{{hc|qemu-mac-hasher.py|<nowiki><br />
#!/usr/bin/env python<br />
<br />
import sys<br />
import zlib<br />
<br />
if len(sys.argv) != 2:<br />
print("usage: %s <VM Name>" % sys.argv[0])<br />
sys.exit(1)<br />
<br />
crc = zlib.crc32(sys.argv[1].encode("utf-8")) & 0xffffffff<br />
crc = str(hex(crc))[2:]<br />
print("52:54:%s%s:%s%s:%s%s:%s%s" % tuple(crc))<br />
</nowiki>}}<br />
<br />
In a script, you can use for example:<br />
<br />
vm_name="''VM Name''"<br />
qemu-system-x86_64 -name "$vm_name" -net nic,macaddr=$(qemu-mac-hasher.py "$vm_name") -net vde ''disk_image''<br />
<br />
=== User-mode networking ===<br />
<br />
By default, without any {{ic|-netdev}} arguments, QEMU will use user-mode networking with a built-in DHCP server. Your virtual machines will be assigned an IP address when they run their DHCP client, and they will be able to access the physical host's network through IP masquerading done by QEMU.<br />
<br />
{{warning|This only works with the TCP and UDP protocols, so ICMP, including {{ic|ping}}, will not work. Do not use {{ic|ping}} to test network connectivity. To make ping work in the guest see [[Sysctl#Allow unprivileged users to create IPPROTO_ICMP sockets]].}}<br />
<br />
This default configuration allows your virtual machines to easily access the Internet, provided that the host is connected to it, but the virtual machines will not be directly visible on the external network, nor will virtual machines be able to talk to each other if you start up more than one concurrently.<br />
<br />
QEMU's user-mode networking can offer more capabilities such as built-in TFTP or SMB servers, redirecting host ports to the guest (for example to allow SSH connections to the guest) or attaching guests to VLANs so that they can talk to each other. See the QEMU documentation on the {{ic|-net user}} flag for more details.<br />
<br />
However, user-mode networking has limitations in both utility and performance. More advanced network configurations require the use of tap devices or other methods.<br />
<br />
{{Note|If the host system uses [[systemd-networkd]], make sure to symlink the {{ic|/etc/resolv.conf}} file as described in [[systemd-networkd#Required services and setup]], otherwise the DNS lookup in the guest system will not work.}}<br />
<br />
=== Tap networking with QEMU ===<br />
<br />
[[wikipedia:TUN/TAP|Tap devices]] are a Linux kernel feature that allows you to create virtual network interfaces that appear as real network interfaces. Packets sent to a tap interface are delivered to a userspace program, such as QEMU, that has bound itself to the interface.<br />
<br />
QEMU can use tap networking for a virtual machine so that packets sent to the tap interface will be sent to the virtual machine and appear as coming from a network interface (usually an Ethernet interface) in the virtual machine. Conversely, everything that the virtual machine sends through its network interface will appear on the tap interface.<br />
<br />
Tap devices are supported by the Linux bridge drivers, so it is possible to bridge together tap devices with each other and possibly with other host interfaces such as {{ic|eth0}}. This is desirable if you want your virtual machines to be able to talk to each other, or if you want other machines on your LAN to be able to talk to the virtual machines.<br />
<br />
{{Warning|If you bridge together tap device and some host interface, such as {{ic|eth0}}, your virtual machines will appear directly on the external network, which will expose them to possible attack. Depending on what resources your virtual machines have access to, you may need to take all the [[Firewalls|precautions]] you normally would take in securing a computer to secure your virtual machines. If the risk is too great, virtual machines have little resources or you set up multiple virtual machines, a better solution might be to use [[#Host-only networking|host-only networking]] and set up NAT. In this case you only need one firewall on the host instead of multiple firewalls for each guest.}}<br />
<br />
As indicated in the user-mode networking section, tap devices offer higher networking performance than user-mode. If the guest OS supports virtio network driver, then the networking performance will be increased considerably as well. Supposing the use of the tap0 device, that the virtio driver is used on the guest, and that no scripts are used to help start/stop networking, next is part of the qemu command one should see:<br />
<br />
-device virtio-net,netdev=network0 -netdev tap,id=network0,ifname=tap0,script=no,downscript=no<br />
<br />
But if already using a tap device with virtio networking driver, one can even boost the networking performance by enabling vhost, like:<br />
<br />
-device virtio-net,netdev=network0 -netdev tap,id=network0,ifname=tap0,script=no,downscript=no,vhost=on<br />
<br />
See [https://web.archive.org/web/20160222161955/http://www.linux-kvm.com:80/content/how-maximize-virtio-net-performance-vhost-net] for more information.<br />
<br />
==== Host-only networking ====<br />
<br />
If the bridge is given an IP address and traffic destined for it is allowed, but no real interface (e.g. {{ic|eth0}}) is connected to the bridge, then the virtual machines will be able to talk to each other and the host system. However, they will not be able to talk to anything on the external network, provided that you do not set up IP masquerading on the physical host. This configuration is called ''host-only networking'' by other virtualization software such as [[VirtualBox]].<br />
<br />
{{Tip|<br />
* If you want to set up IP masquerading, e.g. NAT for virtual machines, see the [[Internet sharing#Enable NAT]] page.<br />
* See [[Network bridge]] for information on creating bridge.<br />
* You may want to have a DHCP server running on the bridge interface to service the virtual network. For example, to use the {{ic|172.20.0.1/16}} subnet with [[dnsmasq]] as the DHCP server:<br />
<br />
{{bc|1=<br />
# ip addr add 172.20.0.1/16 dev br0<br />
# ip link set br0 up<br />
# dnsmasq --interface=br0 --bind-interfaces --dhcp-range=172.20.0.2,172.20.255.254<br />
}}<br />
}}<br />
<br />
==== Internal networking ====<br />
<br />
If you do not give the bridge an IP address and add an [[iptables]] rule to drop all traffic to the bridge in the INPUT chain, then the virtual machines will be able to talk to each other, but not to the physical host or to the outside network. This configuration is called ''internal networking'' by other virtualization software such as [[VirtualBox]]. You will need to either assign static IP addresses to the virtual machines or run a DHCP server on one of them.<br />
<br />
By default iptables would drop packets in the bridge network. You may need to use such iptables rule to allow packets in a bridged network:<br />
<br />
# iptables -I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Bridged networking using qemu-bridge-helper ====<br />
<br />
{{Note|This method is available since QEMU 1.1, see http://wiki.qemu.org/Features/HelperNetworking.}}<br />
<br />
This method does not require a start-up script and readily accommodates multiple taps and multiple bridges. It uses {{ic|/usr/lib/qemu/qemu-bridge-helper}} binary, which allows creating tap devices on an existing bridge.<br />
<br />
{{Tip|See [[Network bridge]] for information on creating bridge.}}<br />
<br />
First, create a configuration file containing the names of all bridges to be used by QEMU:<br />
<br />
{{hc|/etc/qemu/bridge.conf|<br />
allow ''bridge0''<br />
allow ''bridge1''<br />
...}}<br />
<br />
Now start the VM. The most basic usage would be:<br />
<br />
$ qemu-system-x86_64 -net nic -net bridge,br=''bridge0'' ''[...]''<br />
<br />
With multiple taps, the most basic usage requires specifying the VLAN for all additional NICs:<br />
<br />
$ qemu-system-x86_64 -net nic -net bridge,br=''bridge0'' -net nic,vlan=1 -net bridge,vlan=1,br=''bridge1'' ''[...]''<br />
<br />
==== Creating bridge manually ====<br />
<br />
{{Style|This section needs serious cleanup and may contain out-of-date information.}}<br />
<br />
{{Tip|Since QEMU 1.1, the [http://wiki.qemu.org/Features/HelperNetworking network bridge helper] can set tun/tap up for you without the need for additional scripting. See [[#Bridged networking using qemu-bridge-helper]].}}<br />
<br />
The following describes how to bridge a virtual machine to a host interface such as {{ic|eth0}}, which is probably the most common configuration. This configuration makes it appear that the virtual machine is located directly on the external network, on the same Ethernet segment as the physical host machine.<br />
<br />
We will replace the normal Ethernet adapter with a bridge adapter and bind the normal Ethernet adapter to it.<br />
<br />
* Install {{Pkg|bridge-utils}}, which provides {{ic|brctl}} to manipulate bridges.<br />
<br />
* Enable IPv4 forwarding:<br />
# sysctl -w net.ipv4.ip_forward=1<br />
<br />
To make the change permanent, change {{ic|1=net.ipv4.ip_forward = 0}} to {{ic|1=net.ipv4.ip_forward = 1}} in {{ic|/etc/sysctl.d/99-sysctl.conf}}.<br />
<br />
* Load the {{ic|tun}} module and configure it to be loaded on boot. See [[Kernel modules]] for details.<br />
<br />
* Now create the bridge. See [[Bridge with netctl]] for details. Remember to name your bridge as {{ic|br0}}, or change the scripts below to your bridge's name.<br />
<br />
* Create the script that QEMU uses to bring up the tap adapter with {{ic|root:kvm}} 750 permissions:<br />
<br />
{{hc|/etc/qemu-ifup|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifup"<br />
echo "Bringing up $1 for bridged mode..."<br />
sudo /usr/bin/ip link set $1 up promisc on<br />
echo "Adding $1 to br0..."<br />
sudo /usr/bin/brctl addif br0 $1<br />
sleep 2<br />
</nowiki>}}<br />
<br />
* Create the script that QEMU uses to bring down the tap adapter in {{ic|/etc/qemu-ifdown}} with {{ic|root:kvm}} 750 permissions:<br />
{{hc|/etc/qemu-ifdown|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifdown"<br />
sudo /usr/bin/ip link set $1 down<br />
sudo /usr/bin/brctl delif br0 $1<br />
sudo /usr/bin/ip link delete dev $1<br />
</nowiki>}}<br />
<br />
* Use {{ic|visudo}} to add the following to your {{ic|sudoers}} file:<br />
<br />
{{bc|<nowiki><br />
Cmnd_Alias QEMU=/usr/bin/ip,/usr/bin/modprobe,/usr/bin/brctl<br />
%kvm ALL=NOPASSWD: QEMU<br />
</nowiki>}}<br />
<br />
* You launch QEMU using the following {{ic|run-qemu}} script:<br />
<br />
{{hc|run-qemu|<nowiki><br />
#!/bin/bash<br />
USERID=$(whoami)<br />
<br />
# Get name of newly created TAP device; see https://bbs.archlinux.org/viewtopic.php?pid=1285079#p1285079<br />
precreationg=$(/usr/bin/ip tuntap list | /usr/bin/cut -d: -f1 | /usr/bin/sort)<br />
sudo /usr/bin/ip tuntap add user $USERID mode tap<br />
postcreation=$(/usr/bin/ip tuntap list | /usr/bin/cut -d: -f1 | /usr/bin/sort)<br />
IFACE=$(comm -13 <(echo "$precreationg") <(echo "$postcreation"))<br />
<br />
# This line creates a random MAC address. The downside is the DHCP server will assign a different IP address each time<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
# Instead, uncomment and edit this line to set a static MAC address. The benefit is that the DHCP server will assign the same IP address.<br />
# macaddr='52:54:be:36:42:a9'<br />
<br />
qemu-system-x86_64 -net nic,macaddr=$macaddr -net tap,ifname="$IFACE" $*<br />
<br />
sudo ip link set dev $IFACE down &> /dev/null<br />
sudo ip tuntap del $IFACE mode tap &> /dev/null<br />
</nowiki>}}<br />
<br />
Then to launch a VM, do something like this<br />
<br />
$ run-qemu -hda ''myvm.img'' -m 512<br />
<br />
* It is recommended for performance and security reasons to disable the [http://ebtables.netfilter.org/documentation/bridge-nf.html firewall on the bridge]:<br />
<br />
{{hc|/etc/sysctl.d/10-disable-firewall-on-bridge.conf|<nowiki><br />
net.bridge.bridge-nf-call-ip6tables = 0<br />
net.bridge.bridge-nf-call-iptables = 0<br />
net.bridge.bridge-nf-call-arptables = 0<br />
</nowiki>}}<br />
<br />
Run {{ic|sysctl -p /etc/sysctl.d/10-disable-firewall-on-bridge.conf}} to apply the changes immediately.<br />
<br />
See the [http://wiki.libvirt.org/page/Networking#Creating_network_initscripts libvirt wiki] and [https://bugzilla.redhat.com/show_bug.cgi?id=512206 Fedora bug 512206]. If you get errors by sysctl during boot about non-existing files, make the {{ic|bridge}} module load at boot. See [[Kernel modules#Automatic module loading with systemd]].<br />
<br />
Alternatively, you can configure [[iptables]] to allow all traffic to be forwarded across the bridge by adding a rule like this:<br />
<br />
-I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Network sharing between physical device and a Tap device through iptables ====<br />
<br />
{{Merge|Internet_sharing|Duplication, not specific to QEMU.}}<br />
<br />
Bridged networking works fine between a wired interface (Eg. eth0), and it is easy to setup. However if the host gets connected to the network through a wireless device, then bridging is not possible.<br />
<br />
See [[Network bridge#Wireless interface on a bridge]] as a reference.<br />
<br />
One way to overcome that is to setup a tap device with a static IP, making linux automatically handle the routing for it, and then forward traffic between the tap interface and the device connected to the network through iptables rules.<br />
<br />
See [[Internet sharing]] as a reference.<br />
<br />
There you can find what is needed to share the network between devices, included tap and tun ones. The following just hints further on some of the host configurations required. As indicated in the reference above, the client needs to be configured for a static IP, using the IP assigned to the tap interface as the gateway. The caveat is that the DNS servers on the client might need to be manually edited if they change when changing from one host device connected to the network to another.<br />
<br />
To allow IP forwarding on every boot, one need to add the following lines to sysctl configuration file inside {{ic|/etc/sysctl.d}}:<br />
<br />
net.ipv4.ip_forward = 1<br />
net.ipv6.conf.default.forwarding = 1<br />
net.ipv6.conf.all.forwarding = 1<br />
<br />
The iptables rules can look like:<br />
<br />
# Forwarding from/to outside<br />
iptables -A FORWARD -i ${INT} -o ${EXT_0} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_1} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_2} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_0} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_1} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_2} -o ${INT} -j ACCEPT<br />
# NAT/Masquerade (network address translation)<br />
iptables -t nat -A POSTROUTING -o ${EXT_0} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_1} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_2} -j MASQUERADE<br />
<br />
The prior supposes there are 3 devices connected to the network sharing traffic with one internal device, where for example:<br />
<br />
INT=tap0<br />
EXT_0=eth0<br />
EXT_1=wlan0<br />
EXT_2=tun0<br />
<br />
The prior shows a forwarding that would allow sharing wired and wireless connections with the tap device.<br />
<br />
The forwarding rules shown are stateless, and for pure forwarding. One could think of restricting specific traffic, putting a firewall in place to protect the guest and others. However those would decrease the networking performance, while a simple bridge does not include any of that.<br />
<br />
Bonus: Whether the connection is wired or wireless, if one gets connected through VPN to a remote site with a tun device, supposing the tun device opened for that connection is tun0, and the prior iptables rules are applied, then the remote connection gets also shared with the guest. This avoids the need for the guest to also open a VPN connection. Again, as the guest networking needs to be static, then if connecting the host remotely this way, one most probably will need to edit the DNS servers on the guest.<br />
<br />
=== Networking with VDE2 ===<br />
<br />
{{Style|This section needs serious cleanup and may contain out-of-date information.}}<br />
<br />
==== What is VDE? ====<br />
<br />
VDE stands for Virtual Distributed Ethernet. It started as an enhancement of [[User-mode Linux|uml]]_switch. It is a toolbox to manage virtual networks.<br />
<br />
The idea is to create virtual switches, which are basically sockets, and to "plug" both physical and virtual machines in them. The configuration we show here is quite simple; However, VDE is much more powerful than this, it can plug virtual switches together, run them on different hosts and monitor the traffic in the switches. You are invited to read [https://wiki.virtualsquare.org/ the documentation of the project].<br />
<br />
The advantage of this method is you do not have to add sudo privileges to your users. Regular users should not be allowed to run modprobe.<br />
<br />
==== Basics ====<br />
<br />
VDE support can be [[pacman|installed]] via the {{Pkg|vde2}} package.<br />
<br />
In our config, we use tun/tap to create a virtual interface on my host. Load the {{ic|tun}} module (see [[Kernel modules]] for details):<br />
<br />
# modprobe tun<br />
<br />
Now create the virtual switch:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
<br />
This line creates the switch, creates {{ic|tap0}}, "plugs" it, and allows the users of the group {{ic|users}} to use it.<br />
<br />
The interface is plugged in but not configured yet. To configure it, run this command:<br />
<br />
# ip addr add 192.168.100.254/24 dev tap0<br />
<br />
Now, you just have to run KVM with these {{ic|-net}} options as a normal user:<br />
<br />
$ qemu-system-x86_64 -net nic -net vde -hda ''[...]''<br />
<br />
Configure networking for your guest as you would do in a physical network.<br />
<br />
{{Tip|You might want to set up NAT on tap device to access the internet from the virtual machine. See [[Internet sharing#Enable NAT]] for more information.}}<br />
<br />
==== Startup scripts ====<br />
<br />
Example of main script starting VDE:<br />
<br />
{{hc|/etc/systemd/scripts/qemu-network-env|<nowiki><br />
#!/bin/sh<br />
# QEMU/VDE network environment preparation script<br />
<br />
# The IP configuration for the tap device that will be used for<br />
# the virtual machine network:<br />
<br />
TAP_DEV=tap0<br />
TAP_IP=192.168.100.254<br />
TAP_MASK=24<br />
TAP_NETWORK=192.168.100.0<br />
<br />
# Host interface<br />
NIC=eth0<br />
<br />
case "$1" in<br />
start)<br />
echo -n "Starting VDE network for QEMU: "<br />
<br />
# If you want tun kernel module to be loaded by script uncomment here<br />
#modprobe tun 2>/dev/null<br />
## Wait for the module to be loaded<br />
#while ! lsmod | grep -q "^tun"; do echo "Waiting for tun device"; sleep 1; done<br />
<br />
# Start tap switch<br />
vde_switch -tap "$TAP_DEV" -daemon -mod 660 -group users<br />
<br />
# Bring tap interface up<br />
ip address add "$TAP_IP"/"$TAP_MASK" dev "$TAP_DEV"<br />
ip link set "$TAP_DEV" up<br />
<br />
# Start IP Forwarding<br />
echo "1" > /proc/sys/net/ipv4/ip_forward<br />
iptables -t nat -A POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
;;<br />
stop)<br />
echo -n "Stopping VDE network for QEMU: "<br />
# Delete the NAT rules<br />
iptables -t nat -D POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
<br />
# Bring tap interface down<br />
ip link set "$TAP_DEV" down<br />
<br />
# Kill VDE switch<br />
pgrep vde_switch | xargs kill -TERM<br />
;;<br />
restart|reload)<br />
$0 stop<br />
sleep 1<br />
$0 start<br />
;;<br />
*)<br />
echo "Usage: $0 {start|stop|restart|reload}"<br />
exit 1<br />
esac<br />
exit 0<br />
</nowiki>}}<br />
<br />
Example of systemd service using the above script:<br />
<br />
{{hc|/etc/systemd/system/qemu-network-env.service|<nowiki><br />
[Unit]<br />
Description=Manage VDE Switch<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/etc/systemd/scripts/qemu-network-env start<br />
ExecStop=/etc/systemd/scripts/qemu-network-env stop<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
Change permissions for {{ic|qemu-network-env}} to be executable<br />
<br />
# chmod u+x /etc/systemd/scripts/qemu-network-env<br />
<br />
You can [[start]] {{ic|qemu-network-env.service}} as usual.<br />
<br />
====Alternative method====<br />
<br />
If the above method does not work or you do not want to mess with kernel configs, TUN, dnsmasq, and iptables you can do the following for the same result.<br />
<br />
# vde_switch -daemon -mod 660 -group users<br />
# slirpvde --dhcp --daemon<br />
<br />
Then, to start the VM with a connection to the network of the host:<br />
<br />
$ qemu-system-x86_64 -net nic,macaddr=52:54:00:00:EE:03 -net vde ''disk_image''<br />
<br />
=== VDE2 Bridge ===<br />
<br />
Based on [https://selamatpagicikgu.wordpress.com/2011/06/08/quickhowto-qemu-networking-using-vde-tuntap-and-bridge/ quickhowto: qemu networking using vde, tun/tap, and bridge] graphic. Any virtual machine connected to vde is externally exposed. For example, each virtual machine can receive DHCP configuration directly from your ADSL router.<br />
<br />
==== Basics ====<br />
<br />
Remember that you need {{ic|tun}} module and {{Pkg|bridge-utils}} package.<br />
<br />
Create the vde2/tap device:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
# ip link set tap0 up<br />
<br />
Create bridge:<br />
<br />
# brctl addbr br0<br />
<br />
Add devices:<br />
<br />
# brctl addif br0 eth0<br />
# brctl addif br0 tap0<br />
<br />
And configure bridge interface:<br />
<br />
# dhcpcd br0<br />
<br />
==== Startup scripts ====<br />
<br />
All devices must be set up. And only the bridge needs an IP address. For physical devices on the bridge (e.g. {{ic|eth0}}), this can be done with [[netctl]] using a custom Ethernet profile with:<br />
<br />
{{hc|/etc/netctl/ethernet-noip|2=<br />
Description='A more versatile static Ethernet connection'<br />
Interface=eth0<br />
Connection=ethernet<br />
IP=no<br />
}}<br />
<br />
The following custom systemd service can be used to create and activate a VDE2 tap interface for use in the {{ic|users}} user group.<br />
<br />
{{hc|/etc/systemd/system/vde2@.service|2=<br />
[Unit]<br />
Description=Network Connectivity for %i<br />
Wants=network.target<br />
Before=network.target<br />
<br />
[Service]<br />
Type=oneshot<br />
RemainAfterExit=yes<br />
ExecStart=/usr/bin/vde_switch -tap %i -daemon -mod 660 -group users<br />
ExecStart=/usr/bin/ip link set dev %i up<br />
ExecStop=/usr/bin/ip addr flush dev %i<br />
ExecStop=/usr/bin/ip link set dev %i down<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
}}<br />
<br />
And finally, you can create the [[Bridge with netctl|bridge interface with netctl]].<br />
<br />
=== Shorthand configuration ===<br />
<br />
If you are using QEMU with various networking options a lot, you probably have created a lot of {{ic|-netdev}} and {{ic|-device}} argument pairs, which gets quite repetitive. You can instead use the {{ic|-nic}} argument to combine {{ic|-netdev}} and {{ic|-device}} together, so that, for example, these arguments:<br />
<br />
-netdev tap,id=network0,ifname=tap0,script=no,downscript=no,vhost=on -device virtio-net-pci,netdev=network0<br />
<br />
become:<br />
<br />
-nic tap,script=no,downscript=no,vhost=on,model=virtio-net-pci<br />
<br />
Notice the lack of network IDs, and that the device was created with {{ic|1=model=}}. The first half of the {{ic|-nic}} parameters are {{ic|-netdev}} parameters, whereas the second half (after {{ic|1=model=}}) are related with the device. The same parameters (for example, {{ic|1=smb=}}) are used. To completely disable the networking use {{ic|-nic none}}.<br />
<br />
See [https://qemu.weilnetz.de/doc/qemu-doc.html#Network-options QEMU networking documentation] for more information on parameters you can use.<br />
<br />
== Graphic card ==<br />
<br />
QEMU can emulate a standard graphic card text mode using {{ic|-curses}} command line option. This allows to type text and see text output directly inside a text terminal.<br />
<br />
QEMU can emulate several types of VGA card. The card type is passed in the {{ic|-vga ''type''}} command line option and can be {{ic|std}}, {{ic|qxl}}, {{ic|vmware}}, {{ic|virtio}}, {{ic|cirrus}} or {{ic|none}}.<br />
<br />
=== std ===<br />
<br />
With {{ic|-vga std}} you can get a resolution of up to 2560 x 1600 pixels without requiring guest drivers. This is the default since QEMU 2.2.<br />
<br />
=== qxl ===<br />
<br />
QXL is a paravirtual graphics driver with 2D support. To use it, pass the {{ic|-vga qxl}} option and install drivers in the guest. You may want to use [[#SPICE]] for improved graphical performance when using QXL.<br />
<br />
On Linux guests, the {{ic|qxl}} and {{ic|bochs_drm}} kernel modules must be loaded in order to gain a decent performance.<br />
<br />
Default VGA memory size for QXL devices is 16M which is sufficient to drive resolutions approximately up to QHD (2560x1440). To enable higher resolutions, [[#Multi-monitor support|increase vga_memmb]].<br />
<br />
=== vmware ===<br />
<br />
Although it is a bit buggy, it performs better than std and cirrus. Install the VMware drivers {{Pkg|xf86-video-vmware}} and {{Pkg|xf86-input-vmmouse}} for Arch Linux guests.<br />
<br />
=== virtio ===<br />
<br />
{{ic|virtio-vga}} / {{ic|virtio-gpu}} is a paravirtual 3D graphics driver based on [https://virgil3d.github.io/ virgl]. Currently a work in progress, supporting only very recent (>= 4.4) Linux guests with {{Pkg|mesa}} (>=11.2) compiled with the option {{ic|1=gallium-drivers=virgl}}.<br />
<br />
To enable 3D acceleration on the guest system select this vga with {{ic|-vga virtio}} and enable the opengl context in the display device with {{ic|1=-display sdl,gl=on}} or {{ic|1=-display gtk,gl=on}} for the sdl and gtk display output respectively. Successful configuration can be confirmed looking at the kernel log in the guest:<br />
<br />
{{hc|$ dmesg {{!}} grep drm |<br />
[drm] pci: virtio-vga detected<br />
[drm] virgl 3d acceleration enabled<br />
}}<br />
<br />
=== cirrus ===<br />
<br />
The cirrus graphical adapter was the default [http://wiki.qemu.org/ChangeLog/2.2#VGA before 2.2]. It [https://www.kraxel.org/blog/2014/10/qemu-using-cirrus-considered-harmful/ should not] be used on modern systems.<br />
<br />
=== none ===<br />
<br />
This is like a PC that has no VGA card at all. You would not even be able to access it with the {{ic|-vnc}} option. Also, this is different from the {{ic|-nographic}} option which lets QEMU emulate a VGA card, but disables the SDL display.<br />
<br />
== SPICE ==<br />
The [http://spice-space.org/ SPICE project] aims to provide a complete open source solution for remote access to virtual machines in a seamless way.<br />
=== Enabling SPICE support on the host ===<br />
The following is an example of booting with SPICE as the remote desktop protocol, including the support for copy and paste from host:<br />
<br />
$ qemu-system-x86_64 -vga qxl -device virtio-serial-pci -spice port=5930,disable-ticketing -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
The parameters have the following meaning:<br />
<br />
# {{ic|-device virtio-serial-pci}} adds a virtio-serial device<br />
# {{ic|1=-spice port=5930,disable-ticketing}} set TCP port {{ic|5930}} for spice channels listening and allow client to connect without authentication{{Tip|Using [[wikipedia:Unix_socket|Unix sockets]] instead of TCP ports does not involve using network stack on the host system. It does not imply that packets are encapsulated and decapsulated to use the network and the related protocol. The sockets are identified solely by the inodes on the hard drive. It is therefore considered better for performance. Use instead {{ic|1=-spice unix,addr=/tmp/vm_spice.socket,disable-ticketing}}.}}<br />
# {{ic|1=-device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0}} opens a port for spice vdagent in the virtio-serial device,<br />
# {{ic|1=-chardev spicevmc,id=spicechannel0,name=vdagent}} adds a spicevmc chardev for that port. It is important that the {{ic|1=chardev=}} option of the {{ic|virtserialport}} device matches the {{ic|1=id=}} option given to the {{ic|chardev}} option ({{ic|spicechannel0}} in this example). It is also important that the port name is {{ic|com.redhat.spice.0}}, because that is the namespace where vdagent is looking for in the guest. And finally, specify {{ic|1=name=vdagent}} so that spice knows what this channel is for.<br />
<br />
=== Connecting to the guest with a SPICE client ===<br />
<br />
A SPICE client is necessary to connect to the guest. In Arch, the following clients are available:<br />
<br />
{{App|virt-viewer|SPICE client recommended by the protocol developers, a subset of the virt-manager project.|https://virt-manager.org/|{{Pkg|virt-viewer}}}}<br />
<br />
{{App|spice-gtk|SPICE GTK client, a subset of the SPICE project. Embedded into other applications as a widget.|https://www.spice-space.org/|{{Pkg|spice-gtk}}}}<br />
<br />
For clients that run on smartphone or on other platforms, refer to the ''Other clients'' section in [http://www.spice-space.org/download.html spice-space download].<br />
<br />
==== Manually running a SPICE client ====<br />
<br />
One way of connecting to a guest listening on Unix socket {{ic|/tmp/vm_spice.socket}} is to manually run the SPICE client using {{ic|$ remote-viewer spice+unix:///tmp/vm_spice.socket}} or {{ic|1=$ spicy --uri="spice+unix:///tmp/vm_spice.socket"}}, depending on the desired client. Since QEMU in SPICE mode acts similarly to a remote desktop server, it may be more convenient to run QEMU in daemon mode with the {{ic|-daemonize}} parameter.<br />
<br />
{{Tip|To connect to the guest through SSH tunelling, the following type of command can be used: {{bc|$ ssh -fL 5999:localhost:5930 ''my.domain.org'' sleep 10; spicy -h 127.0.0.1 -p 5999}}<br />
This example connects ''spicy'' to the local port {{ic|5999}} which is forwarded through SSH to the guest's SPICE server located at the address ''my.domain.org'', port {{ic|5930}}.<br />
Note the {{ic|-f}} option that requests ssh to execute the command {{ic|sleep 10}} in the background. This way, the ssh session runs while the client is active and auto-closes once the client ends.<br />
}}<br />
<br />
==== Running a SPICE client with QEMU ====<br />
<br />
QEMU can automatically start a SPICE client with an appropriate socket, if the display is set to SPICE with the {{ic|-display spice-app}} parameter. This will use the system's default SPICE client as the viewer, determined by your [[XDG_MIME_Applications#mimeapps.list|mimeapps.list]] files.<br />
<br />
=== Enabling SPICE support on the guest ===<br />
<br />
For '''Arch Linux guests''', for improved support for multiple monitors or clipboard sharing, the following packages should be installed:<br />
* {{Pkg|spice-vdagent}}: Spice agent xorg client that enables copy and paste between client and X-session and more.<br />
* {{Pkg|xf86-video-qxl}}: Xorg X11 qxl video driver<br />
For guests under '''other operating systems''', refer to the ''Guest'' section in [http://www.spice-space.org/download.html spice-space download].<br />
<br />
=== Password authentication with SPICE ===<br />
<br />
If you want to enable password authentication with SPICE you need to remove {{ic|disable-ticketing}} from the {{ic|-spice}} argument and instead add {{ic|1=password=''yourpassword''}}. For example:<br />
<br />
$ qemu-system-x86_64 -vga qxl -spice port=5900,password=''yourpassword'' -device virtio-serial-pci -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
Your SPICE client should now ask for the password to be able to connect to the SPICE server.<br />
<br />
=== TLS encrypted communication with SPICE ===<br />
<br />
You can also configure TLS encryption for communicating with the SPICE server. First, you need to have a directory which contains the following files (the names must be exactly as indicated):<br />
<br />
* {{ic|ca-cert.pem}}: the CA master certificate.<br />
* {{ic|server-cert.pem}}: the server certificate signed with {{ic|ca-cert.pem}}.<br />
* {{ic|server-key.pem}}: the server private key.<br />
<br />
An example of generation of self-signed certificates with your own generated CA for your server is shown in the [https://www.spice-space.org/spice-user-manual.html#_generating_self_signed_certificates Spice User Manual].<br />
<br />
Afterwards, you can run QEMU with SPICE as explained above but using the following {{ic|-spice}} argument: {{ic|1=-spice tls-port=5901,password=''yourpassword'',x509-dir=''/path/to/pki_certs''}}, where {{ic|''/path/to/pki_certs''}} is the directory path that contains the three needed files shown earlier.<br />
<br />
It is now possible to connect to the server using {{pkg|virt-viewer}}:<br />
<br />
$ remote-viewer spice://''hostname''?tls-port=5901 --spice-ca-file=''/path/to/ca-cert.pem'' --spice-host-subject="C=''XX'',L=''city'',O=''organization'',CN=''hostname''" --spice-secure-channels=all<br />
<br />
Keep in mind that the {{ic|--spice-host-subject}} parameter needs to be set according to your {{ic|server-cert.pem}} subject. You also need to copy {{ic|ca-cert.pem}} to every client to verify the server certificate.<br />
<br />
{{Tip|You can get the subject line of the server certificate in the correct format for {{ic|--spice-host-subject}} (with entries separated by commas) using the following command: {{bc|<nowiki>$ openssl x509 -noout -subject -in server-cert.pem | cut -d' ' -f2- | sed 's/\///' | sed 's/\//,/g'</nowiki>}}<br />
}}<br />
<br />
The equivalent {{Pkg|spice-gtk}} command is:<br />
<br />
$ spicy -h ''hostname'' -s 5901 --spice-ca-file=ca-cert.pem --spice-host-subject="C=''XX'',L=''city'',O=''organization'',CN=''hostname''" --spice-secure-channels=all<br />
<br />
== VNC ==<br />
<br />
One can add the {{ic|-vnc :''X''}} option to have QEMU redirect the VGA display to the VNC session. Substitute {{ic|''X''}} for the number of the display (0 will then listen on 5900, 1 on 5901...).<br />
<br />
$ qemu-system-x86_64 -vnc :0<br />
<br />
An example is also provided in the [[#Starting QEMU virtual machines on boot]] section.<br />
{{Warning|The default VNC server setup does not use any form of authentication. Any user can connect from any host.}}<br />
<br />
=== Basic password authentication ===<br />
<br />
An access password can be setup easily by using the {{ic|password}} option. The password must be indicated in the QEMU monitor and connection is only possible once the password is provided.<br />
<br />
$ qemu-system-x86_64 -vnc :0,password -monitor stdio<br />
<br />
In the QEMU monitor, password is set using the command {{ic|change vnc password}} and then indicating the password.<br />
<br />
The following command line directly runs vnc with a password:<br />
<br />
$ printf "change vnc password\n%s\n" MYPASSWORD | qemu-system-x86_64 -vnc :0,password -monitor stdio<br />
<br />
{{Note|The password is limited to 8 characters and can be guessed through brute force attack. More elaborated protection is strongly recommended for public network.}}<br />
<br />
== Audio ==<br />
<br />
=== Host ===<br />
<br />
The {{ic|-audiodev}} flag sets the audio backend driver and its options. The list of available audio backend drivers and their optional settings is detailed in the {{man|1|qemu}}. man page.<br />
<br />
At the bare minimum, you need to choose a driver and set an id.<br />
<br />
-audiodev pa,id=snd0<br />
<br />
=== Guest ===<br />
<br />
==== With audiodev ====<br />
<br />
===== Intel HD Audio =====<br />
<br />
For Intel HD Audio emulation add both controller and codec devices. To list the available Intel HDA Audio devices:<br />
<br />
$ qemu-system-x86_64 -device help | grep hda<br />
<br />
Add the audio controller<br />
<br />
-device ich9-intel-hda<br />
<br />
Add the audio codec and map it to a host audio backend id<br />
<br />
-device hda-output,audiodev=snd0<br />
<br />
===== Intel 82801AA AC97 =====<br />
<br />
For AC97 emulation just add the audio card device and map it to a host audio backend id<br />
<br />
-device AC97,audiodev=snd0<br />
<br />
==== Without audiodev ====<br />
<br />
To get list of the supported emulation audio drivers:<br />
$ qemu-system-x86_64 -soundhw help<br />
<br />
To use e.g. {{ic|hda}} driver for the guest use the {{ic|-device intel-hda -device hda-duplex}} command with QEMU.<br />
<br />
{{Note|Video graphic card emulated drivers for the guest machine may also cause a problem with the sound quality. Test one by one to make it work. You can list possible options with {{ic|<nowiki>qemu-system-x86_64 -h | grep vga</nowiki>}}.}}<br />
<br />
== Installing virtio drivers ==<br />
<br />
QEMU offers guests the ability to use paravirtualized block and network devices using the [http://wiki.libvirt.org/page/Virtio virtio] drivers, which provide better performance and lower overhead.<br />
<br />
* A virtio block device requires the option {{Ic|-drive}} for passing a disk image, with parameter {{Ic|1=if=virtio}}:<br />
$ qemu-system-x86_64 -boot order=c -drive file=''disk_image'',if=virtio<br />
<br />
* Almost the same goes for the network:<br />
$ qemu-system-x86_64 -nic user,model=virtio-net-pci<br />
<br />
{{Note|This will only work if the guest machine has drivers for virtio devices. Linux does, and the required drivers are included in Arch Linux, but there is no guarantee that virtio devices will work with other operating systems.}}<br />
<br />
=== Preparing an (Arch) Linux guest ===<br />
<br />
To use virtio devices after an Arch Linux guest has been installed, the following modules must be loaded in the guest: {{Ic|virtio}}, {{Ic|virtio_pci}}, {{Ic|virtio_blk}}, {{Ic|virtio_net}}, and {{Ic|virtio_ring}}. For 32-bit guests, the specific "virtio" module is not necessary.<br />
<br />
If you want to boot from a virtio disk, the initial ramdisk must contain the necessary modules. By default, this is handled by [[mkinitcpio]]'s {{ic|autodetect}} hook. Otherwise use the {{ic|MODULES}} array in {{ic|/etc/mkinitcpio.conf}} to include the necessary modules and rebuild the initial ramdisk.<br />
<br />
{{hc|/etc/mkinitcpio.conf|2=<br />
MODULES=(virtio virtio_blk virtio_pci virtio_net)}}<br />
<br />
Virtio disks are recognized with the prefix {{ic|'''v'''}} (e.g. {{ic|'''v'''da}}, {{ic|'''v'''db}}, etc.); therefore, changes must be made in at least {{ic|/etc/fstab}} and {{ic|/boot/grub/grub.cfg}} when booting from a virtio disk.<br />
<br />
{{Tip|When referencing disks by [[UUID]] in both {{ic|/etc/fstab}} and bootloader, nothing has to be done.}}<br />
<br />
Further information on paravirtualization with KVM can be found [http://www.linux-kvm.org/page/Boot_from_virtio_block_device here].<br />
<br />
You might also want to install {{Pkg|qemu-guest-agent}} to implement support for QMP commands that will enhance the hypervisor management capabilities. After installing the package you can enable and start the {{ic|qemu-ga.service}}.<br />
<br />
=== Preparing a Windows guest ===<br />
<br />
==== Block device drivers ====<br />
<br />
===== New Install of Windows =====<br />
<br />
Windows does not come with the virtio drivers. Therefore, you will need to load them during installation. There are basically two ways to do this: via Floppy Disk or via ISO files. Both images can be downloaded from the [https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/stable-virtio/virtio-win.iso Fedora repository].<br />
<br />
The floppy disk option is difficult because you will need to press F6 (Shift-F6 on newer Windows) at the very beginning of powering on the QEMU. This is difficult since you need time to connect your VNC console window. You can attempt to add a delay to the boot sequence. See {{man|1|qemu}} for more details about applying a delay at boot.<br />
<br />
The ISO option to load drivers is the preferred way, but it is available only on Windows Vista and Windows Server 2008 and later. The procedure is to load the image with virtio drivers in an additional cdrom device along with the primary disk device and Windows installer:<br />
<br />
$ qemu-system-x86_64 ... \<br />
-drive file=''windows_disk_image'',index=0,media=disk,if=virtio \<br />
-drive file=''windows.iso'',index=2,media=cdrom \<br />
-drive file=''virtio.iso'',index=3,media=cdrom \<br />
...<br />
<br />
During the installation, at some stage, the Windows installer will ask "Where do you want to install Windows?", it will give a warning that no disks are found. Follow the example instructions below (based on Windows Server 2012 R2 with Update).<br />
<br />
* Select the option ''Load Drivers''.<br />
* Uncheck the box for ''Hide drivers that aren't compatible with this computer's hardware''.<br />
* Click the browse button and open the CDROM for the virtio iso, usually named "virtio-win-XX".<br />
* Now browse to {{ic|E:\viostor\[your-os]\amd64}}, select it, and confirm.<br />
<br />
You should now see your virtio disk(s) listed here, ready to be selected, formatted and installed to.<br />
<br />
===== Change Existing Windows VM to use virtio =====<br />
<br />
Modifying an existing Windows guest for booting from virtio disk requires that the virtio driver is available in the guest and that it is loaded at boot time.<br />
<br />
One can find the virtio disk driver in the [https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/stable-virtio/virtio-win.iso Fedora repository].<br />
<br />
Now, create a new disk image that will be used to search for the virtio driver:<br />
<br />
$ qemu-img create -f qcow2 ''fake.qcow2'' 1G<br />
<br />
Run the original Windows guest (with the boot disk still in IDE mode) with the fake disk (in virtio mode) and a CD-ROM with the driver.<br />
<br />
$ qemu-system-x86_64 -m 512 -drive file=''windows_disk_image'',if=ide -drive file=''fake.qcow2'',if=virtio -cdrom virtio-win-0.1-81.iso<br />
<br />
Windows will detect the fake disk and look for a suitable driver. If it fails, go to ''Device Manager'', locate the SCSI drive with an exclamation mark icon (should be open), click ''Update driver'' and select the virtual CD-ROM. Do not navigate to the driver folder within the CD-ROM, simply select the CD-ROM drive and Windows will find the appropriate driver automatically (tested for Windows 7 SP1).<br />
<br />
Request Windows to boot in safe mode next time it starts up. This can be done using the ''msconfig.exe'' tool in Windows. In safe mode all the drivers will be loaded at boot time including the new virtio driver. Once Windows knows that the virtio driver is required at boot it will memorize it for future boot.<br />
<br />
Once instructed to boot in safe mode, you can turn off the virtual machine and launch it again, now with the boot disk attached in virtio mode:<br />
<br />
$ qemu-system-x86_64 -m 512 -drive file=''windows_disk_image'',if=virtio<br />
<br />
You should boot in safe mode with virtio driver loaded, you can now return to ''msconfig.exe'' disable safe mode boot and restart Windows.<br />
<br />
{{Note|If you encounter the blue screen of death using the {{ic|1=if=virtio}} parameter, it probably means the virtio disk driver is not installed or not loaded at boot time, reboot in safe mode and check your driver configuration.}}<br />
<br />
==== Network drivers ====<br />
<br />
Installing virtio network drivers is a bit easier, simply add the {{ic|-nic}} argument.<br />
<br />
$ qemu-system-x86_64 -m 512 -drive file=''windows_disk_image'',if=virtio -nic user,model=virtio-net-pci -cdrom virtio-win-0.1-74.iso<br />
<br />
Windows will detect the network adapter and try to find a driver for it. If it fails, go to the ''Device Manager'', locate the network adapter with an exclamation mark icon (should be open), click ''Update driver'' and select the virtual CD-ROM. Do not forget to select the checkbox which says to search for directories recursively.<br />
<br />
==== Balloon driver ====<br />
<br />
If you want to track you guest memory state (for example via {{ic|virsh}} command {{ic|dommemstat}}) or change guest's memory size in runtime (you still will not be able to change memory size, but can limit memory usage via inflating balloon driver) you will need to install guest balloon driver.<br />
<br />
For this you will need to go to ''Device Manager'', locate ''PCI standard RAM Controller'' in ''System devices'' (or unrecognized PCI controller from ''Other devices'') and choose ''Update driver''. In opened window you will need to choose ''Browse my computer...'' and select the CD-ROM (and do not forget the ''Include subdirectories'' checkbox). Reboot after installation. This will install the driver and you will be able to inflate the balloon (for example via hmp command {{ic|balloon ''memory_size''}}, which will cause balloon to take as much memory as possible in order to shrink the guest's available memory size to ''memory_size''). However, you still will not be able to track guest memory state. In order to do this you will need to install ''Balloon'' service properly. For that open command line as administrator, go to the CD-ROM, ''Balloon'' directory and deeper, depending on your system and architecture. Once you are in ''amd64'' (''x86'') directory, run {{ic|blnsrv.exe -i}} which will do the installation. After that {{ic|virsh}} command {{ic|dommemstat}} should be outputting all supported values.<br />
<br />
=== Preparing a FreeBSD guest ===<br />
<br />
Install the {{ic|emulators/virtio-kmod}} port if you are using FreeBSD 8.3 or later up until 10.0-CURRENT where they are included into the kernel. After installation, add the following to your {{ic|/boot/loader.conf}} file:<br />
<br />
{{bc|1=<br />
virtio_load="YES"<br />
virtio_pci_load="YES"<br />
virtio_blk_load="YES"<br />
if_vtnet_load="YES"<br />
virtio_balloon_load="YES"<br />
}}<br />
<br />
Then modify your {{ic|/etc/fstab}} by doing the following:<br />
<br />
# sed -ibak "s/ada/vtbd/g" /etc/fstab<br />
<br />
And verify that {{ic|/etc/fstab}} is consistent. If anything goes wrong, just boot into a rescue CD and copy {{ic|/etc/fstab.bak}} back to {{ic|/etc/fstab}}.<br />
<br />
== QEMU monitor ==<br />
<br />
While QEMU is running, a monitor console is provided in order to provide several ways to interact with the virtual machine running. The QEMU monitor offers interesting capabilities such as obtaining information about the current virtual machine, hotplugging devices, creating snapshots of the current state of the virtual machine, etc. To see the list of all commands, run {{ic|help}} or {{ic|?}} in the QEMU monitor console or review the relevant section of the [https://qemu.weilnetz.de/doc/qemu-doc.html#pcsys_005fmonitor official QEMU documentation].<br />
<br />
=== Accessing the monitor console ===<br />
<br />
==== Graphical view ====<br />
<br />
When using the {{ic|std}} default graphics option, one can access the QEMU monitor by pressing {{ic|Ctrl+Alt+2}} or by clicking ''View > compatmonitor0'' in the QEMU window. To return to the virtual machine graphical view either press {{ic|Ctrl+Alt+1}} or click ''View > VGA''.<br />
<br />
However, the standard method of accessing the monitor is not always convenient and does not work in all graphic outputs QEMU supports.<br />
<br />
==== Telnet ====<br />
<br />
To enable [[telnet]], run QEMU with the {{ic|-monitor telnet:127.0.0.1:''port'',server,nowait}} parameter. When the virtual machine is started you will be able to access the monitor via telnet:<br />
<br />
$ telnet 127.0.0.1 ''port''<br />
<br />
{{Note|If {{ic|127.0.0.1}} is specified as the IP to listen it will be only possible to connect to the monitor from the same host QEMU is running on. If connecting from remote hosts is desired, QEMU must be told to listen {{ic|0.0.0.0}} as follows: {{ic|-monitor telnet:0.0.0.0:''port'',server,nowait}}. Keep in mind that it is recommended to have a [[firewall]] configured in this case or make sure your local network is completely trustworthy since this connection is completely unauthenticated and unencrypted.}}<br />
<br />
==== UNIX socket ====<br />
<br />
Run QEMU with the {{ic|-monitor unix:''socketfile'',server,nowait}} parameter. Then you can connect with either {{pkg|socat}} or {{pkg|openbsd-netcat}}.<br />
<br />
For example, if QEMU is run via:<br />
<br />
$ qemu-system-x86_64 ''[...]'' -monitor unix:/tmp/monitor.sock,server,nowait ''[...]''<br />
<br />
It is possible to connect to the monitor with:<br />
<br />
$ socat - UNIX-CONNECT:/tmp/monitor.sock<br />
<br />
Or with:<br />
<br />
$ nc -U /tmp/monitor.sock<br />
<br />
==== TCP ====<br />
<br />
You can expose the monitor over TCP with the argument {{ic|-monitor tcp:127.0.0.1:''port'',server,nowait}}. Then connect with netcat, either {{pkg|openbsd-netcat}} or {{pkg|gnu-netcat}} by running:<br />
<br />
$ nc 127.0.0.1 ''port''<br />
<br />
{{Note|In order to be able to connect to the tcp socket from other devices other than the same host QEMU is being run on you need to listen to {{ic|0.0.0.0}} like explained in the telnet case. The same security warnings apply in this case as well.}}<br />
<br />
==== Standard I/O ====<br />
<br />
It is possible to access the monitor automatically from the same terminal QEMU is being run by running it with the argument {{ic|-monitor stdio}}.<br />
<br />
=== Sending keyboard presses to the virtual machine using the monitor console ===<br />
<br />
Some combinations of keys may be difficult to perform on virtual machines due to the host intercepting them instead in some configurations (a notable example is the {{ic|Ctrl+Alt+F*}} key combinations, which change the active tty). To avoid this problem, the problematic combination of keys may be sent via the monitor console instead. Switch to the monitor and use the {{ic|sendkey}} command to forward the necessary keypresses to the virtual machine. For example:<br />
<br />
(qemu) sendkey ctrl-alt-f2<br />
<br />
=== Creating and managing snapshots via the monitor console ===<br />
<br />
{{Note|This feature will '''only''' work when the virtual machine disk image is in ''qcow2'' format. It will not work with ''raw'' images.}}<br />
<br />
It is sometimes desirable to save the current state of a virtual machine and having the possibility of reverting the state of the virtual machine to that of a previously saved snapshot at any time. The QEMU monitor console provides the user with the necessary utilities to create snapshots, manage them, and revert the machine state to a saved snapshot.<br />
<br />
* Use {{ic|savevm ''name''}} in order to create a snapshot with the tag ''name''.<br />
* Use {{ic|loadvm ''name''}} to revert the virtual machine to the state of the snapshot ''name''.<br />
* Use {{ic|delvm ''name''}} to delete the snapshot tagged as ''name''.<br />
* Use {{ic|info snapshots}} to see a list of saved snapshots. Snapshots are identified by both an auto-incremented ID number and a text tag (set by the user on snapshot creation).<br />
<br />
=== Running the virtual machine in immutable mode ===<br />
<br />
It is possible to run a virtual machine in a frozen state so that all changes will be discarded when the virtual machine is powered off just by running QEMU with the {{ic|-snapshot}} parameter. When the disk image is written by the guest, changes will be saved in a temporary file in {{ic|/tmp}} and will be discarded when QEMU halts.<br />
<br />
However, if a machine is running in frozen mode it is still possible to save the changes to the disk image if it is afterwards desired by using the monitor console and running the following command:<br />
<br />
(qemu) commit all<br />
<br />
If snapshots are created when running in frozen mode they will be discarded as soon as QEMU is exited unless changes are explicitly commited to disk, as well.<br />
<br />
=== Pause and power options via the monitor console ===<br />
<br />
Some operations of a physical machine can be emulated by QEMU using some monitor commands:<br />
<br />
* {{ic|system_powerdown}} will send an ACPI shutdown request to the virtual machine. This effect is similar to the power button in a physical machine.<br />
* {{ic|system_reset}} will reset the virtual machine similarly to a reset button in a physical machine. This operation can cause data loss and file system corruption since the virtual machine is not cleanly restarted.<br />
* {{ic|stop}} will pause the virtual machine.<br />
* {{ic|cont}} will resume a virtual machine previously paused.<br />
<br />
=== Taking screenshots of the virtual machine ===<br />
<br />
Screenshots of the virtual machine graphic display can be obtained in the PPM format by running the following command in the monitor console:<br />
<br />
(qemu) screendump ''file.ppm''<br />
<br />
== QEMU machine protocol ==<br />
<br />
The QEMU machine protocol (QMP) is a JSON-based protocol which allows applications to control a QEMU instance. Similarly to the [[#QEMU monitor]] it offers ways to interact with a running machine and the JSON protocol allows to do it programmatically. The description of all the QMP commands can be found in [https://raw.githubusercontent.com/coreos/qemu/master/qmp-commands.hx qmp-commands].<br />
<br />
=== Start QMP ===<br />
<br />
The usual way to control the guest using the QMP protocol, is to open a TCP socket when launching the machine using the {{ic|-qmp}} option. Here it is using for example the TCP port 4444:<br />
<br />
$ qemu-system-x86_64 ''[...]'' -qmp tcp:localhost:4444,server,nowait<br />
<br />
Then one way to communicate with the QMP agent is to use [[netcat]]:<br />
<br />
{{hc|nc localhost 4444|{"QMP": {"version": {"qemu": {"micro": 0, "minor": 1, "major": 3}, "package": ""}, "capabilities": []} } }}<br />
<br />
At this stage, the only command that can be recognized is {{ic|qmp_capabilities}}, so that QMP enters into command mode. Type:<br />
<br />
{"execute": "qmp_capabilities"}<br />
<br />
Now, QMP is ready to receive commands, to retrieve the list of recognized commands, use:<br />
<br />
{"execute": "query-commands"}<br />
<br />
=== Live merging of child image into parent image ===<br />
<br />
It is possible to merge a running snapshot into its parent by issuing a {{ic|block-commit}} command. In its simplest form the following line will commit the child into its parent:<br />
<br />
{"execute": "block-commit", "arguments": {"device": "''devicename''"}}<br />
<br />
Upon reception of this command, the handler looks for the base image and converts it from read only to read write mode and then runs the commit job.<br />
<br />
Once the ''block-commit'' operation has completed, the event {{ic|BLOCK_JOB_READY}} will be emitted, signalling that the synchronization has finished. The job can then be gracefully completed by issuing the command {{ic|block-job-complete}}:<br />
<br />
{"execute": "block-job-complete", "arguments": {"device": "''devicename''"}}<br />
<br />
Until such a command is issued, the ''commit'' operation remains active.<br />
After successful completion, the base image remains in read write mode and becomes the new active layer. On the other hand, the child image becomes invalid and it is the responsibility of the user to clean it up.<br />
<br />
{{Tip|The list of device and their names can be retrieved by executing the command {{ic|query-block}} and parsing the results. The device name is in the {{ic|device}} field, for example {{ic|ide0-hd0}} for the hard disk in this example: {{hc|{"execute": "query-block"}|{"return": [{"io-status": "ok", "device": "'''ide0-hd0'''", "locked": false, "removable": false, "inserted": {"iops_rd": 0, "detect_zeroes": "off", "image": {"backing-image": {"virtual-size": 27074281472, "filename": "parent.qcow2", ... } }} }}<br />
<br />
=== Live creation of a new snapshot ===<br />
<br />
To create a new snapshot out of a running image, run the command:<br />
<br />
{"execute": "blockdev-snapshot-sync", "arguments": {"device": "''devicename''","snapshot-file": "''new_snapshot_name''.qcow2"}}<br />
<br />
This creates an overlay file named {{ic|''new_snapshot_name''.qcow2}} which then becomes the new active layer.<br />
<br />
== Tips and tricks ==<br />
=== Improve virtual machine performance ===<br />
<br />
There are a number of techniques that you can use to improve the performance of the virtual machine. For example:<br />
<br />
* Apply [[#Enabling KVM]]: add {{ic|-enable-kvm}} to the QEMU start command you use.<br />
* Use the {{ic|-cpu host}} option to make QEMU emulate the host's exact CPU. If you do not do this, it may be trying to emulate a more generic CPU.<br />
* Especially for Windows guests, enable [http://blog.wikichoon.com/2014/07/enabling-hyper-v-enlightenments-with-kvm.html Hyper-V enlightenments]: {{ic|1=-cpu host,hv_relaxed,hv_spinlocks=0x1fff,hv_vapic,hv_time}}.<br />
* If the host machine has multiple cores, assign the guest more cores using the {{ic|-smp}} option.<br />
* Make sure you have assigned the virtual machine enough memory. By default, QEMU only assigns 128 MiB of memory to each virtual machine. Use the {{ic|-m}} option to assign more memory. For example, {{ic|-m 1024}} runs a virtual machine with 1024 MiB of memory.<br />
* If supported by drivers in the guest operating system, use [http://wiki.libvirt.org/page/Virtio virtio] for network and/or block devices. For example:<br />
$ qemu-system-x86_64 -net nic,model=virtio -net tap,if=tap0,script=no -drive file=''disk_image'',media=disk,if=virtio<br />
* Use TAP devices instead of user-mode networking. See [[#Tap networking with QEMU]].<br />
* If the guest OS is doing heavy writing to its disk, you may benefit from certain mount options on the host's file system. For example, you can mount an [[Ext4|ext4 file system]] with the option {{ic|1=barrier=0}}. You should read the documentation for any options that you change because sometimes performance-enhancing options for file systems come at the cost of data integrity.<br />
* If you have a raw disk image, you may want to disable the cache:<br />
$ qemu-system-x86_64 -drive file=''disk_image'',if=virtio,'''cache=none'''<br />
* Use the native Linux AIO:<br />
$ qemu-system-x86_64 -drive file=''disk_image'',if=virtio''',aio=native,cache.direct=on'''<br />
* If you are running multiple virtual machines concurrently that all have the same operating system installed, you can save memory by enabling [[wikipedia:Kernel_SamePage_Merging_(KSM)|kernel same-page merging]]. See [[#Enabling KSM]].<br />
* In some cases, memory can be reclaimed from running virtual machines by running a memory ballooning driver in the guest operating system and launching QEMU using {{ic|-device virtio-balloon}}.<br />
* It is possible to use a emulation layer for an ICH-9 AHCI controller (although it may be unstable). The AHCI emulation supports [[Wikipedia:Native_Command_Queuing|NCQ]], so multiple read or write requests can be outstanding at the same time:<br />
$ qemu-system-x86_64 -drive id=disk,file=''disk_image'',if=none -device ich9-ahci,id=ahci -device ide-drive,drive=disk,bus=ahci.0<br />
<br />
See http://www.linux-kvm.org/page/Tuning_KVM for more information.<br />
<br />
=== Starting QEMU virtual machines on boot ===<br />
<br />
==== With libvirt ====<br />
<br />
If a virtual machine is set up with [[libvirt]], it can be configured with {{ic|virsh autostart}} or through the ''virt-manager'' GUI to start at host boot by going to the Boot Options for the virtual machine and selecting "Start virtual machine on host boot up".<br />
<br />
==== With systemd service ====<br />
<br />
To run QEMU VMs on boot, you can use following systemd unit and config.<br />
<br />
{{hc|/etc/systemd/system/qemu@.service|2=<br />
[Unit]<br />
Description=QEMU virtual machine<br />
<br />
[Service]<br />
Environment="haltcmd=kill -INT $MAINPID"<br />
EnvironmentFile=/etc/conf.d/qemu.d/%i<br />
ExecStart=/usr/bin/qemu-system-x86_64 -name %i -enable-kvm -m 512 -nographic $args<br />
ExecStop=/usr/bin/bash -c ${haltcmd}<br />
ExecStop=/usr/bin/bash -c 'while nc localhost 7100; do sleep 1; done'<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
}}<br />
<br />
{{Note|This service will wait for the console port to be released, which means that the VM has been shutdown, to graciously end.}}<br />
<br />
Then create per-VM configuration files, named {{ic|/etc/conf.d/qemu.d/''vm_name''}}, with the variables {{ic|args}} and {{ic|haltcmd}} set. Example configs:<br />
<br />
{{hc|/etc/conf.d/qemu.d/one|2=<br />
args="-hda /dev/vg0/vm1 -serial telnet:localhost:7000,server,nowait,nodelay \<br />
-monitor telnet:localhost:7100,server,nowait,nodelay -vnc :0"<br />
<br />
haltcmd="echo 'system_powerdown' {{!}} nc localhost 7100" # or netcat/ncat}}<br />
<br />
{{hc|/etc/conf.d/qemu.d/two|2=<br />
args="-hda /srv/kvm/vm2 -serial telnet:localhost:7001,server,nowait,nodelay -vnc :1"<br />
<br />
haltcmd="ssh powermanager@vm2 sudo poweroff"}}<br />
<br />
The description of the variables is the following:<br />
<br />
* {{ic|args}} - QEMU command line arguments to be used.<br />
* {{ic|haltcmd}} - Command to shut down a VM safely. In the first example, the QEMU monitor is exposed via telnet using {{ic|-monitor telnet:..}} and the VMs are powered off via ACPI by sending {{ic|system_powerdown}} to monitor with the {{ic|nc}} command. In the other example, SSH is used.<br />
<br />
To set which virtual machines will start on boot-up, [[enable]] the {{ic|qemu@''vm_name''.service}} systemd unit.<br />
<br />
=== Mouse integration ===<br />
<br />
To prevent the mouse from being grabbed when clicking on the guest operating system's window, add the options {{ic|-usb -device usb-tablet}}. This means QEMU is able to report the mouse position without having to grab the mouse. This also overrides PS/2 mouse emulation when activated. For example:<br />
<br />
$ qemu-system-x86_64 -hda ''disk_image'' -m 512 -usb -device usb-tablet<br />
<br />
If that does not work, try using {{ic|-vga qxl}} parameter, also look at the instructions [[#Mouse cursor is jittery or erratic]].<br />
<br />
=== Pass-through host USB device ===<br />
<br />
It is possible to access the physical device connected to a USB port of the host from the guest. The first step is to identify where the device is connected, this can be found running the {{ic|lsusb}} command. For example:<br />
<br />
{{hc|$ lsusb|<br />
...<br />
Bus '''003''' Device '''007''': ID '''0781''':'''5406''' SanDisk Corp. Cruzer Micro U3<br />
}}<br />
<br />
The outputs in bold above will be useful to identify respectively the ''host_bus'' and ''host_addr'' or the ''vendor_id'' and ''product_id''.<br />
<br />
In qemu, the idea is to emulate an EHCI (USB 2) or XHCI (USB 3) controller with the option {{ic|1=-device usb-ehci,id=ehci}} or {{ic|1=-device qemu-xhci,id=xhci}} respectively and then attach the physical device to it with the option {{ic|1=-device usb-host,..}}. We will consider that ''controller_id'' is either {{ic|ehci}} or {{ic|xhci}} for the rest of this section.<br />
<br />
Then, there are two ways to connect to the USB of the host with qemu:<br />
<br />
# Identify the device and connect to it on any bus and address it is attached to on the host, the generic syntax is: {{bc|1=-device usb-host,bus=''controller_id''.0,vendorid=0x''vendor_id'',productid=0x''product_id''}}Applied to the device used in the example above, it becomes:{{bc|1=-device usb-ehci,id=ehci -device usb-host,bus=ehci.0,vendorid=0x'''0781''',productid=0x'''5406'''}}One can also add the {{ic|1=...,port=''port_number''}} setting to the previous option to specify in which physical port of the virtual controller the device should be attached, useful in the case one wants to add multiple usb devices to the VM. Another option is to use the new {{ic|usb-host}} {{ic|hostdevice}} property which is available since QEMU 5.1.0, the syntax is: {{bc|1=-device qemu-xhci,id=xhci -device usb-host,bus=xhci.0,hostdevice=/dev/bus/usb/003/007}}<br />
# Attach whatever is connected to a given USB bus and address, the syntax is:{{bc|1=-device usb-host,bus=''controller_id''.0,hostbus=''host_bus'',host_addr=''host_addr''}}Applied to the bus and the address in the example above, it becomes:{{bc|1=-device usb-ehci,id=ehci -device usb-host,bus=ehci.0,hostbus='''3''',hostaddr='''7'''}}<br />
<br />
{{Note|If you encounter permission errors when running QEMU, see [[udev#About udev rules]] for information on how to set permissions of the device.}}<br />
<br />
=== USB redirection with SPICE ===<br />
<br />
When using [[#SPICE]] it is possible to redirect USB devices from the client to the virtual machine without needing to specify them in the QEMU command. It is possible to configure the number of USB slots available for redirected devices (the number of slots will determine the maximum number of devices which can be redirected simultaneously). The main advantages of using SPICE for redirection compared to the previously-mentioned {{ic|-usbdevice}} method is the possibility of hot-swapping USB devices after the virtual machine has started, without needing to halt it in order to remove USB devices from the redirection or adding new ones. This method of USB redirection also allows us to redirect USB devices over the network, from the client to the server. In summary, it is the most flexible method of using USB devices in a QEMU virtual machine.<br />
<br />
We need to add one EHCI/UHCI controller per available USB redirection slot desired as well as one SPICE redirection channel per slot. For example, adding the following arguments to the QEMU command you use for starting the virtual machine in SPICE mode will start the virtual machine with three available USB slots for redirection:<br />
<br />
{{bc|1=-device ich9-usb-ehci1,id=usb \<br />
-device ich9-usb-uhci1,masterbus=usb.0,firstport=0,multifunction=on \<br />
-device ich9-usb-uhci2,masterbus=usb.0,firstport=2 \<br />
-device ich9-usb-uhci3,masterbus=usb.0,firstport=4 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev1 -device usb-redir,chardev=usbredirchardev1,id=usbredirdev1 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev2 -device usb-redir,chardev=usbredirchardev2,id=usbredirdev2 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev3 -device usb-redir,chardev=usbredirchardev3,id=usbredirdev3}}<br />
See [https://www.spice-space.org/usbredir.html SPICE/usbredir] for more information.<br />
<br />
Both {{ic|spicy}} from {{Pkg|spice-gtk}} (''Input > Select USB Devices for redirection'') and {{ic|remote-viewer}} from {{pkg|virt-viewer}} (''File > USB device selection'') support this feature. Please make sure that you have installed the necessary SPICE Guest Tools on the virtual machine for this functionality to work as expected (see the [[#SPICE]] section for more information).<br />
<br />
{{Warning|Keep in mind that when a USB device is redirected from the client, it will not be usable from the client operating system itself until the redirection is stopped. It is specially important to never redirect the input devices (namely mouse and keyboard), since it will be then difficult to access the SPICE client menus to revert the situation, because the client will not respond to the input devices after being redirected to the virtual machine.}}<br />
<br />
=== Enabling KSM ===<br />
<br />
Kernel Samepage Merging (KSM) is a feature of the Linux kernel that allows for an application to register with the kernel to have its pages merged with other processes that also register to have their pages merged. The KSM mechanism allows for guest virtual machines to share pages with each other. In an environment where many of the guest operating systems are similar, this can result in significant memory savings.<br />
<br />
{{Note|Although KSM may reduce memory usage, it may increase CPU usage. Also note some security issues may occur, see [[Wikipedia:Kernel same-page merging]].}}<br />
<br />
To enable KSM:<br />
<br />
# echo 1 > /sys/kernel/mm/ksm/run<br />
<br />
To make it permanent, use [[systemd#systemd-tmpfiles - temporary files|systemd's temporary files]]:<br />
<br />
{{hc|/etc/tmpfiles.d/ksm.conf|<br />
w /sys/kernel/mm/ksm/run - - - - 1<br />
}}<br />
<br />
If KSM is running, and there are pages to be merged (i.e. at least two similar VMs are running), then {{ic|/sys/kernel/mm/ksm/pages_shared}} should be non-zero. See https://www.kernel.org/doc/html/latest/admin-guide/mm/ksm.html for more information.<br />
<br />
{{Tip|An easy way to see how well KSM is performing is to simply print the contents of all the files in that directory: {{bc|$ grep . /sys/kernel/mm/ksm/*}}}}<br />
<br />
=== Multi-monitor support ===<br />
<br />
The Linux QXL driver supports four heads (virtual screens) by default. This can be changed via the {{ic|1=qxl.heads=N}} kernel parameter.<br />
<br />
The default VGA memory size for QXL devices is 16M (VRAM size is 64M). This is not sufficient if you would like to enable two 1920x1200 monitors since that requires 2 × 1920 × 4 (color depth) × 1200 = 17.6 MiB VGA memory. This can be changed by replacing {{ic|-vga qxl}} by {{ic|<nowiki>-vga none -device qxl-vga,vgamem_mb=32</nowiki>}}. If you ever increase vgamem_mb beyond 64M, then you also have to increase the {{ic|vram_size_mb}} option.<br />
<br />
=== Copy and paste ===<br />
<br />
One way to share the clipboard between the host and the guest is to enable the SPICE remote desktop protocol and access the client with a SPICE client.<br />
One needs to follow the steps described in [[#SPICE]]. A guest run this way will support copy paste with the host.<br />
<br />
=== Windows-specific notes ===<br />
<br />
QEMU can run any version of Windows from Windows 95 through Windows 10.<br />
<br />
It is possible to run [[Windows PE]] in QEMU.<br />
<br />
==== Fast startup ====<br />
<br />
{{Note|An administrator account is required to change power settings.}}<br />
<br />
For Windows 8 (or later) guests it is better to disable "Turn on fast startup (recommended)" from the Power Options of the Control Panel as explained in the following [https://www.tenforums.com/tutorials/4189-turn-off-fast-startup-windows-10-a.html forum page], as it causes the guest to hang during every other boot.<br />
<br />
Fast Startup may also need to be disabled for changes to the {{ic|-smp}} option to be properly applied.<br />
<br />
==== Remote Desktop Protocol ====<br />
<br />
If you use a MS Windows guest, you might want to use RDP to connect to your guest VM. If you are using a VLAN or are not in the same network as the guest, use:<br />
<br />
$ qemu-system-x86_64 -nographic -net user,hostfwd=tcp::5555-:3389<br />
<br />
Then connect with either {{Pkg|rdesktop}} or {{Pkg|freerdp}} to the guest. For example:<br />
<br />
$ xfreerdp -g 2048x1152 localhost:5555 -z -x lan<br />
<br />
=== Clone Linux system installed on physical equipment ===<br />
<br />
Linux system installed on physical equipment can be cloned for running on QEMU vm. See [https://coffeebirthday.wordpress.com/2018/09/14/clone-linux-system-for-qemu-virtual-machine/ Clone Linux system from hardware for QEMU virtual machine]<br />
<br />
=== Chrooting into arm/arm64 environment from x86_64 ===<br />
<br />
Sometimes it is easier to work directly on a disk image instead of the real ARM based device. This can be achieved by mounting an SD card/storage containing the ''root'' partition and chrooting into it.<br />
<br />
Another use case for an ARM chroot is building ARM packages on an x86_64 machine - {{AUR|armutils-git}} can be used for that. Here, the chroot environment can be created from an image tarball from [https://archlinuxarm.org Arch Linux ARM] - see [https://nerdstuff.org/posts/2020/2020-003_simplest_way_to_create_an_arm_chroot/] for a detailed description of this approach.<br />
<br />
Either way, from the chroot it should be possible to run ''pacman'' and install more packages, compile large libraries etc. Since the executables are for the ARM architecture, the translation to x86 needs to be performed by [[QEMU]].<br />
<br />
Install {{AUR|binfmt-qemu-static}} and {{AUR|qemu-user-static}} from the [[AUR]] on the x86_64 machine/host. ''binfmt-qemu-static'' will take care of registering the qemu binaries to binfmt service.<br />
<br />
[[Restart]] {{ic|systemd-binfmt.service}}<br />
<br />
{{AUR|qemu-user-static}} is needed to allow the execution of compiled programs from other architectures. This is similar to what is provided by {{Pkg|qemu-arch-extra}}, but the "static" variant is required for chroot. Examples:<br />
<br />
qemu-arm-static path_to_sdcard/usr/bin/ls<br />
qemu-aarch64-static path_to_sdcard/usr/bin/ls<br />
<br />
These two lines execute the {{ic|ls}} command compiled for 32-bit ARM and 64-bit ARM respectively. Note that this will not work without chrooting, because it will look for libraries not present in the host system.<br />
<br />
{{AUR|qemu-user-static}} allows automatically prefixing the ARM exectuable with {{ic|qemu-arm-static}} or {{ic|qemu-aarch64-static}}.<br />
<br />
Make sure that the ARM executable support is active:<br />
<br />
{{hc|$ ls /proc/sys/fs/binfmt_misc|<br />
qemu-aarch64 qemu-arm qemu-cris qemu-microblaze qemu-mipsel qemu-ppc64 qemu-riscv64 qemu-sh4 qemu-sparc qemu-sparc64 status<br />
qemu-alpha qemu-armeb qemu-m68k qemu-mips qemu-ppc qemu-ppc64abi32 qemu-s390x qemu-sh4eb qemu-sparc32plus register<br />
}}<br />
<br />
Each executable must be listed.<br />
<br />
If it is not active, reinstall ''binfmt-qemu-static'' and restart ''systemd-binfmt''.<br />
<br />
Mount the SD card to {{ic|/mnt/scdard}} (the device name may be different).<br />
<br />
# mkdir -p /mnt/sdcard<br />
# mount /dev/mmcblk0p2 /mnt/sdcard<br />
<br />
Mount boot partition if needed (again, use the suitable device name):<br />
<br />
# mount /dev/mmcblk0p1 /mnt/sdcard/boot<br />
<br />
Finally ''chroot'' into the SD card root as described in [[Change root#Using chroot]]:<br />
<br />
# chroot /mnt/sdcard /bin/bash<br />
<br />
Alternatively, you can use ''arch-chroot'' from {{Pkg|arch-install-scripts}}, as it will provide an easier way to get network support:<br />
# arch-chroot /mnt/sdcard /bin/bash<br />
<br />
You can also use ''systemd-nspawn'' to chroot into the ARM environment:<br />
# systemd-nspawn -D /mnt/sdcard -M myARMMachine --bind-ro=/etc/resolv.conf<br />
<br />
{{ic|1=--bind-ro=/etc/resolv.conf}} is optional and gives a working network DNS inside the chroot<br />
<br />
== Troubleshooting ==<br />
<br />
=== Mouse cursor is jittery or erratic ===<br />
<br />
If the cursor jumps around the screen uncontrollably, entering this on the terminal before starting QEMU might help:<br />
<br />
$ export SDL_VIDEO_X11_DGAMOUSE=0<br />
<br />
If this helps, you can add this to your {{ic|~/.bashrc}} file.<br />
<br />
=== No visible Cursor ===<br />
<br />
Add {{ic|-show-cursor}} to QEMU's options to see a mouse cursor.<br />
<br />
If that still does not work, make sure you have set your display device appropriately, for example: {{ic|-vga qxl}}.<br />
<br />
Another option to try is {{ic|-usb -device usb-tablet}} as mentioned in [[#Mouse integration]]. This overrides the default PS/2 mouse emulation and synchronizes pointer location between host and guest as an added bonus.<br />
<br />
=== Two different mouse cursors are visible ===<br />
<br />
Apply the tip [[#Mouse integration]].<br />
<br />
=== Keyboard issues when using VNC ===<br />
<br />
When using VNC, you might experience keyboard problems described (in gory details) [https://www.berrange.com/posts/2010/07/04/more-than-you-or-i-ever-wanted-to-know-about-virtual-keyboard-handling/ here]. The solution is ''not'' to use the {{ic|-k}} option on QEMU, and to use {{ic|gvncviewer}} from {{Pkg|gtk-vnc}}. See also [http://www.mail-archive.com/libvir-list@redhat.com/msg13340.html this] message posted on libvirt's mailing list.<br />
<br />
=== Keyboard seems broken or the arrow keys do not work ===<br />
<br />
Should you find that some of your keys do not work or "press" the wrong key (in particular, the arrow keys), you likely need to specify your keyboard layout as an option. The keyboard layouts can be found in {{ic|/usr/share/qemu/keymaps}}.<br />
<br />
$ qemu-system-x86_64 -k ''keymap'' ''disk_image''<br />
<br />
=== Guest display stretches on window resize ===<br />
<br />
To restore default window size, press {{ic|Ctrl+Alt+u}}.<br />
<br />
=== ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy ===<br />
<br />
If an error message like this is printed when starting QEMU with {{ic|-enable-kvm}} option:<br />
<br />
ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy<br />
failed to initialize KVM: Device or resource busy<br />
<br />
that means another [[hypervisor]] is currently running. It is not recommended or possible to run several hypervisors in parallel.<br />
<br />
=== libgfapi error message ===<br />
<br />
The error message displayed at startup:<br />
<br />
Failed to open module: libgfapi.so.0: cannot open shared object file: No such file or directory<br />
<br />
[[Install]] {{pkg|glusterfs}} or ignore the error message as GlusterFS is a optional dependency.<br />
<br />
=== Kernel panic on LIVE-environments===<br />
<br />
If you start a live-environment (or better: booting a system) you may encounter this:<br />
<br />
[ end Kernel panic - not syncing: VFS: Unable to mount root fs on unknown block(0,0)<br />
<br />
or some other boot hindering process (e.g. cannot unpack initramfs, cant start service foo).<br />
Try starting the VM with the {{ic|-m VALUE}} switch and an appropriate amount of RAM, if the ram is to low you will probably encounter similar issues as above/without the memory-switch.<br />
<br />
=== Windows 7 guest suffers low-quality sound ===<br />
<br />
Using the {{ic|hda}} audio driver for Windows 7 guest may result in low-quality sound. Changing the audio driver to {{ic|ac97}} by passing the {{ic|-soundhw ac97}} arguments to QEMU and installing the AC97 driver from [https://www.realtek.com/en/component/zoo/category/pc-audio-codecs-ac-97-audio-codecs-software Realtek AC'97 Audio Codecs] in the guest may solve the problem. See [https://bugzilla.redhat.com/show_bug.cgi?id=1176761#c16 Red Hat Bugzilla – Bug 1176761] for more information.<br />
<br />
=== Could not access KVM kernel module: Permission denied ===<br />
<br />
If you encounter the following error:<br />
<br />
libvirtError: internal error: process exited while connecting to monitor: Could not access KVM kernel module: Permission denied failed to initialize KVM: Permission denied<br />
<br />
Systemd 234 assigns a dynamic ID for the {{ic|kvm}} group (see {{Bug|54943}}). To avoid this error, you need edit the file {{ic|/etc/libvirt/qemu.conf}} and change the line with {{ic|1=group = "78"}} to {{ic|1=group = "kvm"}}.<br />
<br />
=== "System Thread Exception Not Handled" when booting a Windows VM ===<br />
<br />
Windows 8 or Windows 10 guests may raise a generic compatibility exception at boot, namely "System Thread Exception Not Handled", which tends to be caused by legacy drivers acting strangely on real machines. On KVM machines this issue can generally be solved by setting the CPU model to {{ic|core2duo}}.<br />
<br />
=== Certain Windows games/applications crashing/causing a bluescreen ===<br />
<br />
Occasionally, applications running in the VM may crash unexpectedly, whereas they would run normally on a physical machine. If, while running {{ic|dmesg -wH}}, you encounter an error mentioning {{ic|MSR}}, the reason for those crashes is that KVM injects a [[wikipedia:General protection fault|General protection fault]] (GPF) when the guest tries to access unsupported [[wikipedia:Model-specific register|Model-specific registers]] (MSRs) - this often results in guest applications/OS crashing. A number of those issues can be solved by passing the {{ic|1=ignore_msrs=1}} option to the KVM module, which will ignore unimplemented MSRs.<br />
<br />
{{hc|/etc/modprobe.d/kvm.conf|2=<br />
...<br />
options kvm ignore_msrs=1<br />
...<br />
}}<br />
<br />
Cases where adding this option might help:<br />
<br />
* GeForce Experience complaining about an unsupported CPU being present.<br />
* StarCraft 2 and L.A. Noire reliably blue-screening Windows 10 with {{ic|KMODE_EXCEPTION_NOT_HANDLED}}. The blue screen information does not identify a driver file in these cases.<br />
<br />
{{Warning|While this is normally safe and some applications might not work without this, silently ignoring unknown MSR accesses could potentially break other software within the VM or other VMs.}}<br />
<br />
=== Applications in the VM experience long delays or take a long time to start ===<br />
<br />
This may be caused by insufficient available entropy in the VM. Consider allowing the guest to access the hosts's entropy pool by adding a [https://wiki.qemu.org/Features/VirtIORNG VirtIO RNG device] to the VM, or by installing an entropy generating daemon such as [[Haveged]].<br />
<br />
Anecdotally, OpenSSH takes a while to start accepting connections under insufficient entropy, without the logs revealing why.<br />
<br />
=== High interrupt latency and microstuttering ===<br />
<br />
This problem manifests itself as small pauses (stutters) and is particularly noticeable in graphics-intensive applications, such as games.<br />
<br />
* One of the causes is CPU power saving features, which are controlled by [[CPU frequency scaling]]. Change this to {{ic|performance}} for all processor cores. <br />
* Another possible cause is PS/2 inputs. Switch from PS/2 to Virtio inputs, see [[PCI passthrough via OVMF#Passing keyboard/mouse via Evdev]].<br />
<br />
=== QXL video causes low resolution ===<br />
<br />
QEMU 4.1.0 introduced a regression where QXL video can fall back to low resolutions, when being displayed through spice. [https://bugs.launchpad.net/qemu/+bug/1843151] For example, when KMS starts, text resolution may become as low as 4x10 characters. When trying to increase GUI resolution, it may go to the lowest supported resolution.<br />
<br />
As a workaround, create your device in this form:<br />
<br />
-device qxl-vga,max_outputs=1...<br />
<br />
=== Hang during VM initramfs ===<br />
<br />
Linux 5.2.11 introduced a KVM regression where under some circumstances a VM may permanently hang during the early boot phase, when the initramfs is being loaded or ran. [https://www.spinics.net/lists/kvm/msg195171.html] Linux 5.3 fixed the regression. The host shows qemu using 100% CPU * number of virtual CPUs. Reported case is with a host using hyperthreading, and a VM being given more than host's {{ic|nproc}}/2 virtual CPUs. It is unknown what exact circumstances trigger one of the threads to delete a memory region to cause this. The workarounds are:<br />
<br />
* Upgrade to Linux 5.3.<br />
* Downgrade to Linux 5.2.10<br />
* Until fixed, try giving the VM no more than the host's {{ic|nproc}}/2 virtual CPUs<br />
* Custom compile linux, reverting commit 2ad350fb4c (note this re-introduces a regression triggered when removing a memslot)<br />
<br />
=== VM does not boot when using a Secure Boot enabled OVMF ===<br />
<br />
{{ic|/usr/share/edk2-ovmf/x64/OVMF_CODE.secboot.fd}} from {{Pkg|edk2-ovmf}} is built with [[Wikipedia:System Management Mode|SMM]] support. If S3 support is not disabled in the VM, then the VM might not boot at all.<br />
<br />
Add the {{ic|1=-global ICH9-LPC.disable_s3=1}} option to the ''qemu'' command.<br />
<br />
See {{Bug|59465}} and https://github.com/tianocore/edk2/blob/master/OvmfPkg/README for more details and the required options to use Secure Boot in QEMU.<br />
<br />
=== Guest CPU interrupts are not firing ===<br />
<br />
If you are writing your own operating system by following the [https://wiki.osdev.org/ OSDev wiki], or are simply getting stepping through the guest architecture assembly code using QEMU's {{ic|gdb}} interface using the {{ic|-s}} flag, it's useful to know that many emulators, QEMU included, usually implement some CPU interrupts leaving many hardware interrupts unimplemented. One way to know if your code if firing an interrupt, is by using:<br />
<br />
-d int<br />
<br />
to enable showing interrupts/exceptions on stdout.<br />
<br />
To see what other guest debugging features QEMU has to offer, see:<br />
<br />
qemu-system-x86_64 -d help<br />
<br />
or replace {{ic|x86_64}} for your chosen guest architecture.<br />
<br />
== See also ==<br />
<br />
* [http://qemu.org Official QEMU website]<br />
* [http://www.linux-kvm.org Official KVM website]<br />
* [http://qemu.weilnetz.de/qemu-doc.html QEMU Emulator User Documentation]<br />
* [[Wikibooks:QEMU|QEMU Wikibook]]<br />
* [http://alien.slackbook.org/dokuwiki/doku.php?id=slackware:qemu Hardware virtualization with QEMU] by AlienBOB (last updated in 2008)<br />
* [http://blog.falconindy.com/articles/build-a-virtual-army.html Building a Virtual Army] by Falconindy<br />
* [http://git.qemu.org/?p=qemu.git;a=tree;f=docs Lastest docs]<br />
* [http://qemu.weilnetz.de/ QEMU on Windows]<br />
* [[wikipedia:Qemu|Wikipedia]]<br />
* [[debian:QEMU|Debian Wiki - QEMU]]<br />
* [https://people.gnome.org/~markmc/qemu-networking.html QEMU Networking on gnome.org]<br />
* [http://bsdwiki.reedmedia.net/wiki/networking_qemu_virtual_bsd_systems.html Networking QEMU Virtual BSD Systems]<br />
* [https://www.gnu.org/software/hurd/hurd/running/qemu.html QEMU on gnu.org]<br />
* [https://wiki.freebsd.org/qemu QEMU on FreeBSD as host]<br />
* [https://wiki.mikejung.biz/KVM_/_Xen KVM/QEMU Virtio Tuning and SSD VM Optimization Guide]<br />
* [https://doc.opensuse.org/documentation/leap/virtualization/html/book-virt/part-virt-qemu.html Managing Virtual Machines with QEMU - openSUSE documentation]<br />
* [https://www.ibm.com/support/knowledgecenter/en/linuxonibm/liaat/liaatkvm.htm KVM on IBM Knowledge Center]</div>Malcontenthttps://wiki.archlinux.org/index.php?title=QEMU&diff=634803QEMU2020-09-09T14:33:11Z<p>Malcontent: I added an extra list before, the article mentions two options, so I am combining what I added to the existing list</p>
<hr />
<div>[[Category:Emulation]]<br />
[[Category:Hypervisors]]<br />
[[de:Qemu]]<br />
[[es:QEMU]]<br />
[[fr:Qemu]]<br />
[[ja:QEMU]]<br />
[[zh-hans:QEMU]]<br />
[[zh-hant:QEMU]]<br />
{{Related articles start}}<br />
{{Related|:Category:Hypervisors}}<br />
{{Related|Libvirt}}<br />
{{Related|QEMU/Guest graphics acceleration}}<br />
{{Related|PCI passthrough via OVMF}}<br />
{{Related articles end}}<br />
<br />
According to the [http://wiki.qemu.org/Main_Page QEMU about page], "QEMU is a generic and open source machine emulator and virtualizer."<br />
<br />
When used as a machine emulator, QEMU can run OSes and programs made for one machine (e.g. an ARM board) on a different machine (e.g. your x86 PC). By using dynamic translation, it achieves very good performance.<br />
<br />
QEMU can use other hypervisors like [[Xen]] or [[KVM]] to use CPU extensions ([[Wikipedia:Hardware-assisted virtualization|HVM]]) for virtualization. When used as a virtualizer, QEMU achieves near native performances by executing the guest code directly on the host CPU.<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|qemu}} package (or {{Pkg|qemu-headless}} for the version without GUI) and below optional packages for your needs:<br />
<br />
* {{Pkg|qemu-arch-extra}} - extra architectures support<br />
* {{Pkg|qemu-block-gluster}} - [[Glusterfs]] block support<br />
* {{Pkg|qemu-block-iscsi}} - [[iSCSI]] block support<br />
* {{Pkg|qemu-block-rbd}} - RBD block support <br />
* {{Pkg|samba}} - [[Samba|SMB/CIFS]] server support<br />
<br />
Alternatively, {{AUR|qemu-user-static}} exists as a usermode and static variant.<br />
<br />
=== QEMU variants ===<br />
<br />
QEMU is offered in several variants suited for different use cases.<br />
<br />
As a first classification, QEMU is offered in full-system and usermode emulation modes:<br />
<br />
; Full-system emulation<br />
: In this mode, QEMU emulates a full system, including one or several processors and various peripherals. It is more accurate but slower, and does not require the emulated OS to be Linux.<br />
: QEMU commands for full-system emulation are named {{ic|qemu-system-''target_architecture''}}, e.g. {{ic|qemu-system-x86_64}} for emulating intel 64-bit CPUs, {{ic|qemu-system-i386}} for intel 32 bits CPUs, {{ic|qemu-system-arm}} for ARM (32 bits), {{ic|qemu-system-aarch64}} for ARM64, etc.<br />
: If the target architecture matches the host CPU, this mode may still benefit from a significant speedup by using a hypervisor like [[#Enabling KVM|KVM]] or Xen.<br />
; [https://www.qemu.org/docs/master/user/main.html Usermode emulation]: In this mode, QEMU is able to invoke a Linux executable compiled for a (potentially) different architecture by leveraging the host system resources. There may be compatibility issues, e.g. some features may not be implemented, dynamically linked executables will not work out of the box (see [[#Chrooting into arm/arm64 environment from x86_64|the section below]] to address this) and only Linux is supported (although [https://wiki.winehq.org/Emulation Wine may be used] for running Windows executables).<br />
: QEMU commands for usermode emulation are named {{ic|qemu-''target_architecture''}}, e.g. {{ic|qemu-x86_64}} for emulating intel 64-bit CPUs.<br />
<br />
QEMU is offered in dynamically-linked and statically-linked variants:<br />
<br />
; Dynamically-linked (default): {{ic|qemu-*}} commands depend on the host OS libraries, so executables are smaller.<br />
; Statically-linked: {{ic|qemu-*}} commands can be copied to any Linux system with the same architecture.<br />
<br />
In the case of Arch Linux, full-system emulation is offered as:<br />
<br />
; Non-headless (default): This variant enables GUI features that require additional dependencies (like SDL or GTK).<br />
; Headless: This is a slimmer variant that does not require GUI (this is suitable e.g. for servers).<br />
<br />
Note that headless and non-headless versions install commands with the same name (e.g. {{ic|qemu-system-x86_64}}) and thus cannot be both installed at the same time.<br />
<br />
=== Details on packages offered in Arch Linux ===<br />
<br />
* The {{Pkg|qemu}} package provides the {{ic|x86_64}} architecture emulators for full-system emulation ({{ic|qemu-system-x86_64}}). The {{Pkg|qemu-arch-extra}} package provides the {{ic|x86_64}} usermode variant ({{ic|qemu-x86_64}}) and also for the rest of supported architectures it includes both full-system and usermode variants (e.g. {{ic|qemu-system-arm}} and {{ic|qemu-arm}}).<br />
* The headless versions of these packages (only applicable to full-system emulation) are {{Pkg|qemu-headless}} ({{ic|x86_64}}-only) and {{Pkg|qemu-headless-arch-extra}} (rest of architectures).<br />
* Full-system emulation can be expanded with some QEMU modules present in separate packages: {{Pkg|qemu-block-gluster}}, {{Pkg|qemu-block-iscsi}}, {{Pkg|qemu-block-rbd}} and {{Pkg|qemu-guest-agent}}.<br />
* The unofficial AUR package {{AUR|qemu-user-static}} provides a usermode and static variant for all target architectures supported by QEMU. A precompiled version of this package exists: {{AUR|qemu-user-static-bin}}. The installed QEMU commands are named {{ic|qemu-''target_architecture''-static}}, for example, {{ic|qemu-x86_64-static}} for intel 64-bit CPUs.<br />
<br />
{{Note|At present, Arch does not offer a full-system mode and statically linked variant (neither officially nor via AUR), as this is usually not needed.}}<br />
<br />
== Graphical front-ends for QEMU ==<br />
<br />
Unlike other virtualization programs such as [[VirtualBox]] and [[VMware]], QEMU does not provide a GUI to manage virtual machines (other than the window that appears when running a virtual machine), nor does it provide a way to create persistent virtual machines with saved settings. All parameters to run a virtual machine must be specified on the command line at every launch, unless you have created a custom script to start your virtual machine(s).<br />
<br />
[[Libvirt]] provides a convenient way to manage QEMU virtual machines. See [[Libvirt#Client|list of libvirt clients]] for available front-ends.<br />
<br />
Other GUI front-ends for QEMU:<br />
<br />
* {{App|AQEMU|QEMU GUI written in Qt5.|https://github.com/tobimensch/aqemu|{{AUR|aqemu}}}}<br />
<br />
== Creating new virtualized system ==<br />
<br />
=== Creating a hard disk image ===<br />
<br />
{{Accuracy|If I get the man page right the raw format only allocates the full size if the filesystem does not support "holes" or it is <br />
explicitly told to preallocate. See man qemu-img in section Notes.}} <br />
<br />
{{Tip|See [[Wikibooks:QEMU/Images]] for more information on QEMU images.}}<br />
<br />
To run QEMU you will need a hard disk image, unless you are booting a live system from CD-ROM or the network (and not doing so to install an operating system to a hard disk image). A hard disk image is a file which stores the contents of the emulated hard disk.<br />
<br />
A hard disk image can be ''raw'', so that it is literally byte-by-byte the same as what the guest sees, and will always use the full capacity of the guest hard drive on the host. This method provides the least I/O overhead, but can waste a lot of space, as not-used space on the guest cannot be used on the host.<br />
<br />
Alternatively, the hard disk image can be in a format such as ''qcow2'' which only allocates space to the image file when the guest operating system actually writes to those sectors on its virtual hard disk. The image appears as the full size to the guest operating system, even though it may take up only a very small amount of space on the host system. This image format also supports QEMU snapshotting functionality (see [[#Creating and managing snapshots via the monitor console]] for details). However, using this format instead of ''raw'' will likely affect performance.<br />
<br />
QEMU provides the {{ic|qemu-img}} command to create hard disk images. For example to create a 4 GB image in the ''raw'' format:<br />
<br />
$ qemu-img create -f raw ''image_file'' 4G<br />
<br />
You may use {{ic|-f qcow2}} to create a ''qcow2'' disk instead.<br />
<br />
{{Note|You can also simply create a ''raw'' image by creating a file of the needed size using {{ic|dd}} or {{ic|fallocate}}.}}<br />
<br />
{{Warning|If you store the hard disk images on a [[Btrfs]] file system, you should consider disabling [[Btrfs#Copy-on-Write (CoW)|Copy-on-Write]] for the directory before creating any images.}}<br />
<br />
==== Overlay storage images ====<br />
<br />
You can create a storage image once (the 'backing' image) and have QEMU keep mutations to this image in an overlay image. This allows you to revert to a previous state of this storage image. You could revert by creating a new overlay image at the time you wish to revert, based on the original backing image.<br />
<br />
To create an overlay image, issue a command like:<br />
<br />
$ qemu-img create -o backing_file=''img1.raw'',backing_fmt=''raw'' -f ''qcow2'' ''img1.cow''<br />
<br />
After that you can run your QEMU VM as usual (see [[#Running virtualized system]]):<br />
<br />
$ qemu-system-x86_64 ''img1.cow''<br />
<br />
The backing image will then be left intact and mutations to this storage will be recorded in the overlay image file.<br />
<br />
When the path to the backing image changes, repair is required.<br />
<br />
{{Warning|The backing image's absolute filesystem path is stored in the (binary) overlay image file. Changing the backing image's path requires some effort.}}<br />
<br />
Make sure that the original backing image's path still leads to this image. If necessary, make a symbolic link at the original path to the new path. Then issue a command like:<br />
<br />
$ qemu-img rebase -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
At your discretion, you may alternatively perform an 'unsafe' rebase where the old path to the backing image is not checked:<br />
<br />
$ qemu-img rebase -u -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
==== Resizing an image ====<br />
<br />
{{Warning|Resizing an image containing an NTFS boot file system could make the operating system installed on it unbootable. It is recommended to create a backup first.}}<br />
<br />
The {{ic|qemu-img}} executable has the {{ic|resize}} option, which enables easy resizing of a hard drive image. It works for both ''raw'' and ''qcow2''. For example, to increase image space by 10 GB, run:<br />
<br />
$ qemu-img resize ''disk_image'' +10G<br />
<br />
After enlarging the disk image, you must use file system and partitioning tools inside the virtual machine to actually begin using the new space. When shrinking a disk image, you must '''first reduce the allocated file systems and partition sizes''' using the file system and partitioning tools inside the virtual machine and then shrink the disk image accordingly, otherwise shrinking the disk image will result in data loss! For a Windows guest, open the "create and format hard disk partitions" control panel.<br />
<br />
==== Converting an image ====<br />
<br />
You can convert an image to other formats using {{ic|qemu-img convert}}. This example shows how to convert a ''raw'' image to ''qcow2'':<br />
<br />
$ qemu-img convert -f raw -O qcow2 ''input''.img ''output''.qcow2<br />
<br />
This will not remove the original input file.<br />
<br />
=== Preparing the installation media ===<br />
<br />
To install an operating system into your disk image, you need the installation medium (e.g. optical disk, USB-drive, or ISO image) for the operating system. The installation medium should not be mounted because QEMU accesses the media directly.<br />
<br />
{{Tip|If using an optical disk, it is a good idea to first dump the media to a file because this both improves performance and does not require you to have direct access to the devices (that is, you can run QEMU as a regular user without having to change access permissions on the media's device file). For example, if the CD-ROM device node is named {{ic|/dev/cdrom}}, you can dump it to a file with the command: {{bc|1=$ dd if=/dev/cdrom of=''cd_image.iso'' bs=4k}}}}<br />
<br />
=== Installing the operating system ===<br />
<br />
This is the first time you will need to start the emulator. To install the operating system on the disk image, you must attach both the disk image and the installation media to the virtual machine, and have it boot from the installation media.<br />
<br />
For example on i386 guests, to install from a bootable ISO file as CD-ROM and a raw disk image:<br />
<br />
$ qemu-system-x86_64 -cdrom ''iso_image'' -boot order=d -drive file=''disk_image'',format=raw<br />
<br />
See {{man|1|qemu}} for more information about loading other media types (such as floppy, disk images or physical drives) and [[#Running virtualized system]] for other useful options.<br />
<br />
After the operating system has finished installing, the QEMU image can be booted directly (see [[#Running virtualized system]]).<br />
<br />
{{Note|By default only 128 MB of memory is assigned to the machine. The amount of memory can be adjusted with the {{ic|-m}} switch, for example {{ic|-m 512M}} or {{ic|-m 2G}}.}}<br />
<br />
{{Tip|<br />
* Instead of specifying {{ic|1=-boot order=x}}, some users may feel more comfortable using a boot menu: {{ic|1=-boot menu=on}}, at least during configuration and experimentation.<br />
* When running QEMU in headless mode, it starts a local VNC server on port 5900 per default. You can use [[TigerVNC]] to connect to the guest OS: {{ic|vncviewer :5900}}<br />
* If you need to replace floppies or CDs as part of the installation process, you can use the QEMU machine monitor (press {{ic|Ctrl+Alt+2}} in the virtual machine's window) to remove and attach storage devices to a virtual machine. Type {{ic|info block}} to see the block devices, and use the {{ic|change}} command to swap out a device. Press {{ic|Ctrl+Alt+1}} to go back to the virtual machine.<br />
}}<br />
<br />
== Running virtualized system ==<br />
<br />
{{ic|qemu-system-*}} binaries (for example {{ic|qemu-system-i386}} or {{ic|qemu-system-x86_64}}, depending on guest's architecture) are used to run the virtualized guest. The usage is:<br />
<br />
$ qemu-system-x86_64 ''options'' ''disk_image''<br />
<br />
Options are the same for all {{ic|qemu-system-*}} binaries, see {{man|1|qemu}} for documentation of all options.<br />
<br />
By default, QEMU will show the virtual machine's video output in a window. One thing to keep in mind: when you click inside the QEMU window, the mouse pointer is grabbed. To release it, press {{ic|Ctrl+Alt+g}}.<br />
<br />
{{Warning|QEMU should never be run as root. If you must launch it in a script as root, you should use the {{ic|-runas}} option to make QEMU drop root privileges.}}<br />
<br />
=== Enabling KVM ===<br />
<br />
KVM (''Kernel-based Virtual Machine'') full virtualization must be supported by your Linux kernel and your hardware, and necessary [[kernel modules]] must be loaded. See [[KVM]] for more information.<br />
<br />
To start QEMU in KVM mode, append {{ic|-enable-kvm}} to the additional start options. To check if KVM is enabled for a running VM, enter the [[#QEMU monitor]] and type {{ic|info kvm}}.<br />
<br />
{{Note|<br />
* The argument {{ic|1=accel=kvm}} of the {{ic|-machine}} option is equivalent to the {{ic|-enable-kvm}} or the {{ic|-accel kvm}} option.<br />
* CPU model {{ic|host}} requires KVM<br />
* If you start your VM with a GUI tool and experience very bad performance, you should check for proper KVM support, as QEMU may be falling back to software emulation.<br />
* KVM needs to be enabled in order to start Windows 7 and Windows 8 properly without a ''blue screen''.<br />
}}<br />
<br />
=== Enabling IOMMU (Intel VT-d/AMD-Vi) support ===<br />
<br />
First enable IOMMU, see [[PCI passthrough via OVMF#Setting up IOMMU]].<br />
<br />
Add {{ic|-device intel-iommu}} to create the IOMMU device:<br />
<br />
$ qemu-system-x86_64 '''-enable-kvm -machine q35 -device intel-iommu''' -cpu host ..<br />
<br />
{{Note|<br />
On Intel CPU based systems creating an IOMMU device in a QEMU guest with {{ic|-device intel-iommu}} will disable PCI passthrough with an error like: {{bc|Device at bus pcie.0 addr 09.0 requires iommu notifier which is currently not supported by intel-iommu emulation}} While adding the kernel parameter {{ic|1=intel_iommu=on}} is still needed for remapping IO (e.g. [[PCI passthrough via OVMF#Isolating the GPU|PCI passthrough with vfio-pci]]), {{ic|-device intel-iommu}} should not be set if PCI PCI passthrough is required.<br />
}}<br />
<br />
== Sharing data between host and guest ==<br />
<br />
=== Network ===<br />
<br />
Data can be shared between the host and guest OS using any network protocol that can transfer files, such as [[NFS]], [[SMB]], [[Wikipedia:Network block device|NBD]], HTTP, [[Very Secure FTP Daemon|FTP]], or [[SSH]], provided that you have set up the network appropriately and enabled the appropriate services.<br />
<br />
The default user-mode networking allows the guest to access the host OS at the IP address 10.0.2.2. Any servers that you are running on your host OS, such as a SSH server or SMB server, will be accessible at this IP address. So on the guests, you can mount directories exported on the host via [[SMB]] or [[NFS]], or you can access the host's HTTP server, etc.<br />
It will not be possible for the host OS to access servers running on the guest OS, but this can be done with other network configurations (see [[#Tap networking with QEMU]]).<br />
<br />
=== QEMU's port forwarding ===<br />
<br />
QEMU can forward ports from the host to the guest to enable e.g. connecting from the host to an SSH server running on the guest.<br />
<br />
For example, to bind port 10022 on the host with port 22 (SSH) on the guest, start QEMU with a command like:<br />
<br />
$ qemu-system-x86_64 ''disk_image'' -nic user,hostfwd=tcp::10022-:22<br />
<br />
Make sure the sshd is running on the guest and connect with:<br />
<br />
$ ssh ''guest-user''@localhost -p 10022<br />
<br />
You can use [[SSHFS]] to mount the guest's file system at the host for shared read and write access.<br />
<br />
=== QEMU's built-in SMB server ===<br />
<br />
QEMU's documentation says it has a "built-in" SMB server, but actually it just starts up [[Samba]] on the host with an automatically generated {{ic|smb.conf}} file located in {{ic|/tmp/qemu-smb.''random_string''}} and makes it accessible to the guest at a different IP address (10.0.2.4 by default). This only works for user networking, and is useful when you do not want to start the normal [[Samba]] service on the host, which the guest can also access if you have set up shares on it.<br />
<br />
Only a single directory can be set as shared with the option {{ic|1=smb=}}, but adding more directories (even while the virtual machine is running) could be as easy as creating symbolic links in the shared directory if QEMU configured SMB to follow symbolic links. It does not do so, but the configuration of the running SMB server can be changed as described below.<br />
<br />
''Samba'' must be installed on the host. To enable this feature, start QEMU with a command like:<br />
<br />
$ qemu-system-x86_64 ''disk_image'' -net nic -net user,smb=''shared_dir_path''<br />
<br />
where {{ic|''shared_dir_path''}} is a directory that you want to share between the guest and host.<br />
<br />
Then, in the guest, you will be able to access the shared directory on the host 10.0.2.4 with the share name "qemu". For example, in Windows Explorer you would go to {{ic|\\10.0.2.4\qemu}}.<br />
<br />
{{Note|<br />
* If you are using sharing options multiple times like {{ic|1=-net user,smb=''shared_dir_path1'' -net user,smb=''shared_dir_path2''}} or {{ic|1=-net user,smb=''shared_dir_path1'',smb=''shared_dir_path2''}} then it will share only the last defined one.<br />
* If you cannot access the shared folder and the guest system is Windows, check that the [http://ecross.mvps.org/howto/enable-netbios-over-tcp-ip-with-windows.htm NetBIOS protocol is enabled] and that a firewall does not block [https://technet.microsoft.com/en-us/library/cc940063.aspx ports] used by the NetBIOS protocol.<br />
* If you cannot access the shared folder and the guest system is Windows 10 Enterprise or Education or Windows Server 2016, [https://support.microsoft.com/en-us/help/4046019 enable guest access].<br />
}}<br />
<br />
One way to share multiple directories and to add or remove them while the virtual machine is running, is to share an empty directory and create/remove symbolic links to the directories in the shared directory. For this to work, the configuration of the running SMB server can be changed with the following script, which also allows the execution of files on the guest that are not set executable on the host:<br />
<br />
#!/bin/bash<br />
eval $(ps h -C smbd -o pid,args | grep /tmp/qemu-smb | gawk '{print "pid="$1";conf="$6}')<br />
echo "[global]<br />
allow insecure wide links = yes<br />
[qemu]<br />
follow symlinks = yes<br />
wide links = yes<br />
acl allow execute always = yes" >> $conf<br />
# in case the change is not detected automatically:<br />
smbcontrol --configfile=$conf $pid reload-config<br />
<br />
This can be applied to the running server started by qemu only after the guest has connected to the network drive the first time. An alternative to this method is to add additional shares to the configuration file like so:<br />
<br />
echo "[''myshare'']<br />
path=''another_path''<br />
read only=no<br />
guest ok=yes<br />
force user=''username''" >> $conf<br />
<br />
This share will be available on the guest as {{ic|\\10.0.2.4\''myshare''}}.<br />
<br />
=== Using filesystem passthrough and VirtFS ===<br />
<br />
See the [https://wiki.qemu.org/Documentation/9psetup QEMU documentation].<br />
<br />
=== Mounting a partition of the guest on the host ===<br />
<br />
It can be useful to mount a drive image under the host system, it can be a way to transfer files in and out of the guest. This should be done when the virtual machine is not running.<br />
<br />
The procedure to mount the drive on the host depends on the type of qemu image, ''raw'' or ''qcow2''. We detail thereafter the steps to mount a drive in the two formats in [[#Mounting a partition from a raw image]] and [[#Mounting a partition from a qcow2 image]]. For the full documentation see [[Wikibooks:QEMU/Images#Mounting an image on the host]].<br />
<br />
{{Warning|You must make sure to unmount the partitions before running the virtual machine again. Otherwise, data corruption is very likely to occur.}}<br />
<br />
==== Mounting a partition from a raw image ====<br />
<br />
It is possible to mount partitions that are inside a raw disk image file by setting them up as loopback devices.<br />
<br />
===== With manually specifying byte offset =====<br />
<br />
One way to mount a disk image partition is to mount the disk image at a certain offset using a command like the following:<br />
<br />
# mount -o loop,offset=32256 ''disk_image'' ''mountpoint''<br />
<br />
The {{ic|1=offset=32256}} option is actually passed to the {{ic|losetup}} program to set up a loopback device that starts at byte offset 32256 of the file and continues to the end. This loopback device is then mounted. You may also use the {{ic|sizelimit}} option to specify the exact size of the partition, but this is usually unnecessary.<br />
<br />
Depending on your disk image, the needed partition may not start at offset 32256. Run {{ic|fdisk -l ''disk_image''}} to see the partitions in the image. fdisk gives the start and end offsets in 512-byte sectors, so multiply by 512 to get the correct offset to pass to {{ic|mount}}.<br />
<br />
===== With loop module autodetecting partitions =====<br />
<br />
The Linux loop driver actually supports partitions in loopback devices, but it is disabled by default. To enable it, do the following:<br />
<br />
* Get rid of all your loopback devices (unmount all mounted images, etc.).<br />
* [[Kernel_modules#Manual_module_handling|Unload]] the {{ic|loop}} kernel module, and load it with the {{ic|1=max_part=15}} parameter set. Additionally, the maximum number of loop devices can be controlled with the {{ic|max_loop}} parameter.<br />
<br />
{{Tip|You can put an entry in {{ic|/etc/modprobe.d}} to load the loop module with {{ic|1=max_part=15}} every time, or you can put {{ic|1=loop.max_part=15}} on the kernel command-line, depending on whether you have the {{ic|loop.ko}} module built into your kernel or not.}}<br />
<br />
Set up your image as a loopback device:<br />
<br />
# losetup -f -P ''disk_image''<br />
<br />
Then, if the device created was {{ic|/dev/loop0}}, additional devices {{ic|/dev/loop0pX}} will have been automatically created, where X is the number of the partition. These partition loopback devices can be mounted directly. For example:<br />
<br />
# mount /dev/loop0p1 ''mountpoint''<br />
<br />
To mount the disk image with ''udisksctl'', see [[Udisks#Mount loop devices]].<br />
<br />
===== With kpartx =====<br />
<br />
'''kpartx''' from the {{Pkg|multipath-tools}} package can read a partition table on a device and create a new device for each partition. For example:<br />
<br />
# kpartx -a ''disk_image''<br />
<br />
This will setup the loopback device and create the necessary partition(s) device(s) in {{ic|/dev/mapper/}}.<br />
<br />
==== Mounting a partition from a qcow2 image ====<br />
<br />
We will use {{ic|qemu-nbd}}, which lets use the NBD (''network block device'') protocol to share the disk image.<br />
<br />
First, we need the ''nbd'' module loaded:<br />
<br />
# modprobe nbd max_part=16<br />
<br />
Then, we can share the disk and create the device entries:<br />
<br />
# qemu-nbd -c /dev/nbd0 ''/path/to/image.qcow2''<br />
<br />
Discover the partitions:<br />
<br />
# partprobe /dev/nbd0<br />
<br />
''fdisk'' can be used to get information regarding the different partitions in {{{ic|''nbd0''}}:<br />
<br />
{{hc|# fdisk -l /dev/nbd0|2=<br />
Disk /dev/nbd0: 25.2 GiB, 27074281472 bytes, 52879456 sectors<br />
Units: sectors of 1 * 512 = 512 bytes<br />
Sector size (logical/physical): 512 bytes / 512 bytes<br />
I/O size (minimum/optimal): 512 bytes / 512 bytes<br />
Disklabel type: dos<br />
Disk identifier: 0xa6a4d542<br />
<br />
Device Boot Start End Sectors Size Id Type<br />
/dev/nbd0p1 * 2048 1026047 1024000 500M 7 HPFS/NTFS/exFAT<br />
/dev/nbd0p2 1026048 52877311 51851264 24.7G 7 HPFS/NTFS/exFAT}}<br />
<br />
Then mount any partition of the drive image, for example the partition 2:<br />
<br />
# mount /dev/nbd0'''p2''' ''mountpoint''<br />
<br />
After the usage, it is important to unmount the image and reverse previous steps, i.e. unmount the partition and disconnect the nbd device:<br />
<br />
# umount ''mountpoint''<br />
# qemu-nbd -d /dev/nbd0<br />
<br />
=== Using any real partition as the single primary partition of a hard disk image ===<br />
<br />
Sometimes, you may wish to use one of your system partitions from within QEMU. Using a raw partition for a virtual machine will improve performance, as the read and write operations do not go through the file system layer on the physical host. Such a partition also provides a way to share data between the host and guest.<br />
<br />
In Arch Linux, device files for raw partitions are, by default, owned by ''root'' and the ''disk'' group. If you would like to have a non-root user be able to read and write to a raw partition, you must either change the owner of the partition's device file to that user, add that user to the ''disk'' group, or use [[ACL]] for more fine-grained access control.<br />
<br />
{{Warning|<br />
* Although it is possible, it is not recommended to allow virtual machines to alter critical data on the host system, such as the root partition.<br />
* You must not mount a file system on a partition read-write on both the host and the guest at the same time. Otherwise, data corruption will result.<br />
}}<br />
<br />
After doing so, you can attach the partition to a QEMU virtual machine as a virtual disk.<br />
<br />
However, things are a little more complicated if you want to have the ''entire'' virtual machine contained in a partition. In that case, there would be no disk image file to actually boot the virtual machine since you cannot install a bootloader to a partition that is itself formatted as a file system and not as a partitioned device with an MBR. Such a virtual machine can be booted either by specifying the [[kernel]] and [[initrd]] manually, or by simulating a disk with an MBR by using the [https://www.kernel.org/doc/html/latest/admin-guide/device-mapper/index.html Device-mapper], linear [[RAID]], or a [https://www.kernel.org/doc/html/latest/admin-guide/blockdev/nbd.html Linux Network Block Device].<br />
<br />
==== By specifying kernel and initrd manually ====<br />
<br />
QEMU supports loading [[Kernels|Linux kernels]] and [[initramfs|init ramdisks]] directly, thereby circumventing bootloaders such as [[GRUB]]. It then can be launched with the physical partition containing the root file system as the virtual disk, which will not appear to be partitioned. This is done by issuing a command similar to the following:<br />
<br />
{{Note|In this example, it is the '''host's''' images that are being used, not the guest's. If you wish to use the guest's images, either mount {{ic|/dev/sda3}} read-only (to protect the file system from the host) and specify the {{ic|/full/path/to/images}} or use some kexec hackery in the guest to reload the guest's kernel (extends boot time). }}<br />
<br />
$ qemu-system-x86_64 -kernel /boot/vmlinuz-linux -initrd /boot/initramfs-linux.img -append root=/dev/sda /dev/sda3<br />
<br />
In the above example, the physical partition being used for the guest's root file system is {{ic|/dev/sda3}} on the host, but it shows up as {{ic|/dev/sda}} on the guest.<br />
<br />
You may, of course, specify any kernel and initrd that you want, and not just the ones that come with Arch Linux.<br />
<br />
When there are multiple [[kernel parameters]] to be passed to the {{ic|-append}} option, they need to be quoted using single or double quotes. For example:<br />
<br />
... -append 'root=/dev/sda1 console=ttyS0'<br />
<br />
==== Simulate a virtual disk with MBR ====<br />
<br />
A more complicated way to have a virtual machine use a physical partition, while keeping that partition formatted as a file system and not just having the guest partition the partition as if it were a disk, is to simulate an MBR for it so that it can boot using a bootloader such as GRUB.<br />
<br />
For the following, suppose you have a plain, unmounted {{ic|/dev/hda''N''}} partition with some file system on it you wish to make part of a QEMU disk image. The trick is to dynamically prepend a master boot record (MBR) to the real partition you wish to embed in a QEMU raw disk image. More generally, the partition can be any part of a larger simulated disk, in particular a block device that simulates the original physical disk but only exposes {{ic|/dev/hda''N''}} to the virtual machine.<br />
<br />
A virtual disk of this type can be represented by a VMDK file that contains references to (a copy of) the MBR and the partition, but QEMU does not support this VMDK format. For instance, a virtual disk [https://www.virtualbox.org/manual/ch09.html#rawdisk created by]<br />
<br />
$ VBoxManage internalcommands createrawvmdk -filename ''/path/to/file.vmdk'' -rawdisk /dev/hda<br />
<br />
will be rejected by QEMU with the error message<br />
<br />
Unsupported image type 'partitionedDevice'<br />
<br />
Note that {{ic|VBoxManage}} creates two files, {{ic|''file.vmdk''}} and {{ic|''file-pt.vmdk''}}, the latter being a copy of the MBR, to which the text file {{ic|file.vmdk}} points. Read operations outside the target partition or the MBR would give zeros, while written data would be discarded.<br />
<br />
===== Device Mapper =====<br />
<br />
A method that is similar to the use of a VMDK descriptor file uses the device mapper to prepend a loop device attached to the MBR file to the target partition. In case we do not need our virtual disk to have the same size as the original, we first create a file to hold the MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=2048<br />
<br />
Here, a 1 MB (2048 * 512 bytes) file is created in accordance with partition alignment policies used by modern disk partitioning tools. For compatibility with older partitioning software, 63 sectors instead of 2048 might be required. The MBR only needs a single 512 bytes block, the additional free space can be used for a BIOS boot partition and, in the case of a hybrid partitioning scheme, for a GUID Partition Table. Then, we attach a loop device to the MBR file:<br />
<br />
# losetup --show -f ''/path/to/mbr''<br />
/dev/loop0<br />
<br />
In this example, the resulting device is {{ic|/dev/loop0}}. The device mapper is now used to join the MBR and the partition:<br />
<br />
# echo "0 2048 linear /dev/loop0 0<br />
2048 `blockdev --getsz /dev/hda''N''` linear /dev/hda''N'' 0" | dmsetup create qemu<br />
<br />
The resulting {{ic|/dev/mapper/qemu}} is what we will use as a QEMU raw disk image. Additional steps are required to create a partition table (see the section that describes the use of a linear RAID for an example) and boot loader code on the virtual disk (which will be stored in {{ic|''/path/to/mbr''}}).<br />
<br />
The following setup is an example where the position of {{ic|/dev/hda''N''}} on the virtual disk is to be the same as on the physical disk and the rest of the disk is hidden, except for the MBR, which is provided as a copy:<br />
<br />
# dd if=/dev/hda count=1 of=''/path/to/mbr''<br />
# loop=`losetup --show -f ''/path/to/mbr''`<br />
# start=`blockdev --report /dev/hda''N'' | tail -1 | awk '{print $5}'`<br />
# size=`blockdev --getsz /dev/hda''N''`<br />
# disksize=`blockdev --getsz /dev/hda`<br />
# echo "0 1 linear $loop 0<br />
1 $((start-1)) zero<br />
$start $size linear /dev/hda''N'' 0<br />
$((start+size)) $((disksize-start-size)) zero" | dmsetup create qemu<br />
<br />
The table provided as standard input to {{ic|dmsetup}} has a similar format as the table in a VDMK descriptor file produced by {{ic|VBoxManage}} and can alternatively be loaded from a file with {{ic|dmsetup create qemu --table ''table_file''}}. To the virtual machine, only {{ic|/dev/hda''N''}} is accessible, while the rest of the hard disk reads as zeros and discards written data, except for the first sector. We can print the table for {{ic|/dev/mapper/qemu}} with {{ic|dmsetup table qemu}} (use {{ic|udevadm info -rq name /sys/dev/block/''major'':''minor''}} to translate {{ic|''major'':''minor''}} to the corresponding {{ic|/dev/''blockdevice''}} name). Use {{ic|dmsetup remove qemu}} and {{ic|losetup -d $loop}} to delete the created devices.<br />
<br />
A situation where this example would be useful is an existing Windows XP installation in a multi-boot configuration and maybe a hybrid partitioning scheme (on the physical hardware, Windows XP could be the only operating system that uses the MBR partition table, while more modern operating systems installed on the same computer could use the GUID Partition Table). Windows XP supports hardware profiles, so that that the same installation can be used with different hardware configurations alternatingly (in this case bare metal vs. virtual) with Windows needing to install drivers for newly detected hardware only once for every profile. Note that in this example the boot loader code in the copied MBR needs to be updated to directly load Windows XP from {{ic|/dev/hda''N''}} instead of trying to start the multi-boot capable boot loader (like GRUB) present in the original system. Alternatively, a copy of the boot partition containing the boot loader installation can be included in the virtual disk the same way as the MBR.<br />
<br />
===== Linear RAID =====<br />
<br />
You can also do this using software [[RAID]] in linear mode (you need the {{ic|linear.ko}} kernel driver) and a loopback device: <br />
<br />
First, you create some small file to hold the MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=32<br />
<br />
Here, a 16 KB (32 * 512 bytes) file is created. It is important not to make it too small (even if the MBR only needs a single 512 bytes block), since the smaller it will be, the smaller the chunk size of the software RAID device will have to be, which could have an impact on performance. Then, you setup a loopback device to the MBR file:<br />
<br />
# losetup -f ''/path/to/mbr''<br />
<br />
Let us assume the resulting device is {{ic|/dev/loop0}}, because we would not already have been using other loopbacks. Next step is to create the "merged" MBR + {{ic|/dev/hda''N''}} disk image using software RAID:<br />
<br />
# modprobe linear<br />
# mdadm --build --verbose /dev/md0 --chunk=16 --level=linear --raid-devices=2 /dev/loop0 /dev/hda''N''<br />
<br />
The resulting {{ic|/dev/md0}} is what you will use as a QEMU raw disk image (do not forget to set the permissions so that the emulator can access it). The last (and somewhat tricky) step is to set the disk configuration (disk geometry and partitions table) so that the primary partition start point in the MBR matches the one of {{ic|/dev/hda''N''}} inside {{ic|/dev/md0}} (an offset of exactly 16 * 512 = 16384 bytes in this example). Do this using {{ic|fdisk}} on the host machine, not in the emulator: the default raw disc detection routine from QEMU often results in non-kilobyte-roundable offsets (such as 31.5 KB, as in the previous section) that cannot be managed by the software RAID code. Hence, from the the host:<br />
<br />
# fdisk /dev/md0<br />
<br />
Press {{ic|X}} to enter the expert menu. Set number of 's'ectors per track so that the size of one cylinder matches the size of your MBR file. For two heads and a sector size of 512, the number of sectors per track should be 16, so we get cylinders of size 2x16x512=16k.<br />
<br />
Now, press {{ic|R}} to return to the main menu.<br />
<br />
Press {{ic|P}} and check that the cylinder size is now 16k.<br />
<br />
Now, create a single primary partition corresponding to {{ic|/dev/hda''N''}}. It should start at cylinder 2 and end at the end of the disk (note that the number of cylinders now differs from what it was when you entered fdisk.<br />
<br />
Finally, 'w'rite the result to the file: you are done. You now have a partition you can mount directly from your host, as well as part of a QEMU disk image:<br />
<br />
$ qemu-system-x86_64 -hdc /dev/md0 ''[...]''<br />
<br />
You can, of course, safely set any bootloader on this disk image using QEMU, provided the original {{ic|/dev/hda''N''}} partition contains the necessary tools.<br />
<br />
===== Network Block Device =====<br />
<br />
Instead of the methods decribed above, you may use {{ic|nbd-server}} (from the {{pkg|nbd}} package) to create an MBR wrapper for QEMU.<br />
<br />
Assuming you have already set up your MBR wrapper file like above, rename it to {{ic|wrapper.img.0}}. Then create a symbolic link named {{ic|wrapper.img.1}} in the same directory, pointing to your partition. Then put the following script in the same directory:<br />
<br />
#!/bin/sh<br />
dir="$(realpath "$(dirname "$0")")"<br />
cat >wrapper.conf <<EOF<br />
[generic]<br />
allowlist = true<br />
listenaddr = 127.713705<br />
port = 10809<br />
<br />
[wrap]<br />
exportname = $dir/wrapper.img<br />
multifile = true<br />
EOF<br />
<br />
nbd-server \<br />
-C wrapper.conf \<br />
-p wrapper.pid \<br />
"$@"<br />
<br />
The {{ic|.0}} and {{ic|.1}} suffixes are essential; the rest can be changed. After running the above script (which you may need to do as root to make sure nbd-server is able to access the partition), you can launch QEMU with:<br />
<br />
qemu-system-x86_64 -drive file=nbd:127.713705:10809:exportname=wrap ''[...]''<br />
<br />
== Networking ==<br />
<br />
{{Style|Network topologies (sections [[#Host-only networking]], [[#Internal networking]] and info spread out across other sections) should not be described alongside the various virtual interfaces implementations, such as [[#User-mode networking]], [[#Tap networking with QEMU]], [[#Networking with VDE2]].}}<br />
<br />
The performance of virtual networking should be better with tap devices and bridges than with user-mode networking or vde because tap devices and bridges are implemented in-kernel.<br />
<br />
In addition, networking performance can be improved by assigning virtual machines a [http://wiki.libvirt.org/page/Virtio virtio] network device rather than the default emulation of an e1000 NIC. See [[#Installing virtio drivers]] for more information.<br />
<br />
=== Link-level address caveat ===<br />
<br />
By giving the {{ic|-net nic}} argument to QEMU, it will, by default, assign a virtual machine a network interface with the link-level address {{ic|52:54:00:12:34:56}}. However, when using bridged networking with multiple virtual machines, it is essential that each virtual machine has a unique link-level (MAC) address on the virtual machine side of the tap device. Otherwise, the bridge will not work correctly, because it will receive packets from multiple sources that have the same link-level address. This problem occurs even if the tap devices themselves have unique link-level addresses because the source link-level address is not rewritten as packets pass through the tap device.<br />
<br />
Make sure that each virtual machine has a unique link-level address, but it should always start with {{ic|52:54:}}. Use the following option, replace ''X'' with arbitrary hexadecimal digit:<br />
<br />
$ qemu-system-x86_64 -net nic,macaddr=52:54:''XX:XX:XX:XX'' -net vde ''disk_image''<br />
<br />
Generating unique link-level addresses can be done in several ways:<br />
<br />
* Manually specify unique link-level address for each NIC. The benefit is that the DHCP server will assign the same IP address each time the virtual machine is run, but it is unusable for large number of virtual machines.<br />
* Generate random link-level address each time the virtual machine is run. Practically zero probability of collisions, but the downside is that the DHCP server will assign a different IP address each time. You can use the following command in a script to generate random link-level address in a {{ic|macaddr}} variable:<br />
<br />
{{bc|1=<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
qemu-system-x86_64 -net nic,macaddr="$macaddr" -net vde ''disk_image''<br />
}}<br />
<br />
* Use the following script {{ic|qemu-mac-hasher.py}} to generate the link-level address from the virtual machine name using a hashing function. Given that the names of virtual machines are unique, this method combines the benefits of the aforementioned methods: it generates the same link-level address each time the script is run, yet it preserves the practically zero probability of collisions.<br />
<br />
{{hc|qemu-mac-hasher.py|<nowiki><br />
#!/usr/bin/env python<br />
<br />
import sys<br />
import zlib<br />
<br />
if len(sys.argv) != 2:<br />
print("usage: %s <VM Name>" % sys.argv[0])<br />
sys.exit(1)<br />
<br />
crc = zlib.crc32(sys.argv[1].encode("utf-8")) & 0xffffffff<br />
crc = str(hex(crc))[2:]<br />
print("52:54:%s%s:%s%s:%s%s:%s%s" % tuple(crc))<br />
</nowiki>}}<br />
<br />
In a script, you can use for example:<br />
<br />
vm_name="''VM Name''"<br />
qemu-system-x86_64 -name "$vm_name" -net nic,macaddr=$(qemu-mac-hasher.py "$vm_name") -net vde ''disk_image''<br />
<br />
=== User-mode networking ===<br />
<br />
By default, without any {{ic|-netdev}} arguments, QEMU will use user-mode networking with a built-in DHCP server. Your virtual machines will be assigned an IP address when they run their DHCP client, and they will be able to access the physical host's network through IP masquerading done by QEMU.<br />
<br />
{{warning|This only works with the TCP and UDP protocols, so ICMP, including {{ic|ping}}, will not work. Do not use {{ic|ping}} to test network connectivity. To make ping work in the guest see [[Sysctl#Allow unprivileged users to create IPPROTO_ICMP sockets]].}}<br />
<br />
This default configuration allows your virtual machines to easily access the Internet, provided that the host is connected to it, but the virtual machines will not be directly visible on the external network, nor will virtual machines be able to talk to each other if you start up more than one concurrently.<br />
<br />
QEMU's user-mode networking can offer more capabilities such as built-in TFTP or SMB servers, redirecting host ports to the guest (for example to allow SSH connections to the guest) or attaching guests to VLANs so that they can talk to each other. See the QEMU documentation on the {{ic|-net user}} flag for more details.<br />
<br />
However, user-mode networking has limitations in both utility and performance. More advanced network configurations require the use of tap devices or other methods.<br />
<br />
{{Note|If the host system uses [[systemd-networkd]], make sure to symlink the {{ic|/etc/resolv.conf}} file as described in [[systemd-networkd#Required services and setup]], otherwise the DNS lookup in the guest system will not work.}}<br />
<br />
=== Tap networking with QEMU ===<br />
<br />
[[wikipedia:TUN/TAP|Tap devices]] are a Linux kernel feature that allows you to create virtual network interfaces that appear as real network interfaces. Packets sent to a tap interface are delivered to a userspace program, such as QEMU, that has bound itself to the interface.<br />
<br />
QEMU can use tap networking for a virtual machine so that packets sent to the tap interface will be sent to the virtual machine and appear as coming from a network interface (usually an Ethernet interface) in the virtual machine. Conversely, everything that the virtual machine sends through its network interface will appear on the tap interface.<br />
<br />
Tap devices are supported by the Linux bridge drivers, so it is possible to bridge together tap devices with each other and possibly with other host interfaces such as {{ic|eth0}}. This is desirable if you want your virtual machines to be able to talk to each other, or if you want other machines on your LAN to be able to talk to the virtual machines.<br />
<br />
{{Warning|If you bridge together tap device and some host interface, such as {{ic|eth0}}, your virtual machines will appear directly on the external network, which will expose them to possible attack. Depending on what resources your virtual machines have access to, you may need to take all the [[Firewalls|precautions]] you normally would take in securing a computer to secure your virtual machines. If the risk is too great, virtual machines have little resources or you set up multiple virtual machines, a better solution might be to use [[#Host-only networking|host-only networking]] and set up NAT. In this case you only need one firewall on the host instead of multiple firewalls for each guest.}}<br />
<br />
As indicated in the user-mode networking section, tap devices offer higher networking performance than user-mode. If the guest OS supports virtio network driver, then the networking performance will be increased considerably as well. Supposing the use of the tap0 device, that the virtio driver is used on the guest, and that no scripts are used to help start/stop networking, next is part of the qemu command one should see:<br />
<br />
-device virtio-net,netdev=network0 -netdev tap,id=network0,ifname=tap0,script=no,downscript=no<br />
<br />
But if already using a tap device with virtio networking driver, one can even boost the networking performance by enabling vhost, like:<br />
<br />
-device virtio-net,netdev=network0 -netdev tap,id=network0,ifname=tap0,script=no,downscript=no,vhost=on<br />
<br />
See [https://web.archive.org/web/20160222161955/http://www.linux-kvm.com:80/content/how-maximize-virtio-net-performance-vhost-net] for more information.<br />
<br />
==== Host-only networking ====<br />
<br />
If the bridge is given an IP address and traffic destined for it is allowed, but no real interface (e.g. {{ic|eth0}}) is connected to the bridge, then the virtual machines will be able to talk to each other and the host system. However, they will not be able to talk to anything on the external network, provided that you do not set up IP masquerading on the physical host. This configuration is called ''host-only networking'' by other virtualization software such as [[VirtualBox]].<br />
<br />
{{Tip|<br />
* If you want to set up IP masquerading, e.g. NAT for virtual machines, see the [[Internet sharing#Enable NAT]] page.<br />
* See [[Network bridge]] for information on creating bridge.<br />
* You may want to have a DHCP server running on the bridge interface to service the virtual network. For example, to use the {{ic|172.20.0.1/16}} subnet with [[dnsmasq]] as the DHCP server:<br />
<br />
{{bc|1=<br />
# ip addr add 172.20.0.1/16 dev br0<br />
# ip link set br0 up<br />
# dnsmasq --interface=br0 --bind-interfaces --dhcp-range=172.20.0.2,172.20.255.254<br />
}}<br />
}}<br />
<br />
==== Internal networking ====<br />
<br />
If you do not give the bridge an IP address and add an [[iptables]] rule to drop all traffic to the bridge in the INPUT chain, then the virtual machines will be able to talk to each other, but not to the physical host or to the outside network. This configuration is called ''internal networking'' by other virtualization software such as [[VirtualBox]]. You will need to either assign static IP addresses to the virtual machines or run a DHCP server on one of them.<br />
<br />
By default iptables would drop packets in the bridge network. You may need to use such iptables rule to allow packets in a bridged network:<br />
<br />
# iptables -I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Bridged networking using qemu-bridge-helper ====<br />
<br />
{{Note|This method is available since QEMU 1.1, see http://wiki.qemu.org/Features/HelperNetworking.}}<br />
<br />
This method does not require a start-up script and readily accommodates multiple taps and multiple bridges. It uses {{ic|/usr/lib/qemu/qemu-bridge-helper}} binary, which allows creating tap devices on an existing bridge.<br />
<br />
{{Tip|See [[Network bridge]] for information on creating bridge.}}<br />
<br />
First, create a configuration file containing the names of all bridges to be used by QEMU:<br />
<br />
{{hc|/etc/qemu/bridge.conf|<br />
allow ''bridge0''<br />
allow ''bridge1''<br />
...}}<br />
<br />
Now start the VM. The most basic usage would be:<br />
<br />
$ qemu-system-x86_64 -net nic -net bridge,br=''bridge0'' ''[...]''<br />
<br />
With multiple taps, the most basic usage requires specifying the VLAN for all additional NICs:<br />
<br />
$ qemu-system-x86_64 -net nic -net bridge,br=''bridge0'' -net nic,vlan=1 -net bridge,vlan=1,br=''bridge1'' ''[...]''<br />
<br />
==== Creating bridge manually ====<br />
<br />
{{Style|This section needs serious cleanup and may contain out-of-date information.}}<br />
<br />
{{Tip|Since QEMU 1.1, the [http://wiki.qemu.org/Features/HelperNetworking network bridge helper] can set tun/tap up for you without the need for additional scripting. See [[#Bridged networking using qemu-bridge-helper]].}}<br />
<br />
The following describes how to bridge a virtual machine to a host interface such as {{ic|eth0}}, which is probably the most common configuration. This configuration makes it appear that the virtual machine is located directly on the external network, on the same Ethernet segment as the physical host machine.<br />
<br />
We will replace the normal Ethernet adapter with a bridge adapter and bind the normal Ethernet adapter to it.<br />
<br />
* Install {{Pkg|bridge-utils}}, which provides {{ic|brctl}} to manipulate bridges.<br />
<br />
* Enable IPv4 forwarding:<br />
# sysctl -w net.ipv4.ip_forward=1<br />
<br />
To make the change permanent, change {{ic|1=net.ipv4.ip_forward = 0}} to {{ic|1=net.ipv4.ip_forward = 1}} in {{ic|/etc/sysctl.d/99-sysctl.conf}}.<br />
<br />
* Load the {{ic|tun}} module and configure it to be loaded on boot. See [[Kernel modules]] for details.<br />
<br />
* Now create the bridge. See [[Bridge with netctl]] for details. Remember to name your bridge as {{ic|br0}}, or change the scripts below to your bridge's name.<br />
<br />
* Create the script that QEMU uses to bring up the tap adapter with {{ic|root:kvm}} 750 permissions:<br />
<br />
{{hc|/etc/qemu-ifup|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifup"<br />
echo "Bringing up $1 for bridged mode..."<br />
sudo /usr/bin/ip link set $1 up promisc on<br />
echo "Adding $1 to br0..."<br />
sudo /usr/bin/brctl addif br0 $1<br />
sleep 2<br />
</nowiki>}}<br />
<br />
* Create the script that QEMU uses to bring down the tap adapter in {{ic|/etc/qemu-ifdown}} with {{ic|root:kvm}} 750 permissions:<br />
{{hc|/etc/qemu-ifdown|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifdown"<br />
sudo /usr/bin/ip link set $1 down<br />
sudo /usr/bin/brctl delif br0 $1<br />
sudo /usr/bin/ip link delete dev $1<br />
</nowiki>}}<br />
<br />
* Use {{ic|visudo}} to add the following to your {{ic|sudoers}} file:<br />
<br />
{{bc|<nowiki><br />
Cmnd_Alias QEMU=/usr/bin/ip,/usr/bin/modprobe,/usr/bin/brctl<br />
%kvm ALL=NOPASSWD: QEMU<br />
</nowiki>}}<br />
<br />
* You launch QEMU using the following {{ic|run-qemu}} script:<br />
<br />
{{hc|run-qemu|<nowiki><br />
#!/bin/bash<br />
USERID=$(whoami)<br />
<br />
# Get name of newly created TAP device; see https://bbs.archlinux.org/viewtopic.php?pid=1285079#p1285079<br />
precreationg=$(/usr/bin/ip tuntap list | /usr/bin/cut -d: -f1 | /usr/bin/sort)<br />
sudo /usr/bin/ip tuntap add user $USERID mode tap<br />
postcreation=$(/usr/bin/ip tuntap list | /usr/bin/cut -d: -f1 | /usr/bin/sort)<br />
IFACE=$(comm -13 <(echo "$precreationg") <(echo "$postcreation"))<br />
<br />
# This line creates a random MAC address. The downside is the DHCP server will assign a different IP address each time<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
# Instead, uncomment and edit this line to set a static MAC address. The benefit is that the DHCP server will assign the same IP address.<br />
# macaddr='52:54:be:36:42:a9'<br />
<br />
qemu-system-x86_64 -net nic,macaddr=$macaddr -net tap,ifname="$IFACE" $*<br />
<br />
sudo ip link set dev $IFACE down &> /dev/null<br />
sudo ip tuntap del $IFACE mode tap &> /dev/null<br />
</nowiki>}}<br />
<br />
Then to launch a VM, do something like this<br />
<br />
$ run-qemu -hda ''myvm.img'' -m 512<br />
<br />
* It is recommended for performance and security reasons to disable the [http://ebtables.netfilter.org/documentation/bridge-nf.html firewall on the bridge]:<br />
<br />
{{hc|/etc/sysctl.d/10-disable-firewall-on-bridge.conf|<nowiki><br />
net.bridge.bridge-nf-call-ip6tables = 0<br />
net.bridge.bridge-nf-call-iptables = 0<br />
net.bridge.bridge-nf-call-arptables = 0<br />
</nowiki>}}<br />
<br />
Run {{ic|sysctl -p /etc/sysctl.d/10-disable-firewall-on-bridge.conf}} to apply the changes immediately.<br />
<br />
See the [http://wiki.libvirt.org/page/Networking#Creating_network_initscripts libvirt wiki] and [https://bugzilla.redhat.com/show_bug.cgi?id=512206 Fedora bug 512206]. If you get errors by sysctl during boot about non-existing files, make the {{ic|bridge}} module load at boot. See [[Kernel modules#Automatic module loading with systemd]].<br />
<br />
Alternatively, you can configure [[iptables]] to allow all traffic to be forwarded across the bridge by adding a rule like this:<br />
<br />
-I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Network sharing between physical device and a Tap device through iptables ====<br />
<br />
{{Merge|Internet_sharing|Duplication, not specific to QEMU.}}<br />
<br />
Bridged networking works fine between a wired interface (Eg. eth0), and it is easy to setup. However if the host gets connected to the network through a wireless device, then bridging is not possible.<br />
<br />
See [[Network bridge#Wireless interface on a bridge]] as a reference.<br />
<br />
One way to overcome that is to setup a tap device with a static IP, making linux automatically handle the routing for it, and then forward traffic between the tap interface and the device connected to the network through iptables rules.<br />
<br />
See [[Internet sharing]] as a reference.<br />
<br />
There you can find what is needed to share the network between devices, included tap and tun ones. The following just hints further on some of the host configurations required. As indicated in the reference above, the client needs to be configured for a static IP, using the IP assigned to the tap interface as the gateway. The caveat is that the DNS servers on the client might need to be manually edited if they change when changing from one host device connected to the network to another.<br />
<br />
To allow IP forwarding on every boot, one need to add the following lines to sysctl configuration file inside {{ic|/etc/sysctl.d}}:<br />
<br />
net.ipv4.ip_forward = 1<br />
net.ipv6.conf.default.forwarding = 1<br />
net.ipv6.conf.all.forwarding = 1<br />
<br />
The iptables rules can look like:<br />
<br />
# Forwarding from/to outside<br />
iptables -A FORWARD -i ${INT} -o ${EXT_0} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_1} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_2} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_0} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_1} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_2} -o ${INT} -j ACCEPT<br />
# NAT/Masquerade (network address translation)<br />
iptables -t nat -A POSTROUTING -o ${EXT_0} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_1} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_2} -j MASQUERADE<br />
<br />
The prior supposes there are 3 devices connected to the network sharing traffic with one internal device, where for example:<br />
<br />
INT=tap0<br />
EXT_0=eth0<br />
EXT_1=wlan0<br />
EXT_2=tun0<br />
<br />
The prior shows a forwarding that would allow sharing wired and wireless connections with the tap device.<br />
<br />
The forwarding rules shown are stateless, and for pure forwarding. One could think of restricting specific traffic, putting a firewall in place to protect the guest and others. However those would decrease the networking performance, while a simple bridge does not include any of that.<br />
<br />
Bonus: Whether the connection is wired or wireless, if one gets connected through VPN to a remote site with a tun device, supposing the tun device opened for that connection is tun0, and the prior iptables rules are applied, then the remote connection gets also shared with the guest. This avoids the need for the guest to also open a VPN connection. Again, as the guest networking needs to be static, then if connecting the host remotely this way, one most probably will need to edit the DNS servers on the guest.<br />
<br />
=== Networking with VDE2 ===<br />
<br />
{{Style|This section needs serious cleanup and may contain out-of-date information.}}<br />
<br />
==== What is VDE? ====<br />
<br />
VDE stands for Virtual Distributed Ethernet. It started as an enhancement of [[User-mode Linux|uml]]_switch. It is a toolbox to manage virtual networks.<br />
<br />
The idea is to create virtual switches, which are basically sockets, and to "plug" both physical and virtual machines in them. The configuration we show here is quite simple; However, VDE is much more powerful than this, it can plug virtual switches together, run them on different hosts and monitor the traffic in the switches. You are invited to read [https://wiki.virtualsquare.org/ the documentation of the project].<br />
<br />
The advantage of this method is you do not have to add sudo privileges to your users. Regular users should not be allowed to run modprobe.<br />
<br />
==== Basics ====<br />
<br />
VDE support can be [[pacman|installed]] via the {{Pkg|vde2}} package.<br />
<br />
In our config, we use tun/tap to create a virtual interface on my host. Load the {{ic|tun}} module (see [[Kernel modules]] for details):<br />
<br />
# modprobe tun<br />
<br />
Now create the virtual switch:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
<br />
This line creates the switch, creates {{ic|tap0}}, "plugs" it, and allows the users of the group {{ic|users}} to use it.<br />
<br />
The interface is plugged in but not configured yet. To configure it, run this command:<br />
<br />
# ip addr add 192.168.100.254/24 dev tap0<br />
<br />
Now, you just have to run KVM with these {{ic|-net}} options as a normal user:<br />
<br />
$ qemu-system-x86_64 -net nic -net vde -hda ''[...]''<br />
<br />
Configure networking for your guest as you would do in a physical network.<br />
<br />
{{Tip|You might want to set up NAT on tap device to access the internet from the virtual machine. See [[Internet sharing#Enable NAT]] for more information.}}<br />
<br />
==== Startup scripts ====<br />
<br />
Example of main script starting VDE:<br />
<br />
{{hc|/etc/systemd/scripts/qemu-network-env|<nowiki><br />
#!/bin/sh<br />
# QEMU/VDE network environment preparation script<br />
<br />
# The IP configuration for the tap device that will be used for<br />
# the virtual machine network:<br />
<br />
TAP_DEV=tap0<br />
TAP_IP=192.168.100.254<br />
TAP_MASK=24<br />
TAP_NETWORK=192.168.100.0<br />
<br />
# Host interface<br />
NIC=eth0<br />
<br />
case "$1" in<br />
start)<br />
echo -n "Starting VDE network for QEMU: "<br />
<br />
# If you want tun kernel module to be loaded by script uncomment here<br />
#modprobe tun 2>/dev/null<br />
## Wait for the module to be loaded<br />
#while ! lsmod | grep -q "^tun"; do echo "Waiting for tun device"; sleep 1; done<br />
<br />
# Start tap switch<br />
vde_switch -tap "$TAP_DEV" -daemon -mod 660 -group users<br />
<br />
# Bring tap interface up<br />
ip address add "$TAP_IP"/"$TAP_MASK" dev "$TAP_DEV"<br />
ip link set "$TAP_DEV" up<br />
<br />
# Start IP Forwarding<br />
echo "1" > /proc/sys/net/ipv4/ip_forward<br />
iptables -t nat -A POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
;;<br />
stop)<br />
echo -n "Stopping VDE network for QEMU: "<br />
# Delete the NAT rules<br />
iptables -t nat -D POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
<br />
# Bring tap interface down<br />
ip link set "$TAP_DEV" down<br />
<br />
# Kill VDE switch<br />
pgrep vde_switch | xargs kill -TERM<br />
;;<br />
restart|reload)<br />
$0 stop<br />
sleep 1<br />
$0 start<br />
;;<br />
*)<br />
echo "Usage: $0 {start|stop|restart|reload}"<br />
exit 1<br />
esac<br />
exit 0<br />
</nowiki>}}<br />
<br />
Example of systemd service using the above script:<br />
<br />
{{hc|/etc/systemd/system/qemu-network-env.service|<nowiki><br />
[Unit]<br />
Description=Manage VDE Switch<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/etc/systemd/scripts/qemu-network-env start<br />
ExecStop=/etc/systemd/scripts/qemu-network-env stop<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
Change permissions for {{ic|qemu-network-env}} to be executable<br />
<br />
# chmod u+x /etc/systemd/scripts/qemu-network-env<br />
<br />
You can [[start]] {{ic|qemu-network-env.service}} as usual.<br />
<br />
====Alternative method====<br />
<br />
If the above method does not work or you do not want to mess with kernel configs, TUN, dnsmasq, and iptables you can do the following for the same result.<br />
<br />
# vde_switch -daemon -mod 660 -group users<br />
# slirpvde --dhcp --daemon<br />
<br />
Then, to start the VM with a connection to the network of the host:<br />
<br />
$ qemu-system-x86_64 -net nic,macaddr=52:54:00:00:EE:03 -net vde ''disk_image''<br />
<br />
=== VDE2 Bridge ===<br />
<br />
Based on [https://selamatpagicikgu.wordpress.com/2011/06/08/quickhowto-qemu-networking-using-vde-tuntap-and-bridge/ quickhowto: qemu networking using vde, tun/tap, and bridge] graphic. Any virtual machine connected to vde is externally exposed. For example, each virtual machine can receive DHCP configuration directly from your ADSL router.<br />
<br />
==== Basics ====<br />
<br />
Remember that you need {{ic|tun}} module and {{Pkg|bridge-utils}} package.<br />
<br />
Create the vde2/tap device:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
# ip link set tap0 up<br />
<br />
Create bridge:<br />
<br />
# brctl addbr br0<br />
<br />
Add devices:<br />
<br />
# brctl addif br0 eth0<br />
# brctl addif br0 tap0<br />
<br />
And configure bridge interface:<br />
<br />
# dhcpcd br0<br />
<br />
==== Startup scripts ====<br />
<br />
All devices must be set up. And only the bridge needs an IP address. For physical devices on the bridge (e.g. {{ic|eth0}}), this can be done with [[netctl]] using a custom Ethernet profile with:<br />
<br />
{{hc|/etc/netctl/ethernet-noip|2=<br />
Description='A more versatile static Ethernet connection'<br />
Interface=eth0<br />
Connection=ethernet<br />
IP=no<br />
}}<br />
<br />
The following custom systemd service can be used to create and activate a VDE2 tap interface for use in the {{ic|users}} user group.<br />
<br />
{{hc|/etc/systemd/system/vde2@.service|2=<br />
[Unit]<br />
Description=Network Connectivity for %i<br />
Wants=network.target<br />
Before=network.target<br />
<br />
[Service]<br />
Type=oneshot<br />
RemainAfterExit=yes<br />
ExecStart=/usr/bin/vde_switch -tap %i -daemon -mod 660 -group users<br />
ExecStart=/usr/bin/ip link set dev %i up<br />
ExecStop=/usr/bin/ip addr flush dev %i<br />
ExecStop=/usr/bin/ip link set dev %i down<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
}}<br />
<br />
And finally, you can create the [[Bridge with netctl|bridge interface with netctl]].<br />
<br />
=== Shorthand configuration ===<br />
<br />
If you are using QEMU with various networking options a lot, you probably have created a lot of {{ic|-netdev}} and {{ic|-device}} argument pairs, which gets quite repetitive. You can instead use the {{ic|-nic}} argument to combine {{ic|-netdev}} and {{ic|-device}} together, so that, for example, these arguments:<br />
<br />
-netdev tap,id=network0,ifname=tap0,script=no,downscript=no,vhost=on -device virtio-net-pci,netdev=network0<br />
<br />
become:<br />
<br />
-nic tap,script=no,downscript=no,vhost=on,model=virtio-net-pci<br />
<br />
Notice the lack of network IDs, and that the device was created with {{ic|1=model=}}. The first half of the {{ic|-nic}} parameters are {{ic|-netdev}} parameters, whereas the second half (after {{ic|1=model=}}) are related with the device. The same parameters (for example, {{ic|1=smb=}}) are used. To completely disable the networking use {{ic|-nic none}}.<br />
<br />
See [https://qemu.weilnetz.de/doc/qemu-doc.html#Network-options QEMU networking documentation] for more information on parameters you can use.<br />
<br />
== Graphic card ==<br />
<br />
QEMU can emulate a standard graphic card text mode using {{ic|-curses}} command line option. This allows to type text and see text output directly inside a text terminal.<br />
<br />
QEMU can emulate several types of VGA card. The card type is passed in the {{ic|-vga ''type''}} command line option and can be {{ic|std}}, {{ic|qxl}}, {{ic|vmware}}, {{ic|virtio}}, {{ic|cirrus}} or {{ic|none}}.<br />
<br />
=== std ===<br />
<br />
With {{ic|-vga std}} you can get a resolution of up to 2560 x 1600 pixels without requiring guest drivers. This is the default since QEMU 2.2.<br />
<br />
=== qxl ===<br />
<br />
QXL is a paravirtual graphics driver with 2D support. To use it, pass the {{ic|-vga qxl}} option and install drivers in the guest. You may want to use [[#SPICE]] for improved graphical performance when using QXL.<br />
<br />
On Linux guests, the {{ic|qxl}} and {{ic|bochs_drm}} kernel modules must be loaded in order to gain a decent performance.<br />
<br />
Default VGA memory size for QXL devices is 16M which is sufficient to drive resolutions approximately up to QHD (2560x1440). To enable higher resolutions, [[#Multi-monitor support|increase vga_memmb]].<br />
<br />
=== vmware ===<br />
<br />
Although it is a bit buggy, it performs better than std and cirrus. Install the VMware drivers {{Pkg|xf86-video-vmware}} and {{Pkg|xf86-input-vmmouse}} for Arch Linux guests.<br />
<br />
=== virtio ===<br />
<br />
{{ic|virtio-vga}} / {{ic|virtio-gpu}} is a paravirtual 3D graphics driver based on [https://virgil3d.github.io/ virgl]. Currently a work in progress, supporting only very recent (>= 4.4) Linux guests with {{Pkg|mesa}} (>=11.2) compiled with the option {{ic|1=gallium-drivers=virgl}}.<br />
<br />
To enable 3D acceleration on the guest system select this vga with {{ic|-vga virtio}} and enable the opengl context in the display device with {{ic|1=-display sdl,gl=on}} or {{ic|1=-display gtk,gl=on}} for the sdl and gtk display output respectively. Successful configuration can be confirmed looking at the kernel log in the guest:<br />
<br />
{{hc|$ dmesg {{!}} grep drm |<br />
[drm] pci: virtio-vga detected<br />
[drm] virgl 3d acceleration enabled<br />
}}<br />
<br />
=== cirrus ===<br />
<br />
The cirrus graphical adapter was the default [http://wiki.qemu.org/ChangeLog/2.2#VGA before 2.2]. It [https://www.kraxel.org/blog/2014/10/qemu-using-cirrus-considered-harmful/ should not] be used on modern systems.<br />
<br />
=== none ===<br />
<br />
This is like a PC that has no VGA card at all. You would not even be able to access it with the {{ic|-vnc}} option. Also, this is different from the {{ic|-nographic}} option which lets QEMU emulate a VGA card, but disables the SDL display.<br />
<br />
== SPICE ==<br />
The [http://spice-space.org/ SPICE project] aims to provide a complete open source solution for remote access to virtual machines in a seamless way.<br />
=== Enabling SPICE support on the host ===<br />
The following is an example of booting with SPICE as the remote desktop protocol, including the support for copy and paste from host:<br />
<br />
$ qemu-system-x86_64 -vga qxl -device virtio-serial-pci -spice port=5930,disable-ticketing -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
The parameters have the following meaning:<br />
<br />
# {{ic|-device virtio-serial-pci}} adds a virtio-serial device<br />
# {{ic|1=-spice port=5930,disable-ticketing}} set TCP port {{ic|5930}} for spice channels listening and allow client to connect without authentication{{Tip|Using [[wikipedia:Unix_socket|Unix sockets]] instead of TCP ports does not involve using network stack on the host system. It does not imply that packets are encapsulated and decapsulated to use the network and the related protocol. The sockets are identified solely by the inodes on the hard drive. It is therefore considered better for performance. Use instead {{ic|1=-spice unix,addr=/tmp/vm_spice.socket,disable-ticketing}}.}}<br />
# {{ic|1=-device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0}} opens a port for spice vdagent in the virtio-serial device,<br />
# {{ic|1=-chardev spicevmc,id=spicechannel0,name=vdagent}} adds a spicevmc chardev for that port. It is important that the {{ic|1=chardev=}} option of the {{ic|virtserialport}} device matches the {{ic|1=id=}} option given to the {{ic|chardev}} option ({{ic|spicechannel0}} in this example). It is also important that the port name is {{ic|com.redhat.spice.0}}, because that is the namespace where vdagent is looking for in the guest. And finally, specify {{ic|1=name=vdagent}} so that spice knows what this channel is for.<br />
<br />
=== Connecting to the guest with a SPICE client ===<br />
<br />
A SPICE client is necessary to connect to the guest. In Arch, the following clients are available:<br />
<br />
{{App|virt-viewer|SPICE client recommended by the protocol developers, a subset of the virt-manager project.|https://virt-manager.org/|{{Pkg|virt-viewer}}}}<br />
<br />
{{App|spice-gtk|SPICE GTK client, a subset of the SPICE project. Embedded into other applications as a widget.|https://www.spice-space.org/|{{Pkg|spice-gtk}}}}<br />
<br />
For clients that run on smartphone or on other platforms, refer to the ''Other clients'' section in [http://www.spice-space.org/download.html spice-space download].<br />
<br />
==== Manually running a SPICE client ====<br />
<br />
One way of connecting to a guest listening on Unix socket {{ic|/tmp/vm_spice.socket}} is to manually run the SPICE client using {{ic|$ remote-viewer spice+unix:///tmp/vm_spice.socket}} or {{ic|1=$ spicy --uri="spice+unix:///tmp/vm_spice.socket"}}, depending on the desired client. Since QEMU in SPICE mode acts similarly to a remote desktop server, it may be more convenient to run QEMU in daemon mode with the {{ic|-daemonize}} parameter.<br />
<br />
{{Tip|To connect to the guest through SSH tunelling, the following type of command can be used: {{bc|$ ssh -fL 5999:localhost:5930 ''my.domain.org'' sleep 10; spicy -h 127.0.0.1 -p 5999}}<br />
This example connects ''spicy'' to the local port {{ic|5999}} which is forwarded through SSH to the guest's SPICE server located at the address ''my.domain.org'', port {{ic|5930}}.<br />
Note the {{ic|-f}} option that requests ssh to execute the command {{ic|sleep 10}} in the background. This way, the ssh session runs while the client is active and auto-closes once the client ends.<br />
}}<br />
<br />
==== Running a SPICE client with QEMU ====<br />
<br />
QEMU can automatically start a SPICE client with an appropriate socket, if the display is set to SPICE with the {{ic|-display spice-app}} parameter. This will use the system's default SPICE client as the viewer, determined by your [[XDG_MIME_Applications#mimeapps.list|mimeapps.list]] files.<br />
<br />
=== Enabling SPICE support on the guest ===<br />
<br />
For '''Arch Linux guests''', for improved support for multiple monitors or clipboard sharing, the following packages should be installed:<br />
* {{Pkg|spice-vdagent}}: Spice agent xorg client that enables copy and paste between client and X-session and more.<br />
* {{Pkg|xf86-video-qxl}}: Xorg X11 qxl video driver<br />
For guests under '''other operating systems''', refer to the ''Guest'' section in [http://www.spice-space.org/download.html spice-space download].<br />
<br />
=== Password authentication with SPICE ===<br />
<br />
If you want to enable password authentication with SPICE you need to remove {{ic|disable-ticketing}} from the {{ic|-spice}} argument and instead add {{ic|1=password=''yourpassword''}}. For example:<br />
<br />
$ qemu-system-x86_64 -vga qxl -spice port=5900,password=''yourpassword'' -device virtio-serial-pci -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
Your SPICE client should now ask for the password to be able to connect to the SPICE server.<br />
<br />
=== TLS encrypted communication with SPICE ===<br />
<br />
You can also configure TLS encryption for communicating with the SPICE server. First, you need to have a directory which contains the following files (the names must be exactly as indicated):<br />
<br />
* {{ic|ca-cert.pem}}: the CA master certificate.<br />
* {{ic|server-cert.pem}}: the server certificate signed with {{ic|ca-cert.pem}}.<br />
* {{ic|server-key.pem}}: the server private key.<br />
<br />
An example of generation of self-signed certificates with your own generated CA for your server is shown in the [https://www.spice-space.org/spice-user-manual.html#_generating_self_signed_certificates Spice User Manual].<br />
<br />
Afterwards, you can run QEMU with SPICE as explained above but using the following {{ic|-spice}} argument: {{ic|1=-spice tls-port=5901,password=''yourpassword'',x509-dir=''/path/to/pki_certs''}}, where {{ic|''/path/to/pki_certs''}} is the directory path that contains the three needed files shown earlier.<br />
<br />
It is now possible to connect to the server using {{pkg|virt-viewer}}:<br />
<br />
$ remote-viewer spice://''hostname''?tls-port=5901 --spice-ca-file=''/path/to/ca-cert.pem'' --spice-host-subject="C=''XX'',L=''city'',O=''organization'',CN=''hostname''" --spice-secure-channels=all<br />
<br />
Keep in mind that the {{ic|--spice-host-subject}} parameter needs to be set according to your {{ic|server-cert.pem}} subject. You also need to copy {{ic|ca-cert.pem}} to every client to verify the server certificate.<br />
<br />
{{Tip|You can get the subject line of the server certificate in the correct format for {{ic|--spice-host-subject}} (with entries separated by commas) using the following command: {{bc|<nowiki>$ openssl x509 -noout -subject -in server-cert.pem | cut -d' ' -f2- | sed 's/\///' | sed 's/\//,/g'</nowiki>}}<br />
}}<br />
<br />
The equivalent {{Pkg|spice-gtk}} command is:<br />
<br />
$ spicy -h ''hostname'' -s 5901 --spice-ca-file=ca-cert.pem --spice-host-subject="C=''XX'',L=''city'',O=''organization'',CN=''hostname''" --spice-secure-channels=all<br />
<br />
== VNC ==<br />
<br />
One can add the {{ic|-vnc :''X''}} option to have QEMU redirect the VGA display to the VNC session. Substitute {{ic|''X''}} for the number of the display (0 will then listen on 5900, 1 on 5901...).<br />
<br />
$ qemu-system-x86_64 -vnc :0<br />
<br />
An example is also provided in the [[#Starting QEMU virtual machines on boot]] section.<br />
{{Warning|The default VNC server setup does not use any form of authentication. Any user can connect from any host.}}<br />
<br />
=== Basic password authentication ===<br />
<br />
An access password can be setup easily by using the {{ic|password}} option. The password must be indicated in the QEMU monitor and connection is only possible once the password is provided.<br />
<br />
$ qemu-system-x86_64 -vnc :0,password -monitor stdio<br />
<br />
In the QEMU monitor, password is set using the command {{ic|change vnc password}} and then indicating the password.<br />
<br />
The following command line directly runs vnc with a password:<br />
<br />
$ printf "change vnc password\n%s\n" MYPASSWORD | qemu-system-x86_64 -vnc :0,password -monitor stdio<br />
<br />
{{Note|The password is limited to 8 characters and can be guessed through brute force attack. More elaborated protection is strongly recommended for public network.}}<br />
<br />
== Audio ==<br />
<br />
=== Host ===<br />
<br />
The {{ic|-audiodev}} flag sets the audio backend driver and its options. The list of available audio backend drivers and their optional settings is detailed in the {{man|1|qemu}}. man page.<br />
<br />
At the bare minimum, you need to choose a driver and set an id.<br />
<br />
-audiodev pa,id=snd0<br />
<br />
=== Guest ===<br />
<br />
==== With audiodev ====<br />
<br />
===== Intel HD Audio =====<br />
<br />
For Intel HD Audio emulation add both controller and codec devices. To list the available Intel HDA Audio devices:<br />
<br />
$ qemu-system-x86_64 -device help | grep hda<br />
<br />
Add the audio controller<br />
<br />
-device ich9-intel-hda<br />
<br />
Add the audio codec and map it to a host audio backend id<br />
<br />
-device hda-output,audiodev=snd0<br />
<br />
===== Intel 82801AA AC97 =====<br />
<br />
For AC97 emulation just add the audio card device and map it to a host audio backend id<br />
<br />
-device AC97,audiodev=snd0<br />
<br />
==== Without audiodev ====<br />
<br />
To get list of the supported emulation audio drivers:<br />
$ qemu-system-x86_64 -soundhw help<br />
<br />
To use e.g. {{ic|intel-hda}} driver for the guest use the {{ic|-device intel-hda -device hda-duplex}} command with QEMU.<br />
<br />
{{Note|Video graphic card emulated drivers for the guest machine may also cause a problem with the sound quality. Test one by one to make it work. You can list possible options with {{ic|<nowiki>qemu-system-x86_64 -h | grep vga</nowiki>}}.}}<br />
<br />
== Installing virtio drivers ==<br />
<br />
QEMU offers guests the ability to use paravirtualized block and network devices using the [http://wiki.libvirt.org/page/Virtio virtio] drivers, which provide better performance and lower overhead.<br />
<br />
* A virtio block device requires the option {{Ic|-drive}} for passing a disk image, with parameter {{Ic|1=if=virtio}}:<br />
$ qemu-system-x86_64 -boot order=c -drive file=''disk_image'',if=virtio<br />
<br />
* Almost the same goes for the network:<br />
$ qemu-system-x86_64 -nic user,model=virtio-net-pci<br />
<br />
{{Note|This will only work if the guest machine has drivers for virtio devices. Linux does, and the required drivers are included in Arch Linux, but there is no guarantee that virtio devices will work with other operating systems.}}<br />
<br />
=== Preparing an (Arch) Linux guest ===<br />
<br />
To use virtio devices after an Arch Linux guest has been installed, the following modules must be loaded in the guest: {{Ic|virtio}}, {{Ic|virtio_pci}}, {{Ic|virtio_blk}}, {{Ic|virtio_net}}, and {{Ic|virtio_ring}}. For 32-bit guests, the specific "virtio" module is not necessary.<br />
<br />
If you want to boot from a virtio disk, the initial ramdisk must contain the necessary modules. By default, this is handled by [[mkinitcpio]]'s {{ic|autodetect}} hook. Otherwise use the {{ic|MODULES}} array in {{ic|/etc/mkinitcpio.conf}} to include the necessary modules and rebuild the initial ramdisk.<br />
<br />
{{hc|/etc/mkinitcpio.conf|2=<br />
MODULES=(virtio virtio_blk virtio_pci virtio_net)}}<br />
<br />
Virtio disks are recognized with the prefix {{ic|'''v'''}} (e.g. {{ic|'''v'''da}}, {{ic|'''v'''db}}, etc.); therefore, changes must be made in at least {{ic|/etc/fstab}} and {{ic|/boot/grub/grub.cfg}} when booting from a virtio disk.<br />
<br />
{{Tip|When referencing disks by [[UUID]] in both {{ic|/etc/fstab}} and bootloader, nothing has to be done.}}<br />
<br />
Further information on paravirtualization with KVM can be found [http://www.linux-kvm.org/page/Boot_from_virtio_block_device here].<br />
<br />
You might also want to install {{Pkg|qemu-guest-agent}} to implement support for QMP commands that will enhance the hypervisor management capabilities. After installing the package you can enable and start the {{ic|qemu-ga.service}}.<br />
<br />
=== Preparing a Windows guest ===<br />
<br />
==== Block device drivers ====<br />
<br />
===== New Install of Windows =====<br />
<br />
Windows does not come with the virtio drivers. Therefore, you will need to load them during installation. There are basically two ways to do this: via Floppy Disk or via ISO files. Both images can be downloaded from the [https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/stable-virtio/virtio-win.iso Fedora repository].<br />
<br />
The floppy disk option is difficult because you will need to press F6 (Shift-F6 on newer Windows) at the very beginning of powering on the QEMU. This is difficult since you need time to connect your VNC console window. You can attempt to add a delay to the boot sequence. See {{man|1|qemu}} for more details about applying a delay at boot.<br />
<br />
The ISO option to load drivers is the preferred way, but it is available only on Windows Vista and Windows Server 2008 and later. The procedure is to load the image with virtio drivers in an additional cdrom device along with the primary disk device and Windows installer:<br />
<br />
$ qemu-system-x86_64 ... \<br />
-drive file=''windows_disk_image'',index=0,media=disk,if=virtio \<br />
-drive file=''windows.iso'',index=2,media=cdrom \<br />
-drive file=''virtio.iso'',index=3,media=cdrom \<br />
...<br />
<br />
During the installation, at some stage, the Windows installer will ask "Where do you want to install Windows?", it will give a warning that no disks are found. Follow the example instructions below (based on Windows Server 2012 R2 with Update).<br />
<br />
* Select the option ''Load Drivers''.<br />
* Uncheck the box for ''Hide drivers that aren't compatible with this computer's hardware''.<br />
* Click the browse button and open the CDROM for the virtio iso, usually named "virtio-win-XX".<br />
* Now browse to {{ic|E:\viostor\[your-os]\amd64}}, select it, and confirm.<br />
<br />
You should now see your virtio disk(s) listed here, ready to be selected, formatted and installed to.<br />
<br />
===== Change Existing Windows VM to use virtio =====<br />
<br />
Modifying an existing Windows guest for booting from virtio disk requires that the virtio driver is available in the guest and that it is loaded at boot time.<br />
<br />
One can find the virtio disk driver in the [https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/stable-virtio/virtio-win.iso Fedora repository].<br />
<br />
Now, create a new disk image that will be used to search for the virtio driver:<br />
<br />
$ qemu-img create -f qcow2 ''fake.qcow2'' 1G<br />
<br />
Run the original Windows guest (with the boot disk still in IDE mode) with the fake disk (in virtio mode) and a CD-ROM with the driver.<br />
<br />
$ qemu-system-x86_64 -m 512 -drive file=''windows_disk_image'',if=ide -drive file=''fake.qcow2'',if=virtio -cdrom virtio-win-0.1-81.iso<br />
<br />
Windows will detect the fake disk and look for a suitable driver. If it fails, go to ''Device Manager'', locate the SCSI drive with an exclamation mark icon (should be open), click ''Update driver'' and select the virtual CD-ROM. Do not navigate to the driver folder within the CD-ROM, simply select the CD-ROM drive and Windows will find the appropriate driver automatically (tested for Windows 7 SP1).<br />
<br />
Request Windows to boot in safe mode next time it starts up. This can be done using the ''msconfig.exe'' tool in Windows. In safe mode all the drivers will be loaded at boot time including the new virtio driver. Once Windows knows that the virtio driver is required at boot it will memorize it for future boot.<br />
<br />
Once instructed to boot in safe mode, you can turn off the virtual machine and launch it again, now with the boot disk attached in virtio mode:<br />
<br />
$ qemu-system-x86_64 -m 512 -drive file=''windows_disk_image'',if=virtio<br />
<br />
You should boot in safe mode with virtio driver loaded, you can now return to ''msconfig.exe'' disable safe mode boot and restart Windows.<br />
<br />
{{Note|If you encounter the blue screen of death using the {{ic|1=if=virtio}} parameter, it probably means the virtio disk driver is not installed or not loaded at boot time, reboot in safe mode and check your driver configuration.}}<br />
<br />
==== Network drivers ====<br />
<br />
Installing virtio network drivers is a bit easier, simply add the {{ic|-nic}} argument.<br />
<br />
$ qemu-system-x86_64 -m 512 -drive file=''windows_disk_image'',if=virtio -nic user,model=virtio-net-pci -cdrom virtio-win-0.1-74.iso<br />
<br />
Windows will detect the network adapter and try to find a driver for it. If it fails, go to the ''Device Manager'', locate the network adapter with an exclamation mark icon (should be open), click ''Update driver'' and select the virtual CD-ROM. Do not forget to select the checkbox which says to search for directories recursively.<br />
<br />
==== Balloon driver ====<br />
<br />
If you want to track you guest memory state (for example via {{ic|virsh}} command {{ic|dommemstat}}) or change guest's memory size in runtime (you still will not be able to change memory size, but can limit memory usage via inflating balloon driver) you will need to install guest balloon driver.<br />
<br />
For this you will need to go to ''Device Manager'', locate ''PCI standard RAM Controller'' in ''System devices'' (or unrecognized PCI controller from ''Other devices'') and choose ''Update driver''. In opened window you will need to choose ''Browse my computer...'' and select the CD-ROM (and do not forget the ''Include subdirectories'' checkbox). Reboot after installation. This will install the driver and you will be able to inflate the balloon (for example via hmp command {{ic|balloon ''memory_size''}}, which will cause balloon to take as much memory as possible in order to shrink the guest's available memory size to ''memory_size''). However, you still will not be able to track guest memory state. In order to do this you will need to install ''Balloon'' service properly. For that open command line as administrator, go to the CD-ROM, ''Balloon'' directory and deeper, depending on your system and architecture. Once you are in ''amd64'' (''x86'') directory, run {{ic|blnsrv.exe -i}} which will do the installation. After that {{ic|virsh}} command {{ic|dommemstat}} should be outputting all supported values.<br />
<br />
=== Preparing a FreeBSD guest ===<br />
<br />
Install the {{ic|emulators/virtio-kmod}} port if you are using FreeBSD 8.3 or later up until 10.0-CURRENT where they are included into the kernel. After installation, add the following to your {{ic|/boot/loader.conf}} file:<br />
<br />
{{bc|1=<br />
virtio_load="YES"<br />
virtio_pci_load="YES"<br />
virtio_blk_load="YES"<br />
if_vtnet_load="YES"<br />
virtio_balloon_load="YES"<br />
}}<br />
<br />
Then modify your {{ic|/etc/fstab}} by doing the following:<br />
<br />
# sed -ibak "s/ada/vtbd/g" /etc/fstab<br />
<br />
And verify that {{ic|/etc/fstab}} is consistent. If anything goes wrong, just boot into a rescue CD and copy {{ic|/etc/fstab.bak}} back to {{ic|/etc/fstab}}.<br />
<br />
== QEMU monitor ==<br />
<br />
While QEMU is running, a monitor console is provided in order to provide several ways to interact with the virtual machine running. The QEMU monitor offers interesting capabilities such as obtaining information about the current virtual machine, hotplugging devices, creating snapshots of the current state of the virtual machine, etc. To see the list of all commands, run {{ic|help}} or {{ic|?}} in the QEMU monitor console or review the relevant section of the [https://qemu.weilnetz.de/doc/qemu-doc.html#pcsys_005fmonitor official QEMU documentation].<br />
<br />
=== Accessing the monitor console ===<br />
<br />
==== Graphical view ====<br />
<br />
When using the {{ic|std}} default graphics option, one can access the QEMU monitor by pressing {{ic|Ctrl+Alt+2}} or by clicking ''View > compatmonitor0'' in the QEMU window. To return to the virtual machine graphical view either press {{ic|Ctrl+Alt+1}} or click ''View > VGA''.<br />
<br />
However, the standard method of accessing the monitor is not always convenient and does not work in all graphic outputs QEMU supports.<br />
<br />
==== Telnet ====<br />
<br />
To enable [[telnet]], run QEMU with the {{ic|-monitor telnet:127.0.0.1:''port'',server,nowait}} parameter. When the virtual machine is started you will be able to access the monitor via telnet:<br />
<br />
$ telnet 127.0.0.1 ''port''<br />
<br />
{{Note|If {{ic|127.0.0.1}} is specified as the IP to listen it will be only possible to connect to the monitor from the same host QEMU is running on. If connecting from remote hosts is desired, QEMU must be told to listen {{ic|0.0.0.0}} as follows: {{ic|-monitor telnet:0.0.0.0:''port'',server,nowait}}. Keep in mind that it is recommended to have a [[firewall]] configured in this case or make sure your local network is completely trustworthy since this connection is completely unauthenticated and unencrypted.}}<br />
<br />
==== UNIX socket ====<br />
<br />
Run QEMU with the {{ic|-monitor unix:''socketfile'',server,nowait}} parameter. Then you can connect with either {{pkg|socat}} or {{pkg|openbsd-netcat}}.<br />
<br />
For example, if QEMU is run via:<br />
<br />
$ qemu-system-x86_64 ''[...]'' -monitor unix:/tmp/monitor.sock,server,nowait ''[...]''<br />
<br />
It is possible to connect to the monitor with:<br />
<br />
$ socat - UNIX-CONNECT:/tmp/monitor.sock<br />
<br />
Or with:<br />
<br />
$ nc -U /tmp/monitor.sock<br />
<br />
==== TCP ====<br />
<br />
You can expose the monitor over TCP with the argument {{ic|-monitor tcp:127.0.0.1:''port'',server,nowait}}. Then connect with netcat, either {{pkg|openbsd-netcat}} or {{pkg|gnu-netcat}} by running:<br />
<br />
$ nc 127.0.0.1 ''port''<br />
<br />
{{Note|In order to be able to connect to the tcp socket from other devices other than the same host QEMU is being run on you need to listen to {{ic|0.0.0.0}} like explained in the telnet case. The same security warnings apply in this case as well.}}<br />
<br />
==== Standard I/O ====<br />
<br />
It is possible to access the monitor automatically from the same terminal QEMU is being run by running it with the argument {{ic|-monitor stdio}}.<br />
<br />
=== Sending keyboard presses to the virtual machine using the monitor console ===<br />
<br />
Some combinations of keys may be difficult to perform on virtual machines due to the host intercepting them instead in some configurations (a notable example is the {{ic|Ctrl+Alt+F*}} key combinations, which change the active tty). To avoid this problem, the problematic combination of keys may be sent via the monitor console instead. Switch to the monitor and use the {{ic|sendkey}} command to forward the necessary keypresses to the virtual machine. For example:<br />
<br />
(qemu) sendkey ctrl-alt-f2<br />
<br />
=== Creating and managing snapshots via the monitor console ===<br />
<br />
{{Note|This feature will '''only''' work when the virtual machine disk image is in ''qcow2'' format. It will not work with ''raw'' images.}}<br />
<br />
It is sometimes desirable to save the current state of a virtual machine and having the possibility of reverting the state of the virtual machine to that of a previously saved snapshot at any time. The QEMU monitor console provides the user with the necessary utilities to create snapshots, manage them, and revert the machine state to a saved snapshot.<br />
<br />
* Use {{ic|savevm ''name''}} in order to create a snapshot with the tag ''name''.<br />
* Use {{ic|loadvm ''name''}} to revert the virtual machine to the state of the snapshot ''name''.<br />
* Use {{ic|delvm ''name''}} to delete the snapshot tagged as ''name''.<br />
* Use {{ic|info snapshots}} to see a list of saved snapshots. Snapshots are identified by both an auto-incremented ID number and a text tag (set by the user on snapshot creation).<br />
<br />
=== Running the virtual machine in immutable mode ===<br />
<br />
It is possible to run a virtual machine in a frozen state so that all changes will be discarded when the virtual machine is powered off just by running QEMU with the {{ic|-snapshot}} parameter. When the disk image is written by the guest, changes will be saved in a temporary file in {{ic|/tmp}} and will be discarded when QEMU halts.<br />
<br />
However, if a machine is running in frozen mode it is still possible to save the changes to the disk image if it is afterwards desired by using the monitor console and running the following command:<br />
<br />
(qemu) commit all<br />
<br />
If snapshots are created when running in frozen mode they will be discarded as soon as QEMU is exited unless changes are explicitly commited to disk, as well.<br />
<br />
=== Pause and power options via the monitor console ===<br />
<br />
Some operations of a physical machine can be emulated by QEMU using some monitor commands:<br />
<br />
* {{ic|system_powerdown}} will send an ACPI shutdown request to the virtual machine. This effect is similar to the power button in a physical machine.<br />
* {{ic|system_reset}} will reset the virtual machine similarly to a reset button in a physical machine. This operation can cause data loss and file system corruption since the virtual machine is not cleanly restarted.<br />
* {{ic|stop}} will pause the virtual machine.<br />
* {{ic|cont}} will resume a virtual machine previously paused.<br />
<br />
=== Taking screenshots of the virtual machine ===<br />
<br />
Screenshots of the virtual machine graphic display can be obtained in the PPM format by running the following command in the monitor console:<br />
<br />
(qemu) screendump ''file.ppm''<br />
<br />
== QEMU machine protocol ==<br />
<br />
The QEMU machine protocol (QMP) is a JSON-based protocol which allows applications to control a QEMU instance. Similarly to the [[#QEMU monitor]] it offers ways to interact with a running machine and the JSON protocol allows to do it programmatically. The description of all the QMP commands can be found in [https://raw.githubusercontent.com/coreos/qemu/master/qmp-commands.hx qmp-commands].<br />
<br />
=== Start QMP ===<br />
<br />
The usual way to control the guest using the QMP protocol, is to open a TCP socket when launching the machine using the {{ic|-qmp}} option. Here it is using for example the TCP port 4444:<br />
<br />
$ qemu-system-x86_64 ''[...]'' -qmp tcp:localhost:4444,server,nowait<br />
<br />
Then one way to communicate with the QMP agent is to use [[netcat]]:<br />
<br />
{{hc|nc localhost 4444|{"QMP": {"version": {"qemu": {"micro": 0, "minor": 1, "major": 3}, "package": ""}, "capabilities": []} } }}<br />
<br />
At this stage, the only command that can be recognized is {{ic|qmp_capabilities}}, so that QMP enters into command mode. Type:<br />
<br />
{"execute": "qmp_capabilities"}<br />
<br />
Now, QMP is ready to receive commands, to retrieve the list of recognized commands, use:<br />
<br />
{"execute": "query-commands"}<br />
<br />
=== Live merging of child image into parent image ===<br />
<br />
It is possible to merge a running snapshot into its parent by issuing a {{ic|block-commit}} command. In its simplest form the following line will commit the child into its parent:<br />
<br />
{"execute": "block-commit", "arguments": {"device": "''devicename''"}}<br />
<br />
Upon reception of this command, the handler looks for the base image and converts it from read only to read write mode and then runs the commit job.<br />
<br />
Once the ''block-commit'' operation has completed, the event {{ic|BLOCK_JOB_READY}} will be emitted, signalling that the synchronization has finished. The job can then be gracefully completed by issuing the command {{ic|block-job-complete}}:<br />
<br />
{"execute": "block-job-complete", "arguments": {"device": "''devicename''"}}<br />
<br />
Until such a command is issued, the ''commit'' operation remains active.<br />
After successful completion, the base image remains in read write mode and becomes the new active layer. On the other hand, the child image becomes invalid and it is the responsibility of the user to clean it up.<br />
<br />
{{Tip|The list of device and their names can be retrieved by executing the command {{ic|query-block}} and parsing the results. The device name is in the {{ic|device}} field, for example {{ic|ide0-hd0}} for the hard disk in this example: {{hc|{"execute": "query-block"}|{"return": [{"io-status": "ok", "device": "'''ide0-hd0'''", "locked": false, "removable": false, "inserted": {"iops_rd": 0, "detect_zeroes": "off", "image": {"backing-image": {"virtual-size": 27074281472, "filename": "parent.qcow2", ... } }} }}<br />
<br />
=== Live creation of a new snapshot ===<br />
<br />
To create a new snapshot out of a running image, run the command:<br />
<br />
{"execute": "blockdev-snapshot-sync", "arguments": {"device": "''devicename''","snapshot-file": "''new_snapshot_name''.qcow2"}}<br />
<br />
This creates an overlay file named {{ic|''new_snapshot_name''.qcow2}} which then becomes the new active layer.<br />
<br />
== Tips and tricks ==<br />
=== Improve virtual machine performance ===<br />
<br />
There are a number of techniques that you can use to improve the performance of the virtual machine. For example:<br />
<br />
* Apply [[#Enabling KVM]]: add {{ic|-enable-kvm}} to the QEMU start command you use.<br />
* Use the {{ic|-cpu host}} option to make QEMU emulate the host's exact CPU. If you do not do this, it may be trying to emulate a more generic CPU.<br />
* Especially for Windows guests, enable [http://blog.wikichoon.com/2014/07/enabling-hyper-v-enlightenments-with-kvm.html Hyper-V enlightenments]: {{ic|1=-cpu host,hv_relaxed,hv_spinlocks=0x1fff,hv_vapic,hv_time}}.<br />
* If the host machine has multiple cores, assign the guest more cores using the {{ic|-smp}} option.<br />
* Make sure you have assigned the virtual machine enough memory. By default, QEMU only assigns 128 MiB of memory to each virtual machine. Use the {{ic|-m}} option to assign more memory. For example, {{ic|-m 1024}} runs a virtual machine with 1024 MiB of memory.<br />
* If supported by drivers in the guest operating system, use [http://wiki.libvirt.org/page/Virtio virtio] for network and/or block devices. For example:<br />
$ qemu-system-x86_64 -net nic,model=virtio -net tap,if=tap0,script=no -drive file=''disk_image'',media=disk,if=virtio<br />
* Use TAP devices instead of user-mode networking. See [[#Tap networking with QEMU]].<br />
* If the guest OS is doing heavy writing to its disk, you may benefit from certain mount options on the host's file system. For example, you can mount an [[Ext4|ext4 file system]] with the option {{ic|1=barrier=0}}. You should read the documentation for any options that you change because sometimes performance-enhancing options for file systems come at the cost of data integrity.<br />
* If you have a raw disk image, you may want to disable the cache:<br />
$ qemu-system-x86_64 -drive file=''disk_image'',if=virtio,'''cache=none'''<br />
* Use the native Linux AIO:<br />
$ qemu-system-x86_64 -drive file=''disk_image'',if=virtio''',aio=native,cache.direct=on'''<br />
* If you are running multiple virtual machines concurrently that all have the same operating system installed, you can save memory by enabling [[wikipedia:Kernel_SamePage_Merging_(KSM)|kernel same-page merging]]. See [[#Enabling KSM]].<br />
* In some cases, memory can be reclaimed from running virtual machines by running a memory ballooning driver in the guest operating system and launching QEMU using {{ic|-device virtio-balloon}}.<br />
* It is possible to use a emulation layer for an ICH-9 AHCI controller (although it may be unstable). The AHCI emulation supports [[Wikipedia:Native_Command_Queuing|NCQ]], so multiple read or write requests can be outstanding at the same time:<br />
$ qemu-system-x86_64 -drive id=disk,file=''disk_image'',if=none -device ich9-ahci,id=ahci -device ide-drive,drive=disk,bus=ahci.0<br />
<br />
See http://www.linux-kvm.org/page/Tuning_KVM for more information.<br />
<br />
=== Starting QEMU virtual machines on boot ===<br />
<br />
==== With libvirt ====<br />
<br />
If a virtual machine is set up with [[libvirt]], it can be configured with {{ic|virsh autostart}} or through the ''virt-manager'' GUI to start at host boot by going to the Boot Options for the virtual machine and selecting "Start virtual machine on host boot up".<br />
<br />
==== With systemd service ====<br />
<br />
To run QEMU VMs on boot, you can use following systemd unit and config.<br />
<br />
{{hc|/etc/systemd/system/qemu@.service|2=<br />
[Unit]<br />
Description=QEMU virtual machine<br />
<br />
[Service]<br />
Environment="haltcmd=kill -INT $MAINPID"<br />
EnvironmentFile=/etc/conf.d/qemu.d/%i<br />
ExecStart=/usr/bin/qemu-system-x86_64 -name %i -enable-kvm -m 512 -nographic $args<br />
ExecStop=/usr/bin/bash -c ${haltcmd}<br />
ExecStop=/usr/bin/bash -c 'while nc localhost 7100; do sleep 1; done'<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
}}<br />
<br />
{{Note|This service will wait for the console port to be released, which means that the VM has been shutdown, to graciously end.}}<br />
<br />
Then create per-VM configuration files, named {{ic|/etc/conf.d/qemu.d/''vm_name''}}, with the variables {{ic|args}} and {{ic|haltcmd}} set. Example configs:<br />
<br />
{{hc|/etc/conf.d/qemu.d/one|2=<br />
args="-hda /dev/vg0/vm1 -serial telnet:localhost:7000,server,nowait,nodelay \<br />
-monitor telnet:localhost:7100,server,nowait,nodelay -vnc :0"<br />
<br />
haltcmd="echo 'system_powerdown' {{!}} nc localhost 7100" # or netcat/ncat}}<br />
<br />
{{hc|/etc/conf.d/qemu.d/two|2=<br />
args="-hda /srv/kvm/vm2 -serial telnet:localhost:7001,server,nowait,nodelay -vnc :1"<br />
<br />
haltcmd="ssh powermanager@vm2 sudo poweroff"}}<br />
<br />
The description of the variables is the following:<br />
<br />
* {{ic|args}} - QEMU command line arguments to be used.<br />
* {{ic|haltcmd}} - Command to shut down a VM safely. In the first example, the QEMU monitor is exposed via telnet using {{ic|-monitor telnet:..}} and the VMs are powered off via ACPI by sending {{ic|system_powerdown}} to monitor with the {{ic|nc}} command. In the other example, SSH is used.<br />
<br />
To set which virtual machines will start on boot-up, [[enable]] the {{ic|qemu@''vm_name''.service}} systemd unit.<br />
<br />
=== Mouse integration ===<br />
<br />
To prevent the mouse from being grabbed when clicking on the guest operating system's window, add the options {{ic|-usb -device usb-tablet}}. This means QEMU is able to report the mouse position without having to grab the mouse. This also overrides PS/2 mouse emulation when activated. For example:<br />
<br />
$ qemu-system-x86_64 -hda ''disk_image'' -m 512 -usb -device usb-tablet<br />
<br />
If that does not work, try using {{ic|-vga qxl}} parameter, also look at the instructions [[#Mouse cursor is jittery or erratic]].<br />
<br />
=== Pass-through host USB device ===<br />
<br />
It is possible to access the physical device connected to a USB port of the host from the guest. The first step is to identify where the device is connected, this can be found running the {{ic|lsusb}} command. For example:<br />
<br />
{{hc|$ lsusb|<br />
...<br />
Bus '''003''' Device '''007''': ID '''0781''':'''5406''' SanDisk Corp. Cruzer Micro U3<br />
}}<br />
<br />
The outputs in bold above will be useful to identify respectively the ''host_bus'' and ''host_addr'' or the ''vendor_id'' and ''product_id''.<br />
<br />
In qemu, the idea is to emulate an EHCI (USB 2) or XHCI (USB 3) controller with the option {{ic|1=-device usb-ehci,id=ehci}} or {{ic|1=-device qemu-xhci,id=xhci}} respectively and then attach the physical device to it with the option {{ic|1=-device usb-host,..}}. We will consider that ''controller_id'' is either {{ic|ehci}} or {{ic|xhci}} for the rest of this section.<br />
<br />
Then, there are two ways to connect to the USB of the host with qemu:<br />
<br />
# Identify the device and connect to it on any bus and address it is attached to on the host, the generic syntax is: {{bc|1=-device usb-host,bus=''controller_id''.0,vendorid=0x''vendor_id'',productid=0x''product_id''}}Applied to the device used in the example above, it becomes:{{bc|1=-device usb-ehci,id=ehci -device usb-host,bus=ehci.0,vendorid=0x'''0781''',productid=0x'''5406'''}}One can also add the {{ic|1=...,port=''port_number''}} setting to the previous option to specify in which physical port of the virtual controller the device should be attached, useful in the case one wants to add multiple usb devices to the VM. Another option is to use the new {{ic|usb-host}} {{ic|hostdevice}} property which is available since QEMU 5.1.0, the syntax is: {{bc|1=-device qemu-xhci,id=xhci -device usb-host,bus=xhci.0,hostdevice=/dev/bus/usb/003/007}}<br />
# Attach whatever is connected to a given USB bus and address, the syntax is:{{bc|1=-device usb-host,bus=''controller_id''.0,hostbus=''host_bus'',host_addr=''host_addr''}}Applied to the bus and the address in the example above, it becomes:{{bc|1=-device usb-ehci,id=ehci -device usb-host,bus=ehci.0,hostbus='''3''',hostaddr='''7'''}}<br />
<br />
{{Note|If you encounter permission errors when running QEMU, see [[udev#About udev rules]] for information on how to set permissions of the device.}}<br />
<br />
=== USB redirection with SPICE ===<br />
<br />
When using [[#SPICE]] it is possible to redirect USB devices from the client to the virtual machine without needing to specify them in the QEMU command. It is possible to configure the number of USB slots available for redirected devices (the number of slots will determine the maximum number of devices which can be redirected simultaneously). The main advantages of using SPICE for redirection compared to the previously-mentioned {{ic|-usbdevice}} method is the possibility of hot-swapping USB devices after the virtual machine has started, without needing to halt it in order to remove USB devices from the redirection or adding new ones. This method of USB redirection also allows us to redirect USB devices over the network, from the client to the server. In summary, it is the most flexible method of using USB devices in a QEMU virtual machine.<br />
<br />
We need to add one EHCI/UHCI controller per available USB redirection slot desired as well as one SPICE redirection channel per slot. For example, adding the following arguments to the QEMU command you use for starting the virtual machine in SPICE mode will start the virtual machine with three available USB slots for redirection:<br />
<br />
{{bc|1=-device ich9-usb-ehci1,id=usb \<br />
-device ich9-usb-uhci1,masterbus=usb.0,firstport=0,multifunction=on \<br />
-device ich9-usb-uhci2,masterbus=usb.0,firstport=2 \<br />
-device ich9-usb-uhci3,masterbus=usb.0,firstport=4 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev1 -device usb-redir,chardev=usbredirchardev1,id=usbredirdev1 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev2 -device usb-redir,chardev=usbredirchardev2,id=usbredirdev2 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev3 -device usb-redir,chardev=usbredirchardev3,id=usbredirdev3}}<br />
See [https://www.spice-space.org/usbredir.html SPICE/usbredir] for more information.<br />
<br />
Both {{ic|spicy}} from {{Pkg|spice-gtk}} (''Input > Select USB Devices for redirection'') and {{ic|remote-viewer}} from {{pkg|virt-viewer}} (''File > USB device selection'') support this feature. Please make sure that you have installed the necessary SPICE Guest Tools on the virtual machine for this functionality to work as expected (see the [[#SPICE]] section for more information).<br />
<br />
{{Warning|Keep in mind that when a USB device is redirected from the client, it will not be usable from the client operating system itself until the redirection is stopped. It is specially important to never redirect the input devices (namely mouse and keyboard), since it will be then difficult to access the SPICE client menus to revert the situation, because the client will not respond to the input devices after being redirected to the virtual machine.}}<br />
<br />
=== Enabling KSM ===<br />
<br />
Kernel Samepage Merging (KSM) is a feature of the Linux kernel that allows for an application to register with the kernel to have its pages merged with other processes that also register to have their pages merged. The KSM mechanism allows for guest virtual machines to share pages with each other. In an environment where many of the guest operating systems are similar, this can result in significant memory savings.<br />
<br />
{{Note|Although KSM may reduce memory usage, it may increase CPU usage. Also note some security issues may occur, see [[Wikipedia:Kernel same-page merging]].}}<br />
<br />
To enable KSM:<br />
<br />
# echo 1 > /sys/kernel/mm/ksm/run<br />
<br />
To make it permanent, use [[systemd#systemd-tmpfiles - temporary files|systemd's temporary files]]:<br />
<br />
{{hc|/etc/tmpfiles.d/ksm.conf|<br />
w /sys/kernel/mm/ksm/run - - - - 1<br />
}}<br />
<br />
If KSM is running, and there are pages to be merged (i.e. at least two similar VMs are running), then {{ic|/sys/kernel/mm/ksm/pages_shared}} should be non-zero. See https://www.kernel.org/doc/html/latest/admin-guide/mm/ksm.html for more information.<br />
<br />
{{Tip|An easy way to see how well KSM is performing is to simply print the contents of all the files in that directory: {{bc|$ grep . /sys/kernel/mm/ksm/*}}}}<br />
<br />
=== Multi-monitor support ===<br />
<br />
The Linux QXL driver supports four heads (virtual screens) by default. This can be changed via the {{ic|1=qxl.heads=N}} kernel parameter.<br />
<br />
The default VGA memory size for QXL devices is 16M (VRAM size is 64M). This is not sufficient if you would like to enable two 1920x1200 monitors since that requires 2 × 1920 × 4 (color depth) × 1200 = 17.6 MiB VGA memory. This can be changed by replacing {{ic|-vga qxl}} by {{ic|<nowiki>-vga none -device qxl-vga,vgamem_mb=32</nowiki>}}. If you ever increase vgamem_mb beyond 64M, then you also have to increase the {{ic|vram_size_mb}} option.<br />
<br />
=== Copy and paste ===<br />
<br />
One way to share the clipboard between the host and the guest is to enable the SPICE remote desktop protocol and access the client with a SPICE client.<br />
One needs to follow the steps described in [[#SPICE]]. A guest run this way will support copy paste with the host.<br />
<br />
=== Windows-specific notes ===<br />
<br />
QEMU can run any version of Windows from Windows 95 through Windows 10.<br />
<br />
It is possible to run [[Windows PE]] in QEMU.<br />
<br />
==== Fast startup ====<br />
<br />
{{Note|An administrator account is required to change power settings.}}<br />
<br />
For Windows 8 (or later) guests it is better to disable "Turn on fast startup (recommended)" from the Power Options of the Control Panel as explained in the following [https://www.tenforums.com/tutorials/4189-turn-off-fast-startup-windows-10-a.html forum page], as it causes the guest to hang during every other boot.<br />
<br />
Fast Startup may also need to be disabled for changes to the {{ic|-smp}} option to be properly applied.<br />
<br />
==== Remote Desktop Protocol ====<br />
<br />
If you use a MS Windows guest, you might want to use RDP to connect to your guest VM. If you are using a VLAN or are not in the same network as the guest, use:<br />
<br />
$ qemu-system-x86_64 -nographic -net user,hostfwd=tcp::5555-:3389<br />
<br />
Then connect with either {{Pkg|rdesktop}} or {{Pkg|freerdp}} to the guest. For example:<br />
<br />
$ xfreerdp -g 2048x1152 localhost:5555 -z -x lan<br />
<br />
=== Clone Linux system installed on physical equipment ===<br />
<br />
Linux system installed on physical equipment can be cloned for running on QEMU vm. See [https://coffeebirthday.wordpress.com/2018/09/14/clone-linux-system-for-qemu-virtual-machine/ Clone Linux system from hardware for QEMU virtual machine]<br />
<br />
=== Chrooting into arm/arm64 environment from x86_64 ===<br />
<br />
Sometimes it is easier to work directly on a disk image instead of the real ARM based device. This can be achieved by mounting an SD card/storage containing the ''root'' partition and chrooting into it.<br />
<br />
Another use case for an ARM chroot is building ARM packages on an x86_64 machine - {{AUR|armutils-git}} can be used for that. Here, the chroot environment can be created from an image tarball from [https://archlinuxarm.org Arch Linux ARM] - see [https://nerdstuff.org/posts/2020/2020-003_simplest_way_to_create_an_arm_chroot/] for a detailed description of this approach.<br />
<br />
Either way, from the chroot it should be possible to run ''pacman'' and install more packages, compile large libraries etc. Since the executables are for the ARM architecture, the translation to x86 needs to be performed by [[QEMU]].<br />
<br />
Install {{AUR|binfmt-qemu-static}} and {{AUR|qemu-user-static}} from the [[AUR]] on the x86_64 machine/host. ''binfmt-qemu-static'' will take care of registering the qemu binaries to binfmt service.<br />
<br />
[[Restart]] {{ic|systemd-binfmt.service}}<br />
<br />
{{AUR|qemu-user-static}} is needed to allow the execution of compiled programs from other architectures. This is similar to what is provided by {{Pkg|qemu-arch-extra}}, but the "static" variant is required for chroot. Examples:<br />
<br />
qemu-arm-static path_to_sdcard/usr/bin/ls<br />
qemu-aarch64-static path_to_sdcard/usr/bin/ls<br />
<br />
These two lines execute the {{ic|ls}} command compiled for 32-bit ARM and 64-bit ARM respectively. Note that this will not work without chrooting, because it will look for libraries not present in the host system.<br />
<br />
{{AUR|qemu-user-static}} allows automatically prefixing the ARM exectuable with {{ic|qemu-arm-static}} or {{ic|qemu-aarch64-static}}.<br />
<br />
Make sure that the ARM executable support is active:<br />
<br />
{{hc|$ ls /proc/sys/fs/binfmt_misc|<br />
qemu-aarch64 qemu-arm qemu-cris qemu-microblaze qemu-mipsel qemu-ppc64 qemu-riscv64 qemu-sh4 qemu-sparc qemu-sparc64 status<br />
qemu-alpha qemu-armeb qemu-m68k qemu-mips qemu-ppc qemu-ppc64abi32 qemu-s390x qemu-sh4eb qemu-sparc32plus register<br />
}}<br />
<br />
Each executable must be listed.<br />
<br />
If it is not active, reinstall ''binfmt-qemu-static'' and restart ''systemd-binfmt''.<br />
<br />
Mount the SD card to {{ic|/mnt/scdard}} (the device name may be different).<br />
<br />
# mkdir -p /mnt/sdcard<br />
# mount /dev/mmcblk0p2 /mnt/sdcard<br />
<br />
Mount boot partition if needed (again, use the suitable device name):<br />
<br />
# mount /dev/mmcblk0p1 /mnt/sdcard/boot<br />
<br />
Finally ''chroot'' into the SD card root as described in [[Change root#Using chroot]]:<br />
<br />
# chroot /mnt/sdcard /bin/bash<br />
<br />
Alternatively, you can use ''arch-chroot'' from {{Pkg|arch-install-scripts}}, as it will provide an easier way to get network support:<br />
# arch-chroot /mnt/sdcard /bin/bash<br />
<br />
You can also use ''systemd-nspawn'' to chroot into the ARM environment:<br />
# systemd-nspawn -D /mnt/sdcard -M myARMMachine --bind-ro=/etc/resolv.conf<br />
<br />
{{ic|1=--bind-ro=/etc/resolv.conf}} is optional and gives a working network DNS inside the chroot<br />
<br />
== Troubleshooting ==<br />
<br />
=== Mouse cursor is jittery or erratic ===<br />
<br />
If the cursor jumps around the screen uncontrollably, entering this on the terminal before starting QEMU might help:<br />
<br />
$ export SDL_VIDEO_X11_DGAMOUSE=0<br />
<br />
If this helps, you can add this to your {{ic|~/.bashrc}} file.<br />
<br />
=== No visible Cursor ===<br />
<br />
Add {{ic|-show-cursor}} to QEMU's options to see a mouse cursor.<br />
<br />
If that still does not work, make sure you have set your display device appropriately, for example: {{ic|-vga qxl}}.<br />
<br />
Another option to try is {{ic|-usb -device usb-tablet}} as mentioned in [[#Mouse integration]]. This overrides the default PS/2 mouse emulation and synchronizes pointer location between host and guest as an added bonus.<br />
<br />
=== Two different mouse cursors are visible ===<br />
<br />
Apply the tip [[#Mouse integration]].<br />
<br />
=== Keyboard issues when using VNC ===<br />
<br />
When using VNC, you might experience keyboard problems described (in gory details) [https://www.berrange.com/posts/2010/07/04/more-than-you-or-i-ever-wanted-to-know-about-virtual-keyboard-handling/ here]. The solution is ''not'' to use the {{ic|-k}} option on QEMU, and to use {{ic|gvncviewer}} from {{Pkg|gtk-vnc}}. See also [http://www.mail-archive.com/libvir-list@redhat.com/msg13340.html this] message posted on libvirt's mailing list.<br />
<br />
=== Keyboard seems broken or the arrow keys do not work ===<br />
<br />
Should you find that some of your keys do not work or "press" the wrong key (in particular, the arrow keys), you likely need to specify your keyboard layout as an option. The keyboard layouts can be found in {{ic|/usr/share/qemu/keymaps}}.<br />
<br />
$ qemu-system-x86_64 -k ''keymap'' ''disk_image''<br />
<br />
=== Guest display stretches on window resize ===<br />
<br />
To restore default window size, press {{ic|Ctrl+Alt+u}}.<br />
<br />
=== ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy ===<br />
<br />
If an error message like this is printed when starting QEMU with {{ic|-enable-kvm}} option:<br />
<br />
ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy<br />
failed to initialize KVM: Device or resource busy<br />
<br />
that means another [[hypervisor]] is currently running. It is not recommended or possible to run several hypervisors in parallel.<br />
<br />
=== libgfapi error message ===<br />
<br />
The error message displayed at startup:<br />
<br />
Failed to open module: libgfapi.so.0: cannot open shared object file: No such file or directory<br />
<br />
[[Install]] {{pkg|glusterfs}} or ignore the error message as GlusterFS is a optional dependency.<br />
<br />
=== Kernel panic on LIVE-environments===<br />
<br />
If you start a live-environment (or better: booting a system) you may encounter this:<br />
<br />
[ end Kernel panic - not syncing: VFS: Unable to mount root fs on unknown block(0,0)<br />
<br />
or some other boot hindering process (e.g. cannot unpack initramfs, cant start service foo).<br />
Try starting the VM with the {{ic|-m VALUE}} switch and an appropriate amount of RAM, if the ram is to low you will probably encounter similar issues as above/without the memory-switch.<br />
<br />
=== Windows 7 guest suffers low-quality sound ===<br />
<br />
Using the {{ic|hda}} audio driver for Windows 7 guest may result in low-quality sound. Changing the audio driver to {{ic|ac97}} by passing the {{ic|-soundhw ac97}} arguments to QEMU and installing the AC97 driver from [https://www.realtek.com/en/component/zoo/category/pc-audio-codecs-ac-97-audio-codecs-software Realtek AC'97 Audio Codecs] in the guest may solve the problem. See [https://bugzilla.redhat.com/show_bug.cgi?id=1176761#c16 Red Hat Bugzilla – Bug 1176761] for more information.<br />
<br />
=== Could not access KVM kernel module: Permission denied ===<br />
<br />
If you encounter the following error:<br />
<br />
libvirtError: internal error: process exited while connecting to monitor: Could not access KVM kernel module: Permission denied failed to initialize KVM: Permission denied<br />
<br />
Systemd 234 assigns a dynamic ID for the {{ic|kvm}} group (see {{Bug|54943}}). To avoid this error, you need edit the file {{ic|/etc/libvirt/qemu.conf}} and change the line with {{ic|1=group = "78"}} to {{ic|1=group = "kvm"}}.<br />
<br />
=== "System Thread Exception Not Handled" when booting a Windows VM ===<br />
<br />
Windows 8 or Windows 10 guests may raise a generic compatibility exception at boot, namely "System Thread Exception Not Handled", which tends to be caused by legacy drivers acting strangely on real machines. On KVM machines this issue can generally be solved by setting the CPU model to {{ic|core2duo}}.<br />
<br />
=== Certain Windows games/applications crashing/causing a bluescreen ===<br />
<br />
Occasionally, applications running in the VM may crash unexpectedly, whereas they would run normally on a physical machine. If, while running {{ic|dmesg -wH}}, you encounter an error mentioning {{ic|MSR}}, the reason for those crashes is that KVM injects a [[wikipedia:General protection fault|General protection fault]] (GPF) when the guest tries to access unsupported [[wikipedia:Model-specific register|Model-specific registers]] (MSRs) - this often results in guest applications/OS crashing. A number of those issues can be solved by passing the {{ic|1=ignore_msrs=1}} option to the KVM module, which will ignore unimplemented MSRs.<br />
<br />
{{hc|/etc/modprobe.d/kvm.conf|2=<br />
...<br />
options kvm ignore_msrs=1<br />
...<br />
}}<br />
<br />
Cases where adding this option might help:<br />
<br />
* GeForce Experience complaining about an unsupported CPU being present.<br />
* StarCraft 2 and L.A. Noire reliably blue-screening Windows 10 with {{ic|KMODE_EXCEPTION_NOT_HANDLED}}. The blue screen information does not identify a driver file in these cases.<br />
<br />
{{Warning|While this is normally safe and some applications might not work without this, silently ignoring unknown MSR accesses could potentially break other software within the VM or other VMs.}}<br />
<br />
=== Applications in the VM experience long delays or take a long time to start ===<br />
<br />
This may be caused by insufficient available entropy in the VM. Consider allowing the guest to access the hosts's entropy pool by adding a [https://wiki.qemu.org/Features/VirtIORNG VirtIO RNG device] to the VM, or by installing an entropy generating daemon such as [[Haveged]].<br />
<br />
Anecdotally, OpenSSH takes a while to start accepting connections under insufficient entropy, without the logs revealing why.<br />
<br />
=== High interrupt latency and microstuttering ===<br />
<br />
This problem manifests itself as small pauses (stutters) and is particularly noticeable in graphics-intensive applications, such as games.<br />
<br />
* One of the causes is CPU power saving features, which are controlled by [[CPU frequency scaling]]. Change this to {{ic|performance}} for all processor cores. <br />
* Another possible cause is PS/2 inputs. Switch from PS/2 to Virtio inputs, see [[PCI passthrough via OVMF#Passing keyboard/mouse via Evdev]].<br />
<br />
=== QXL video causes low resolution ===<br />
<br />
QEMU 4.1.0 introduced a regression where QXL video can fall back to low resolutions, when being displayed through spice. [https://bugs.launchpad.net/qemu/+bug/1843151] For example, when KMS starts, text resolution may become as low as 4x10 characters. When trying to increase GUI resolution, it may go to the lowest supported resolution.<br />
<br />
As a workaround, create your device in this form:<br />
<br />
-device qxl-vga,max_outputs=1...<br />
<br />
=== Hang during VM initramfs ===<br />
<br />
Linux 5.2.11 introduced a KVM regression where under some circumstances a VM may permanently hang during the early boot phase, when the initramfs is being loaded or ran. [https://www.spinics.net/lists/kvm/msg195171.html] Linux 5.3 fixed the regression. The host shows qemu using 100% CPU * number of virtual CPUs. Reported case is with a host using hyperthreading, and a VM being given more than host's {{ic|nproc}}/2 virtual CPUs. It is unknown what exact circumstances trigger one of the threads to delete a memory region to cause this. The workarounds are:<br />
<br />
* Upgrade to Linux 5.3.<br />
* Downgrade to Linux 5.2.10<br />
* Until fixed, try giving the VM no more than the host's {{ic|nproc}}/2 virtual CPUs<br />
* Custom compile linux, reverting commit 2ad350fb4c (note this re-introduces a regression triggered when removing a memslot)<br />
<br />
=== VM does not boot when using a Secure Boot enabled OVMF ===<br />
<br />
{{ic|/usr/share/edk2-ovmf/x64/OVMF_CODE.secboot.fd}} from {{Pkg|edk2-ovmf}} is built with [[Wikipedia:System Management Mode|SMM]] support. If S3 support is not disabled in the VM, then the VM might not boot at all.<br />
<br />
Add the {{ic|1=-global ICH9-LPC.disable_s3=1}} option to the ''qemu'' command.<br />
<br />
See {{Bug|59465}} and https://github.com/tianocore/edk2/blob/master/OvmfPkg/README for more details and the required options to use Secure Boot in QEMU.<br />
<br />
=== Guest CPU interrupts are not firing ===<br />
<br />
If you are writing your own operating system by following the [https://wiki.osdev.org/ OSDev wiki], or are simply getting stepping through the guest architecture assembly code using QEMU's {{ic|gdb}} interface using the {{ic|-s}} flag, it's useful to know that many emulators, QEMU included, usually implement some CPU interrupts leaving many hardware interrupts unimplemented. One way to know if your code if firing an interrupt, is by using:<br />
<br />
-d int<br />
<br />
to enable showing interrupts/exceptions on stdout.<br />
<br />
To see what other guest debugging features QEMU has to offer, see:<br />
<br />
qemu-system-x86_64 -d help<br />
<br />
or replace {{ic|x86_64}} for your chosen guest architecture.<br />
<br />
== See also ==<br />
<br />
* [http://qemu.org Official QEMU website]<br />
* [http://www.linux-kvm.org Official KVM website]<br />
* [http://qemu.weilnetz.de/qemu-doc.html QEMU Emulator User Documentation]<br />
* [[Wikibooks:QEMU|QEMU Wikibook]]<br />
* [http://alien.slackbook.org/dokuwiki/doku.php?id=slackware:qemu Hardware virtualization with QEMU] by AlienBOB (last updated in 2008)<br />
* [http://blog.falconindy.com/articles/build-a-virtual-army.html Building a Virtual Army] by Falconindy<br />
* [http://git.qemu.org/?p=qemu.git;a=tree;f=docs Lastest docs]<br />
* [http://qemu.weilnetz.de/ QEMU on Windows]<br />
* [[wikipedia:Qemu|Wikipedia]]<br />
* [[debian:QEMU|Debian Wiki - QEMU]]<br />
* [https://people.gnome.org/~markmc/qemu-networking.html QEMU Networking on gnome.org]<br />
* [http://bsdwiki.reedmedia.net/wiki/networking_qemu_virtual_bsd_systems.html Networking QEMU Virtual BSD Systems]<br />
* [https://www.gnu.org/software/hurd/hurd/running/qemu.html QEMU on gnu.org]<br />
* [https://wiki.freebsd.org/qemu QEMU on FreeBSD as host]<br />
* [https://wiki.mikejung.biz/KVM_/_Xen KVM/QEMU Virtio Tuning and SSD VM Optimization Guide]<br />
* [https://doc.opensuse.org/documentation/leap/virtualization/html/book-virt/part-virt-qemu.html Managing Virtual Machines with QEMU - openSUSE documentation]<br />
* [https://www.ibm.com/support/knowledgecenter/en/linuxonibm/liaat/liaatkvm.htm KVM on IBM Knowledge Center]</div>Malcontenthttps://wiki.archlinux.org/index.php?title=QEMU&diff=634640QEMU2020-09-08T07:26:00Z<p>Malcontent: '-soundhw hda' is deprecated (QEMU 5.1.0)</p>
<hr />
<div>[[Category:Emulation]]<br />
[[Category:Hypervisors]]<br />
[[de:Qemu]]<br />
[[es:QEMU]]<br />
[[fr:Qemu]]<br />
[[ja:QEMU]]<br />
[[zh-hans:QEMU]]<br />
[[zh-hant:QEMU]]<br />
{{Related articles start}}<br />
{{Related|:Category:Hypervisors}}<br />
{{Related|Libvirt}}<br />
{{Related|QEMU/Guest graphics acceleration}}<br />
{{Related|PCI passthrough via OVMF}}<br />
{{Related articles end}}<br />
<br />
According to the [http://wiki.qemu.org/Main_Page QEMU about page], "QEMU is a generic and open source machine emulator and virtualizer."<br />
<br />
When used as a machine emulator, QEMU can run OSes and programs made for one machine (e.g. an ARM board) on a different machine (e.g. your x86 PC). By using dynamic translation, it achieves very good performance.<br />
<br />
QEMU can use other hypervisors like [[Xen]] or [[KVM]] to use CPU extensions ([[Wikipedia:Hardware-assisted virtualization|HVM]]) for virtualization. When used as a virtualizer, QEMU achieves near native performances by executing the guest code directly on the host CPU.<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|qemu}} package (or {{Pkg|qemu-headless}} for the version without GUI) and below optional packages for your needs:<br />
<br />
* {{Pkg|qemu-arch-extra}} - extra architectures support<br />
* {{Pkg|qemu-block-gluster}} - [[Glusterfs]] block support<br />
* {{Pkg|qemu-block-iscsi}} - [[iSCSI]] block support<br />
* {{Pkg|qemu-block-rbd}} - RBD block support <br />
* {{Pkg|samba}} - [[Samba|SMB/CIFS]] server support<br />
<br />
Alternatively, {{AUR|qemu-user-static}} exists as a usermode and static variant.<br />
<br />
=== QEMU variants ===<br />
<br />
QEMU is offered in several variants suited for different use cases.<br />
<br />
As a first classification, QEMU is offered in full-system and usermode emulation modes:<br />
<br />
; Full-system emulation<br />
: In this mode, QEMU emulates a full system, including one or several processors and various peripherals. It is more accurate but slower, and does not require the emulated OS to be Linux.<br />
: QEMU commands for full-system emulation are named {{ic|qemu-system-''target_architecture''}}, e.g. {{ic|qemu-system-x86_64}} for emulating intel 64-bit CPUs, {{ic|qemu-system-i386}} for intel 32 bits CPUs, {{ic|qemu-system-arm}} for ARM (32 bits), {{ic|qemu-system-aarch64}} for ARM64, etc.<br />
: If the target architecture matches the host CPU, this mode may still benefit from a significant speedup by using a hypervisor like [[#Enabling KVM|KVM]] or Xen.<br />
; [https://www.qemu.org/docs/master/user/main.html Usermode emulation]: In this mode, QEMU is able to invoke a Linux executable compiled for a (potentially) different architecture by leveraging the host system resources. There may be compatibility issues, e.g. some features may not be implemented, dynamically linked executables will not work out of the box (see [[#Chrooting into arm/arm64 environment from x86_64|the section below]] to address this) and only Linux is supported (although [https://wiki.winehq.org/Emulation Wine may be used] for running Windows executables).<br />
: QEMU commands for usermode emulation are named {{ic|qemu-''target_architecture''}}, e.g. {{ic|qemu-x86_64}} for emulating intel 64-bit CPUs.<br />
<br />
QEMU is offered in dynamically-linked and statically-linked variants:<br />
<br />
; Dynamically-linked (default): {{ic|qemu-*}} commands depend on the host OS libraries, so executables are smaller.<br />
; Statically-linked: {{ic|qemu-*}} commands can be copied to any Linux system with the same architecture.<br />
<br />
In the case of Arch Linux, full-system emulation is offered as:<br />
<br />
; Non-headless (default): This variant enables GUI features that require additional dependencies (like SDL or GTK).<br />
; Headless: This is a slimmer variant that does not require GUI (this is suitable e.g. for servers).<br />
<br />
Note that headless and non-headless versions install commands with the same name (e.g. {{ic|qemu-system-x86_64}}) and thus cannot be both installed at the same time.<br />
<br />
=== Details on packages offered in Arch Linux ===<br />
<br />
* The {{Pkg|qemu}} package provides the {{ic|x86_64}} architecture emulators for full-system emulation ({{ic|qemu-system-x86_64}}). The {{Pkg|qemu-arch-extra}} package provides the {{ic|x86_64}} usermode variant ({{ic|qemu-x86_64}}) and also for the rest of supported architectures it includes both full-system and usermode variants (e.g. {{ic|qemu-system-arm}} and {{ic|qemu-arm}}).<br />
* The headless versions of these packages (only applicable to full-system emulation) are {{Pkg|qemu-headless}} ({{ic|x86_64}}-only) and {{Pkg|qemu-headless-arch-extra}} (rest of architectures).<br />
* Full-system emulation can be expanded with some QEMU modules present in separate packages: {{Pkg|qemu-block-gluster}}, {{Pkg|qemu-block-iscsi}}, {{Pkg|qemu-block-rbd}} and {{Pkg|qemu-guest-agent}}.<br />
* The unofficial AUR package {{AUR|qemu-user-static}} provides a usermode and static variant for all target architectures supported by QEMU. A precompiled version of this package exists: {{AUR|qemu-user-static-bin}}. The installed QEMU commands are named {{ic|qemu-''target_architecture''-static}}, for example, {{ic|qemu-x86_64-static}} for intel 64-bit CPUs.<br />
<br />
{{Note|At present, Arch does not offer a full-system mode and statically linked variant (neither officially nor via AUR), as this is usually not needed.}}<br />
<br />
== Graphical front-ends for QEMU ==<br />
<br />
Unlike other virtualization programs such as [[VirtualBox]] and [[VMware]], QEMU does not provide a GUI to manage virtual machines (other than the window that appears when running a virtual machine), nor does it provide a way to create persistent virtual machines with saved settings. All parameters to run a virtual machine must be specified on the command line at every launch, unless you have created a custom script to start your virtual machine(s).<br />
<br />
[[Libvirt]] provides a convenient way to manage QEMU virtual machines. See [[Libvirt#Client|list of libvirt clients]] for available front-ends.<br />
<br />
Other GUI front-ends for QEMU:<br />
<br />
* {{App|AQEMU|QEMU GUI written in Qt5.|https://github.com/tobimensch/aqemu|{{AUR|aqemu}}}}<br />
<br />
== Creating new virtualized system ==<br />
<br />
=== Creating a hard disk image ===<br />
<br />
{{Accuracy|If I get the man page right the raw format only allocates the full size if the filesystem does not support "holes" or it is <br />
explicitly told to preallocate. See man qemu-img in section Notes.}} <br />
<br />
{{Tip|See [[Wikibooks:QEMU/Images]] for more information on QEMU images.}}<br />
<br />
To run QEMU you will need a hard disk image, unless you are booting a live system from CD-ROM or the network (and not doing so to install an operating system to a hard disk image). A hard disk image is a file which stores the contents of the emulated hard disk.<br />
<br />
A hard disk image can be ''raw'', so that it is literally byte-by-byte the same as what the guest sees, and will always use the full capacity of the guest hard drive on the host. This method provides the least I/O overhead, but can waste a lot of space, as not-used space on the guest cannot be used on the host.<br />
<br />
Alternatively, the hard disk image can be in a format such as ''qcow2'' which only allocates space to the image file when the guest operating system actually writes to those sectors on its virtual hard disk. The image appears as the full size to the guest operating system, even though it may take up only a very small amount of space on the host system. This image format also supports QEMU snapshotting functionality (see [[#Creating and managing snapshots via the monitor console]] for details). However, using this format instead of ''raw'' will likely affect performance.<br />
<br />
QEMU provides the {{ic|qemu-img}} command to create hard disk images. For example to create a 4 GB image in the ''raw'' format:<br />
<br />
$ qemu-img create -f raw ''image_file'' 4G<br />
<br />
You may use {{ic|-f qcow2}} to create a ''qcow2'' disk instead.<br />
<br />
{{Note|You can also simply create a ''raw'' image by creating a file of the needed size using {{ic|dd}} or {{ic|fallocate}}.}}<br />
<br />
{{Warning|If you store the hard disk images on a [[Btrfs]] file system, you should consider disabling [[Btrfs#Copy-on-Write (CoW)|Copy-on-Write]] for the directory before creating any images.}}<br />
<br />
==== Overlay storage images ====<br />
<br />
You can create a storage image once (the 'backing' image) and have QEMU keep mutations to this image in an overlay image. This allows you to revert to a previous state of this storage image. You could revert by creating a new overlay image at the time you wish to revert, based on the original backing image.<br />
<br />
To create an overlay image, issue a command like:<br />
<br />
$ qemu-img create -o backing_file=''img1.raw'',backing_fmt=''raw'' -f ''qcow2'' ''img1.cow''<br />
<br />
After that you can run your QEMU VM as usual (see [[#Running virtualized system]]):<br />
<br />
$ qemu-system-x86_64 ''img1.cow''<br />
<br />
The backing image will then be left intact and mutations to this storage will be recorded in the overlay image file.<br />
<br />
When the path to the backing image changes, repair is required.<br />
<br />
{{Warning|The backing image's absolute filesystem path is stored in the (binary) overlay image file. Changing the backing image's path requires some effort.}}<br />
<br />
Make sure that the original backing image's path still leads to this image. If necessary, make a symbolic link at the original path to the new path. Then issue a command like:<br />
<br />
$ qemu-img rebase -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
At your discretion, you may alternatively perform an 'unsafe' rebase where the old path to the backing image is not checked:<br />
<br />
$ qemu-img rebase -u -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
==== Resizing an image ====<br />
<br />
{{Warning|Resizing an image containing an NTFS boot file system could make the operating system installed on it unbootable. It is recommended to create a backup first.}}<br />
<br />
The {{ic|qemu-img}} executable has the {{ic|resize}} option, which enables easy resizing of a hard drive image. It works for both ''raw'' and ''qcow2''. For example, to increase image space by 10 GB, run:<br />
<br />
$ qemu-img resize ''disk_image'' +10G<br />
<br />
After enlarging the disk image, you must use file system and partitioning tools inside the virtual machine to actually begin using the new space. When shrinking a disk image, you must '''first reduce the allocated file systems and partition sizes''' using the file system and partitioning tools inside the virtual machine and then shrink the disk image accordingly, otherwise shrinking the disk image will result in data loss! For a Windows guest, open the "create and format hard disk partitions" control panel.<br />
<br />
==== Converting an image ====<br />
<br />
You can convert an image to other formats using {{ic|qemu-img convert}}. This example shows how to convert a ''raw'' image to ''qcow2'':<br />
<br />
$ qemu-img convert -f raw -O qcow2 ''input''.img ''output''.qcow2<br />
<br />
This will not remove the original input file.<br />
<br />
=== Preparing the installation media ===<br />
<br />
To install an operating system into your disk image, you need the installation medium (e.g. optical disk, USB-drive, or ISO image) for the operating system. The installation medium should not be mounted because QEMU accesses the media directly.<br />
<br />
{{Tip|If using an optical disk, it is a good idea to first dump the media to a file because this both improves performance and does not require you to have direct access to the devices (that is, you can run QEMU as a regular user without having to change access permissions on the media's device file). For example, if the CD-ROM device node is named {{ic|/dev/cdrom}}, you can dump it to a file with the command: {{bc|1=$ dd if=/dev/cdrom of=''cd_image.iso'' bs=4k}}}}<br />
<br />
=== Installing the operating system ===<br />
<br />
This is the first time you will need to start the emulator. To install the operating system on the disk image, you must attach both the disk image and the installation media to the virtual machine, and have it boot from the installation media.<br />
<br />
For example on i386 guests, to install from a bootable ISO file as CD-ROM and a raw disk image:<br />
<br />
$ qemu-system-x86_64 -cdrom ''iso_image'' -boot order=d -drive file=''disk_image'',format=raw<br />
<br />
See {{man|1|qemu}} for more information about loading other media types (such as floppy, disk images or physical drives) and [[#Running virtualized system]] for other useful options.<br />
<br />
After the operating system has finished installing, the QEMU image can be booted directly (see [[#Running virtualized system]]).<br />
<br />
{{Note|By default only 128 MB of memory is assigned to the machine. The amount of memory can be adjusted with the {{ic|-m}} switch, for example {{ic|-m 512M}} or {{ic|-m 2G}}.}}<br />
<br />
{{Tip|<br />
* Instead of specifying {{ic|1=-boot order=x}}, some users may feel more comfortable using a boot menu: {{ic|1=-boot menu=on}}, at least during configuration and experimentation.<br />
* When running QEMU in headless mode, it starts a local VNC server on port 5900 per default. You can use [[TigerVNC]] to connect to the guest OS: {{ic|vncviewer :5900}}<br />
* If you need to replace floppies or CDs as part of the installation process, you can use the QEMU machine monitor (press {{ic|Ctrl+Alt+2}} in the virtual machine's window) to remove and attach storage devices to a virtual machine. Type {{ic|info block}} to see the block devices, and use the {{ic|change}} command to swap out a device. Press {{ic|Ctrl+Alt+1}} to go back to the virtual machine.<br />
}}<br />
<br />
== Running virtualized system ==<br />
<br />
{{ic|qemu-system-*}} binaries (for example {{ic|qemu-system-i386}} or {{ic|qemu-system-x86_64}}, depending on guest's architecture) are used to run the virtualized guest. The usage is:<br />
<br />
$ qemu-system-x86_64 ''options'' ''disk_image''<br />
<br />
Options are the same for all {{ic|qemu-system-*}} binaries, see {{man|1|qemu}} for documentation of all options.<br />
<br />
By default, QEMU will show the virtual machine's video output in a window. One thing to keep in mind: when you click inside the QEMU window, the mouse pointer is grabbed. To release it, press {{ic|Ctrl+Alt+g}}.<br />
<br />
{{Warning|QEMU should never be run as root. If you must launch it in a script as root, you should use the {{ic|-runas}} option to make QEMU drop root privileges.}}<br />
<br />
=== Enabling KVM ===<br />
<br />
KVM (''Kernel-based Virtual Machine'') full virtualization must be supported by your Linux kernel and your hardware, and necessary [[kernel modules]] must be loaded. See [[KVM]] for more information.<br />
<br />
To start QEMU in KVM mode, append {{ic|-enable-kvm}} to the additional start options. To check if KVM is enabled for a running VM, enter the [[#QEMU monitor]] and type {{ic|info kvm}}.<br />
<br />
{{Note|<br />
* The argument {{ic|1=accel=kvm}} of the {{ic|-machine}} option is equivalent to the {{ic|-enable-kvm}} or the {{ic|-accel kvm}} option.<br />
* CPU model {{ic|host}} requires KVM<br />
* If you start your VM with a GUI tool and experience very bad performance, you should check for proper KVM support, as QEMU may be falling back to software emulation.<br />
* KVM needs to be enabled in order to start Windows 7 and Windows 8 properly without a ''blue screen''.<br />
}}<br />
<br />
=== Enabling IOMMU (Intel VT-d/AMD-Vi) support ===<br />
<br />
First enable IOMMU, see [[PCI passthrough via OVMF#Setting up IOMMU]].<br />
<br />
Add {{ic|-device intel-iommu}} to create the IOMMU device:<br />
<br />
$ qemu-system-x86_64 '''-enable-kvm -machine q35 -device intel-iommu''' -cpu host ..<br />
<br />
{{Note|<br />
On Intel CPU based systems creating an IOMMU device in a QEMU guest with {{ic|-device intel-iommu}} will disable PCI passthrough with an error like: {{bc|Device at bus pcie.0 addr 09.0 requires iommu notifier which is currently not supported by intel-iommu emulation}} While adding the kernel parameter {{ic|1=intel_iommu=on}} is still needed for remapping IO (e.g. [[PCI passthrough via OVMF#Isolating the GPU|PCI passthrough with vfio-pci]]), {{ic|-device intel-iommu}} should not be set if PCI PCI passthrough is required.<br />
}}<br />
<br />
== Sharing data between host and guest ==<br />
<br />
=== Network ===<br />
<br />
Data can be shared between the host and guest OS using any network protocol that can transfer files, such as [[NFS]], [[SMB]], [[Wikipedia:Network block device|NBD]], HTTP, [[Very Secure FTP Daemon|FTP]], or [[SSH]], provided that you have set up the network appropriately and enabled the appropriate services.<br />
<br />
The default user-mode networking allows the guest to access the host OS at the IP address 10.0.2.2. Any servers that you are running on your host OS, such as a SSH server or SMB server, will be accessible at this IP address. So on the guests, you can mount directories exported on the host via [[SMB]] or [[NFS]], or you can access the host's HTTP server, etc.<br />
It will not be possible for the host OS to access servers running on the guest OS, but this can be done with other network configurations (see [[#Tap networking with QEMU]]).<br />
<br />
=== QEMU's port forwarding ===<br />
<br />
QEMU can forward ports from the host to the guest to enable e.g. connecting from the host to an SSH server running on the guest.<br />
<br />
For example, to bind port 10022 on the host with port 22 (SSH) on the guest, start QEMU with a command like:<br />
<br />
$ qemu-system-x86_64 ''disk_image'' -nic user,hostfwd=tcp::10022-:22<br />
<br />
Make sure the sshd is running on the guest and connect with:<br />
<br />
$ ssh ''guest-user''@localhost -p 10022<br />
<br />
You can use [[SSHFS]] to mount the guest's file system at the host for shared read and write access.<br />
<br />
=== QEMU's built-in SMB server ===<br />
<br />
QEMU's documentation says it has a "built-in" SMB server, but actually it just starts up [[Samba]] on the host with an automatically generated {{ic|smb.conf}} file located in {{ic|/tmp/qemu-smb.''random_string''}} and makes it accessible to the guest at a different IP address (10.0.2.4 by default). This only works for user networking, and is useful when you do not want to start the normal [[Samba]] service on the host, which the guest can also access if you have set up shares on it.<br />
<br />
Only a single directory can be set as shared with the option {{ic|1=smb=}}, but adding more directories (even while the virtual machine is running) could be as easy as creating symbolic links in the shared directory if QEMU configured SMB to follow symbolic links. It does not do so, but the configuration of the running SMB server can be changed as described below.<br />
<br />
''Samba'' must be installed on the host. To enable this feature, start QEMU with a command like:<br />
<br />
$ qemu-system-x86_64 ''disk_image'' -net nic -net user,smb=''shared_dir_path''<br />
<br />
where {{ic|''shared_dir_path''}} is a directory that you want to share between the guest and host.<br />
<br />
Then, in the guest, you will be able to access the shared directory on the host 10.0.2.4 with the share name "qemu". For example, in Windows Explorer you would go to {{ic|\\10.0.2.4\qemu}}.<br />
<br />
{{Note|<br />
* If you are using sharing options multiple times like {{ic|1=-net user,smb=''shared_dir_path1'' -net user,smb=''shared_dir_path2''}} or {{ic|1=-net user,smb=''shared_dir_path1'',smb=''shared_dir_path2''}} then it will share only the last defined one.<br />
* If you cannot access the shared folder and the guest system is Windows, check that the [http://ecross.mvps.org/howto/enable-netbios-over-tcp-ip-with-windows.htm NetBIOS protocol is enabled] and that a firewall does not block [https://technet.microsoft.com/en-us/library/cc940063.aspx ports] used by the NetBIOS protocol.<br />
* If you cannot access the shared folder and the guest system is Windows 10 Enterprise or Education or Windows Server 2016, [https://support.microsoft.com/en-us/help/4046019 enable guest access].<br />
}}<br />
<br />
One way to share multiple directories and to add or remove them while the virtual machine is running, is to share an empty directory and create/remove symbolic links to the directories in the shared directory. For this to work, the configuration of the running SMB server can be changed with the following script, which also allows the execution of files on the guest that are not set executable on the host:<br />
<br />
#!/bin/bash<br />
eval $(ps h -C smbd -o pid,args | grep /tmp/qemu-smb | gawk '{print "pid="$1";conf="$6}')<br />
echo "[global]<br />
allow insecure wide links = yes<br />
[qemu]<br />
follow symlinks = yes<br />
wide links = yes<br />
acl allow execute always = yes" >> $conf<br />
# in case the change is not detected automatically:<br />
smbcontrol --configfile=$conf $pid reload-config<br />
<br />
This can be applied to the running server started by qemu only after the guest has connected to the network drive the first time. An alternative to this method is to add additional shares to the configuration file like so:<br />
<br />
echo "[''myshare'']<br />
path=''another_path''<br />
read only=no<br />
guest ok=yes<br />
force user=''username''" >> $conf<br />
<br />
This share will be available on the guest as {{ic|\\10.0.2.4\''myshare''}}.<br />
<br />
=== Using filesystem passthrough and VirtFS ===<br />
<br />
See the [https://wiki.qemu.org/Documentation/9psetup QEMU documentation].<br />
<br />
=== Mounting a partition of the guest on the host ===<br />
<br />
It can be useful to mount a drive image under the host system, it can be a way to transfer files in and out of the guest. This should be done when the virtual machine is not running.<br />
<br />
The procedure to mount the drive on the host depends on the type of qemu image, ''raw'' or ''qcow2''. We detail thereafter the steps to mount a drive in the two formats in [[#Mounting a partition from a raw image]] and [[#Mounting a partition from a qcow2 image]]. For the full documentation see [[Wikibooks:QEMU/Images#Mounting an image on the host]].<br />
<br />
{{Warning|You must make sure to unmount the partitions before running the virtual machine again. Otherwise, data corruption is very likely to occur.}}<br />
<br />
==== Mounting a partition from a raw image ====<br />
<br />
It is possible to mount partitions that are inside a raw disk image file by setting them up as loopback devices.<br />
<br />
===== With manually specifying byte offset =====<br />
<br />
One way to mount a disk image partition is to mount the disk image at a certain offset using a command like the following:<br />
<br />
# mount -o loop,offset=32256 ''disk_image'' ''mountpoint''<br />
<br />
The {{ic|1=offset=32256}} option is actually passed to the {{ic|losetup}} program to set up a loopback device that starts at byte offset 32256 of the file and continues to the end. This loopback device is then mounted. You may also use the {{ic|sizelimit}} option to specify the exact size of the partition, but this is usually unnecessary.<br />
<br />
Depending on your disk image, the needed partition may not start at offset 32256. Run {{ic|fdisk -l ''disk_image''}} to see the partitions in the image. fdisk gives the start and end offsets in 512-byte sectors, so multiply by 512 to get the correct offset to pass to {{ic|mount}}.<br />
<br />
===== With loop module autodetecting partitions =====<br />
<br />
The Linux loop driver actually supports partitions in loopback devices, but it is disabled by default. To enable it, do the following:<br />
<br />
* Get rid of all your loopback devices (unmount all mounted images, etc.).<br />
* [[Kernel_modules#Manual_module_handling|Unload]] the {{ic|loop}} kernel module, and load it with the {{ic|1=max_part=15}} parameter set. Additionally, the maximum number of loop devices can be controlled with the {{ic|max_loop}} parameter.<br />
<br />
{{Tip|You can put an entry in {{ic|/etc/modprobe.d}} to load the loop module with {{ic|1=max_part=15}} every time, or you can put {{ic|1=loop.max_part=15}} on the kernel command-line, depending on whether you have the {{ic|loop.ko}} module built into your kernel or not.}}<br />
<br />
Set up your image as a loopback device:<br />
<br />
# losetup -f -P ''disk_image''<br />
<br />
Then, if the device created was {{ic|/dev/loop0}}, additional devices {{ic|/dev/loop0pX}} will have been automatically created, where X is the number of the partition. These partition loopback devices can be mounted directly. For example:<br />
<br />
# mount /dev/loop0p1 ''mountpoint''<br />
<br />
To mount the disk image with ''udisksctl'', see [[Udisks#Mount loop devices]].<br />
<br />
===== With kpartx =====<br />
<br />
'''kpartx''' from the {{Pkg|multipath-tools}} package can read a partition table on a device and create a new device for each partition. For example:<br />
<br />
# kpartx -a ''disk_image''<br />
<br />
This will setup the loopback device and create the necessary partition(s) device(s) in {{ic|/dev/mapper/}}.<br />
<br />
==== Mounting a partition from a qcow2 image ====<br />
<br />
We will use {{ic|qemu-nbd}}, which lets use the NBD (''network block device'') protocol to share the disk image.<br />
<br />
First, we need the ''nbd'' module loaded:<br />
<br />
# modprobe nbd max_part=16<br />
<br />
Then, we can share the disk and create the device entries:<br />
<br />
# qemu-nbd -c /dev/nbd0 ''/path/to/image.qcow2''<br />
<br />
Discover the partitions:<br />
<br />
# partprobe /dev/nbd0<br />
<br />
''fdisk'' can be used to get information regarding the different partitions in {{{ic|''nbd0''}}:<br />
<br />
{{hc|# fdisk -l /dev/nbd0|2=<br />
Disk /dev/nbd0: 25.2 GiB, 27074281472 bytes, 52879456 sectors<br />
Units: sectors of 1 * 512 = 512 bytes<br />
Sector size (logical/physical): 512 bytes / 512 bytes<br />
I/O size (minimum/optimal): 512 bytes / 512 bytes<br />
Disklabel type: dos<br />
Disk identifier: 0xa6a4d542<br />
<br />
Device Boot Start End Sectors Size Id Type<br />
/dev/nbd0p1 * 2048 1026047 1024000 500M 7 HPFS/NTFS/exFAT<br />
/dev/nbd0p2 1026048 52877311 51851264 24.7G 7 HPFS/NTFS/exFAT}}<br />
<br />
Then mount any partition of the drive image, for example the partition 2:<br />
<br />
# mount /dev/nbd0'''p2''' ''mountpoint''<br />
<br />
After the usage, it is important to unmount the image and reverse previous steps, i.e. unmount the partition and disconnect the nbd device:<br />
<br />
# umount ''mountpoint''<br />
# qemu-nbd -d /dev/nbd0<br />
<br />
=== Using any real partition as the single primary partition of a hard disk image ===<br />
<br />
Sometimes, you may wish to use one of your system partitions from within QEMU. Using a raw partition for a virtual machine will improve performance, as the read and write operations do not go through the file system layer on the physical host. Such a partition also provides a way to share data between the host and guest.<br />
<br />
In Arch Linux, device files for raw partitions are, by default, owned by ''root'' and the ''disk'' group. If you would like to have a non-root user be able to read and write to a raw partition, you must either change the owner of the partition's device file to that user, add that user to the ''disk'' group, or use [[ACL]] for more fine-grained access control.<br />
<br />
{{Warning|<br />
* Although it is possible, it is not recommended to allow virtual machines to alter critical data on the host system, such as the root partition.<br />
* You must not mount a file system on a partition read-write on both the host and the guest at the same time. Otherwise, data corruption will result.<br />
}}<br />
<br />
After doing so, you can attach the partition to a QEMU virtual machine as a virtual disk.<br />
<br />
However, things are a little more complicated if you want to have the ''entire'' virtual machine contained in a partition. In that case, there would be no disk image file to actually boot the virtual machine since you cannot install a bootloader to a partition that is itself formatted as a file system and not as a partitioned device with an MBR. Such a virtual machine can be booted either by specifying the [[kernel]] and [[initrd]] manually, or by simulating a disk with an MBR by using the [https://www.kernel.org/doc/html/latest/admin-guide/device-mapper/index.html Device-mapper], linear [[RAID]], or a [https://www.kernel.org/doc/html/latest/admin-guide/blockdev/nbd.html Linux Network Block Device].<br />
<br />
==== By specifying kernel and initrd manually ====<br />
<br />
QEMU supports loading [[Kernels|Linux kernels]] and [[initramfs|init ramdisks]] directly, thereby circumventing bootloaders such as [[GRUB]]. It then can be launched with the physical partition containing the root file system as the virtual disk, which will not appear to be partitioned. This is done by issuing a command similar to the following:<br />
<br />
{{Note|In this example, it is the '''host's''' images that are being used, not the guest's. If you wish to use the guest's images, either mount {{ic|/dev/sda3}} read-only (to protect the file system from the host) and specify the {{ic|/full/path/to/images}} or use some kexec hackery in the guest to reload the guest's kernel (extends boot time). }}<br />
<br />
$ qemu-system-x86_64 -kernel /boot/vmlinuz-linux -initrd /boot/initramfs-linux.img -append root=/dev/sda /dev/sda3<br />
<br />
In the above example, the physical partition being used for the guest's root file system is {{ic|/dev/sda3}} on the host, but it shows up as {{ic|/dev/sda}} on the guest.<br />
<br />
You may, of course, specify any kernel and initrd that you want, and not just the ones that come with Arch Linux.<br />
<br />
When there are multiple [[kernel parameters]] to be passed to the {{ic|-append}} option, they need to be quoted using single or double quotes. For example:<br />
<br />
... -append 'root=/dev/sda1 console=ttyS0'<br />
<br />
==== Simulate a virtual disk with MBR ====<br />
<br />
A more complicated way to have a virtual machine use a physical partition, while keeping that partition formatted as a file system and not just having the guest partition the partition as if it were a disk, is to simulate an MBR for it so that it can boot using a bootloader such as GRUB.<br />
<br />
For the following, suppose you have a plain, unmounted {{ic|/dev/hda''N''}} partition with some file system on it you wish to make part of a QEMU disk image. The trick is to dynamically prepend a master boot record (MBR) to the real partition you wish to embed in a QEMU raw disk image. More generally, the partition can be any part of a larger simulated disk, in particular a block device that simulates the original physical disk but only exposes {{ic|/dev/hda''N''}} to the virtual machine.<br />
<br />
A virtual disk of this type can be represented by a VMDK file that contains references to (a copy of) the MBR and the partition, but QEMU does not support this VMDK format. For instance, a virtual disk [https://www.virtualbox.org/manual/ch09.html#rawdisk created by]<br />
<br />
$ VBoxManage internalcommands createrawvmdk -filename ''/path/to/file.vmdk'' -rawdisk /dev/hda<br />
<br />
will be rejected by QEMU with the error message<br />
<br />
Unsupported image type 'partitionedDevice'<br />
<br />
Note that {{ic|VBoxManage}} creates two files, {{ic|''file.vmdk''}} and {{ic|''file-pt.vmdk''}}, the latter being a copy of the MBR, to which the text file {{ic|file.vmdk}} points. Read operations outside the target partition or the MBR would give zeros, while written data would be discarded.<br />
<br />
===== Device Mapper =====<br />
<br />
A method that is similar to the use of a VMDK descriptor file uses the device mapper to prepend a loop device attached to the MBR file to the target partition. In case we do not need our virtual disk to have the same size as the original, we first create a file to hold the MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=2048<br />
<br />
Here, a 1 MB (2048 * 512 bytes) file is created in accordance with partition alignment policies used by modern disk partitioning tools. For compatibility with older partitioning software, 63 sectors instead of 2048 might be required. The MBR only needs a single 512 bytes block, the additional free space can be used for a BIOS boot partition and, in the case of a hybrid partitioning scheme, for a GUID Partition Table. Then, we attach a loop device to the MBR file:<br />
<br />
# losetup --show -f ''/path/to/mbr''<br />
/dev/loop0<br />
<br />
In this example, the resulting device is {{ic|/dev/loop0}}. The device mapper is now used to join the MBR and the partition:<br />
<br />
# echo "0 2048 linear /dev/loop0 0<br />
2048 `blockdev --getsz /dev/hda''N''` linear /dev/hda''N'' 0" | dmsetup create qemu<br />
<br />
The resulting {{ic|/dev/mapper/qemu}} is what we will use as a QEMU raw disk image. Additional steps are required to create a partition table (see the section that describes the use of a linear RAID for an example) and boot loader code on the virtual disk (which will be stored in {{ic|''/path/to/mbr''}}).<br />
<br />
The following setup is an example where the position of {{ic|/dev/hda''N''}} on the virtual disk is to be the same as on the physical disk and the rest of the disk is hidden, except for the MBR, which is provided as a copy:<br />
<br />
# dd if=/dev/hda count=1 of=''/path/to/mbr''<br />
# loop=`losetup --show -f ''/path/to/mbr''`<br />
# start=`blockdev --report /dev/hda''N'' | tail -1 | awk '{print $5}'`<br />
# size=`blockdev --getsz /dev/hda''N''`<br />
# disksize=`blockdev --getsz /dev/hda`<br />
# echo "0 1 linear $loop 0<br />
1 $((start-1)) zero<br />
$start $size linear /dev/hda''N'' 0<br />
$((start+size)) $((disksize-start-size)) zero" | dmsetup create qemu<br />
<br />
The table provided as standard input to {{ic|dmsetup}} has a similar format as the table in a VDMK descriptor file produced by {{ic|VBoxManage}} and can alternatively be loaded from a file with {{ic|dmsetup create qemu --table ''table_file''}}. To the virtual machine, only {{ic|/dev/hda''N''}} is accessible, while the rest of the hard disk reads as zeros and discards written data, except for the first sector. We can print the table for {{ic|/dev/mapper/qemu}} with {{ic|dmsetup table qemu}} (use {{ic|udevadm info -rq name /sys/dev/block/''major'':''minor''}} to translate {{ic|''major'':''minor''}} to the corresponding {{ic|/dev/''blockdevice''}} name). Use {{ic|dmsetup remove qemu}} and {{ic|losetup -d $loop}} to delete the created devices.<br />
<br />
A situation where this example would be useful is an existing Windows XP installation in a multi-boot configuration and maybe a hybrid partitioning scheme (on the physical hardware, Windows XP could be the only operating system that uses the MBR partition table, while more modern operating systems installed on the same computer could use the GUID Partition Table). Windows XP supports hardware profiles, so that that the same installation can be used with different hardware configurations alternatingly (in this case bare metal vs. virtual) with Windows needing to install drivers for newly detected hardware only once for every profile. Note that in this example the boot loader code in the copied MBR needs to be updated to directly load Windows XP from {{ic|/dev/hda''N''}} instead of trying to start the multi-boot capable boot loader (like GRUB) present in the original system. Alternatively, a copy of the boot partition containing the boot loader installation can be included in the virtual disk the same way as the MBR.<br />
<br />
===== Linear RAID =====<br />
<br />
You can also do this using software [[RAID]] in linear mode (you need the {{ic|linear.ko}} kernel driver) and a loopback device: <br />
<br />
First, you create some small file to hold the MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=32<br />
<br />
Here, a 16 KB (32 * 512 bytes) file is created. It is important not to make it too small (even if the MBR only needs a single 512 bytes block), since the smaller it will be, the smaller the chunk size of the software RAID device will have to be, which could have an impact on performance. Then, you setup a loopback device to the MBR file:<br />
<br />
# losetup -f ''/path/to/mbr''<br />
<br />
Let us assume the resulting device is {{ic|/dev/loop0}}, because we would not already have been using other loopbacks. Next step is to create the "merged" MBR + {{ic|/dev/hda''N''}} disk image using software RAID:<br />
<br />
# modprobe linear<br />
# mdadm --build --verbose /dev/md0 --chunk=16 --level=linear --raid-devices=2 /dev/loop0 /dev/hda''N''<br />
<br />
The resulting {{ic|/dev/md0}} is what you will use as a QEMU raw disk image (do not forget to set the permissions so that the emulator can access it). The last (and somewhat tricky) step is to set the disk configuration (disk geometry and partitions table) so that the primary partition start point in the MBR matches the one of {{ic|/dev/hda''N''}} inside {{ic|/dev/md0}} (an offset of exactly 16 * 512 = 16384 bytes in this example). Do this using {{ic|fdisk}} on the host machine, not in the emulator: the default raw disc detection routine from QEMU often results in non-kilobyte-roundable offsets (such as 31.5 KB, as in the previous section) that cannot be managed by the software RAID code. Hence, from the the host:<br />
<br />
# fdisk /dev/md0<br />
<br />
Press {{ic|X}} to enter the expert menu. Set number of 's'ectors per track so that the size of one cylinder matches the size of your MBR file. For two heads and a sector size of 512, the number of sectors per track should be 16, so we get cylinders of size 2x16x512=16k.<br />
<br />
Now, press {{ic|R}} to return to the main menu.<br />
<br />
Press {{ic|P}} and check that the cylinder size is now 16k.<br />
<br />
Now, create a single primary partition corresponding to {{ic|/dev/hda''N''}}. It should start at cylinder 2 and end at the end of the disk (note that the number of cylinders now differs from what it was when you entered fdisk.<br />
<br />
Finally, 'w'rite the result to the file: you are done. You now have a partition you can mount directly from your host, as well as part of a QEMU disk image:<br />
<br />
$ qemu-system-x86_64 -hdc /dev/md0 ''[...]''<br />
<br />
You can, of course, safely set any bootloader on this disk image using QEMU, provided the original {{ic|/dev/hda''N''}} partition contains the necessary tools.<br />
<br />
===== Network Block Device =====<br />
<br />
Instead of the methods decribed above, you may use {{ic|nbd-server}} (from the {{pkg|nbd}} package) to create an MBR wrapper for QEMU.<br />
<br />
Assuming you have already set up your MBR wrapper file like above, rename it to {{ic|wrapper.img.0}}. Then create a symbolic link named {{ic|wrapper.img.1}} in the same directory, pointing to your partition. Then put the following script in the same directory:<br />
<br />
#!/bin/sh<br />
dir="$(realpath "$(dirname "$0")")"<br />
cat >wrapper.conf <<EOF<br />
[generic]<br />
allowlist = true<br />
listenaddr = 127.713705<br />
port = 10809<br />
<br />
[wrap]<br />
exportname = $dir/wrapper.img<br />
multifile = true<br />
EOF<br />
<br />
nbd-server \<br />
-C wrapper.conf \<br />
-p wrapper.pid \<br />
"$@"<br />
<br />
The {{ic|.0}} and {{ic|.1}} suffixes are essential; the rest can be changed. After running the above script (which you may need to do as root to make sure nbd-server is able to access the partition), you can launch QEMU with:<br />
<br />
qemu-system-x86_64 -drive file=nbd:127.713705:10809:exportname=wrap ''[...]''<br />
<br />
== Networking ==<br />
<br />
{{Style|Network topologies (sections [[#Host-only networking]], [[#Internal networking]] and info spread out across other sections) should not be described alongside the various virtual interfaces implementations, such as [[#User-mode networking]], [[#Tap networking with QEMU]], [[#Networking with VDE2]].}}<br />
<br />
The performance of virtual networking should be better with tap devices and bridges than with user-mode networking or vde because tap devices and bridges are implemented in-kernel.<br />
<br />
In addition, networking performance can be improved by assigning virtual machines a [http://wiki.libvirt.org/page/Virtio virtio] network device rather than the default emulation of an e1000 NIC. See [[#Installing virtio drivers]] for more information.<br />
<br />
=== Link-level address caveat ===<br />
<br />
By giving the {{ic|-net nic}} argument to QEMU, it will, by default, assign a virtual machine a network interface with the link-level address {{ic|52:54:00:12:34:56}}. However, when using bridged networking with multiple virtual machines, it is essential that each virtual machine has a unique link-level (MAC) address on the virtual machine side of the tap device. Otherwise, the bridge will not work correctly, because it will receive packets from multiple sources that have the same link-level address. This problem occurs even if the tap devices themselves have unique link-level addresses because the source link-level address is not rewritten as packets pass through the tap device.<br />
<br />
Make sure that each virtual machine has a unique link-level address, but it should always start with {{ic|52:54:}}. Use the following option, replace ''X'' with arbitrary hexadecimal digit:<br />
<br />
$ qemu-system-x86_64 -net nic,macaddr=52:54:''XX:XX:XX:XX'' -net vde ''disk_image''<br />
<br />
Generating unique link-level addresses can be done in several ways:<br />
<br />
* Manually specify unique link-level address for each NIC. The benefit is that the DHCP server will assign the same IP address each time the virtual machine is run, but it is unusable for large number of virtual machines.<br />
* Generate random link-level address each time the virtual machine is run. Practically zero probability of collisions, but the downside is that the DHCP server will assign a different IP address each time. You can use the following command in a script to generate random link-level address in a {{ic|macaddr}} variable:<br />
<br />
{{bc|1=<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
qemu-system-x86_64 -net nic,macaddr="$macaddr" -net vde ''disk_image''<br />
}}<br />
<br />
* Use the following script {{ic|qemu-mac-hasher.py}} to generate the link-level address from the virtual machine name using a hashing function. Given that the names of virtual machines are unique, this method combines the benefits of the aforementioned methods: it generates the same link-level address each time the script is run, yet it preserves the practically zero probability of collisions.<br />
<br />
{{hc|qemu-mac-hasher.py|<nowiki><br />
#!/usr/bin/env python<br />
<br />
import sys<br />
import zlib<br />
<br />
if len(sys.argv) != 2:<br />
print("usage: %s <VM Name>" % sys.argv[0])<br />
sys.exit(1)<br />
<br />
crc = zlib.crc32(sys.argv[1].encode("utf-8")) & 0xffffffff<br />
crc = str(hex(crc))[2:]<br />
print("52:54:%s%s:%s%s:%s%s:%s%s" % tuple(crc))<br />
</nowiki>}}<br />
<br />
In a script, you can use for example:<br />
<br />
vm_name="''VM Name''"<br />
qemu-system-x86_64 -name "$vm_name" -net nic,macaddr=$(qemu-mac-hasher.py "$vm_name") -net vde ''disk_image''<br />
<br />
=== User-mode networking ===<br />
<br />
By default, without any {{ic|-netdev}} arguments, QEMU will use user-mode networking with a built-in DHCP server. Your virtual machines will be assigned an IP address when they run their DHCP client, and they will be able to access the physical host's network through IP masquerading done by QEMU.<br />
<br />
{{warning|This only works with the TCP and UDP protocols, so ICMP, including {{ic|ping}}, will not work. Do not use {{ic|ping}} to test network connectivity. To make ping work in the guest see [[Sysctl#Allow unprivileged users to create IPPROTO_ICMP sockets]].}}<br />
<br />
This default configuration allows your virtual machines to easily access the Internet, provided that the host is connected to it, but the virtual machines will not be directly visible on the external network, nor will virtual machines be able to talk to each other if you start up more than one concurrently.<br />
<br />
QEMU's user-mode networking can offer more capabilities such as built-in TFTP or SMB servers, redirecting host ports to the guest (for example to allow SSH connections to the guest) or attaching guests to VLANs so that they can talk to each other. See the QEMU documentation on the {{ic|-net user}} flag for more details.<br />
<br />
However, user-mode networking has limitations in both utility and performance. More advanced network configurations require the use of tap devices or other methods.<br />
<br />
{{Note|If the host system uses [[systemd-networkd]], make sure to symlink the {{ic|/etc/resolv.conf}} file as described in [[systemd-networkd#Required services and setup]], otherwise the DNS lookup in the guest system will not work.}}<br />
<br />
=== Tap networking with QEMU ===<br />
<br />
[[wikipedia:TUN/TAP|Tap devices]] are a Linux kernel feature that allows you to create virtual network interfaces that appear as real network interfaces. Packets sent to a tap interface are delivered to a userspace program, such as QEMU, that has bound itself to the interface.<br />
<br />
QEMU can use tap networking for a virtual machine so that packets sent to the tap interface will be sent to the virtual machine and appear as coming from a network interface (usually an Ethernet interface) in the virtual machine. Conversely, everything that the virtual machine sends through its network interface will appear on the tap interface.<br />
<br />
Tap devices are supported by the Linux bridge drivers, so it is possible to bridge together tap devices with each other and possibly with other host interfaces such as {{ic|eth0}}. This is desirable if you want your virtual machines to be able to talk to each other, or if you want other machines on your LAN to be able to talk to the virtual machines.<br />
<br />
{{Warning|If you bridge together tap device and some host interface, such as {{ic|eth0}}, your virtual machines will appear directly on the external network, which will expose them to possible attack. Depending on what resources your virtual machines have access to, you may need to take all the [[Firewalls|precautions]] you normally would take in securing a computer to secure your virtual machines. If the risk is too great, virtual machines have little resources or you set up multiple virtual machines, a better solution might be to use [[#Host-only networking|host-only networking]] and set up NAT. In this case you only need one firewall on the host instead of multiple firewalls for each guest.}}<br />
<br />
As indicated in the user-mode networking section, tap devices offer higher networking performance than user-mode. If the guest OS supports virtio network driver, then the networking performance will be increased considerably as well. Supposing the use of the tap0 device, that the virtio driver is used on the guest, and that no scripts are used to help start/stop networking, next is part of the qemu command one should see:<br />
<br />
-device virtio-net,netdev=network0 -netdev tap,id=network0,ifname=tap0,script=no,downscript=no<br />
<br />
But if already using a tap device with virtio networking driver, one can even boost the networking performance by enabling vhost, like:<br />
<br />
-device virtio-net,netdev=network0 -netdev tap,id=network0,ifname=tap0,script=no,downscript=no,vhost=on<br />
<br />
See [https://web.archive.org/web/20160222161955/http://www.linux-kvm.com:80/content/how-maximize-virtio-net-performance-vhost-net] for more information.<br />
<br />
==== Host-only networking ====<br />
<br />
If the bridge is given an IP address and traffic destined for it is allowed, but no real interface (e.g. {{ic|eth0}}) is connected to the bridge, then the virtual machines will be able to talk to each other and the host system. However, they will not be able to talk to anything on the external network, provided that you do not set up IP masquerading on the physical host. This configuration is called ''host-only networking'' by other virtualization software such as [[VirtualBox]].<br />
<br />
{{Tip|<br />
* If you want to set up IP masquerading, e.g. NAT for virtual machines, see the [[Internet sharing#Enable NAT]] page.<br />
* See [[Network bridge]] for information on creating bridge.<br />
* You may want to have a DHCP server running on the bridge interface to service the virtual network. For example, to use the {{ic|172.20.0.1/16}} subnet with [[dnsmasq]] as the DHCP server:<br />
<br />
{{bc|1=<br />
# ip addr add 172.20.0.1/16 dev br0<br />
# ip link set br0 up<br />
# dnsmasq --interface=br0 --bind-interfaces --dhcp-range=172.20.0.2,172.20.255.254<br />
}}<br />
}}<br />
<br />
==== Internal networking ====<br />
<br />
If you do not give the bridge an IP address and add an [[iptables]] rule to drop all traffic to the bridge in the INPUT chain, then the virtual machines will be able to talk to each other, but not to the physical host or to the outside network. This configuration is called ''internal networking'' by other virtualization software such as [[VirtualBox]]. You will need to either assign static IP addresses to the virtual machines or run a DHCP server on one of them.<br />
<br />
By default iptables would drop packets in the bridge network. You may need to use such iptables rule to allow packets in a bridged network:<br />
<br />
# iptables -I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Bridged networking using qemu-bridge-helper ====<br />
<br />
{{Note|This method is available since QEMU 1.1, see http://wiki.qemu.org/Features/HelperNetworking.}}<br />
<br />
This method does not require a start-up script and readily accommodates multiple taps and multiple bridges. It uses {{ic|/usr/lib/qemu/qemu-bridge-helper}} binary, which allows creating tap devices on an existing bridge.<br />
<br />
{{Tip|See [[Network bridge]] for information on creating bridge.}}<br />
<br />
First, create a configuration file containing the names of all bridges to be used by QEMU:<br />
<br />
{{hc|/etc/qemu/bridge.conf|<br />
allow ''bridge0''<br />
allow ''bridge1''<br />
...}}<br />
<br />
Now start the VM. The most basic usage would be:<br />
<br />
$ qemu-system-x86_64 -net nic -net bridge,br=''bridge0'' ''[...]''<br />
<br />
With multiple taps, the most basic usage requires specifying the VLAN for all additional NICs:<br />
<br />
$ qemu-system-x86_64 -net nic -net bridge,br=''bridge0'' -net nic,vlan=1 -net bridge,vlan=1,br=''bridge1'' ''[...]''<br />
<br />
==== Creating bridge manually ====<br />
<br />
{{Style|This section needs serious cleanup and may contain out-of-date information.}}<br />
<br />
{{Tip|Since QEMU 1.1, the [http://wiki.qemu.org/Features/HelperNetworking network bridge helper] can set tun/tap up for you without the need for additional scripting. See [[#Bridged networking using qemu-bridge-helper]].}}<br />
<br />
The following describes how to bridge a virtual machine to a host interface such as {{ic|eth0}}, which is probably the most common configuration. This configuration makes it appear that the virtual machine is located directly on the external network, on the same Ethernet segment as the physical host machine.<br />
<br />
We will replace the normal Ethernet adapter with a bridge adapter and bind the normal Ethernet adapter to it.<br />
<br />
* Install {{Pkg|bridge-utils}}, which provides {{ic|brctl}} to manipulate bridges.<br />
<br />
* Enable IPv4 forwarding:<br />
# sysctl -w net.ipv4.ip_forward=1<br />
<br />
To make the change permanent, change {{ic|1=net.ipv4.ip_forward = 0}} to {{ic|1=net.ipv4.ip_forward = 1}} in {{ic|/etc/sysctl.d/99-sysctl.conf}}.<br />
<br />
* Load the {{ic|tun}} module and configure it to be loaded on boot. See [[Kernel modules]] for details.<br />
<br />
* Now create the bridge. See [[Bridge with netctl]] for details. Remember to name your bridge as {{ic|br0}}, or change the scripts below to your bridge's name.<br />
<br />
* Create the script that QEMU uses to bring up the tap adapter with {{ic|root:kvm}} 750 permissions:<br />
<br />
{{hc|/etc/qemu-ifup|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifup"<br />
echo "Bringing up $1 for bridged mode..."<br />
sudo /usr/bin/ip link set $1 up promisc on<br />
echo "Adding $1 to br0..."<br />
sudo /usr/bin/brctl addif br0 $1<br />
sleep 2<br />
</nowiki>}}<br />
<br />
* Create the script that QEMU uses to bring down the tap adapter in {{ic|/etc/qemu-ifdown}} with {{ic|root:kvm}} 750 permissions:<br />
{{hc|/etc/qemu-ifdown|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifdown"<br />
sudo /usr/bin/ip link set $1 down<br />
sudo /usr/bin/brctl delif br0 $1<br />
sudo /usr/bin/ip link delete dev $1<br />
</nowiki>}}<br />
<br />
* Use {{ic|visudo}} to add the following to your {{ic|sudoers}} file:<br />
<br />
{{bc|<nowiki><br />
Cmnd_Alias QEMU=/usr/bin/ip,/usr/bin/modprobe,/usr/bin/brctl<br />
%kvm ALL=NOPASSWD: QEMU<br />
</nowiki>}}<br />
<br />
* You launch QEMU using the following {{ic|run-qemu}} script:<br />
<br />
{{hc|run-qemu|<nowiki><br />
#!/bin/bash<br />
USERID=$(whoami)<br />
<br />
# Get name of newly created TAP device; see https://bbs.archlinux.org/viewtopic.php?pid=1285079#p1285079<br />
precreationg=$(/usr/bin/ip tuntap list | /usr/bin/cut -d: -f1 | /usr/bin/sort)<br />
sudo /usr/bin/ip tuntap add user $USERID mode tap<br />
postcreation=$(/usr/bin/ip tuntap list | /usr/bin/cut -d: -f1 | /usr/bin/sort)<br />
IFACE=$(comm -13 <(echo "$precreationg") <(echo "$postcreation"))<br />
<br />
# This line creates a random MAC address. The downside is the DHCP server will assign a different IP address each time<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
# Instead, uncomment and edit this line to set a static MAC address. The benefit is that the DHCP server will assign the same IP address.<br />
# macaddr='52:54:be:36:42:a9'<br />
<br />
qemu-system-x86_64 -net nic,macaddr=$macaddr -net tap,ifname="$IFACE" $*<br />
<br />
sudo ip link set dev $IFACE down &> /dev/null<br />
sudo ip tuntap del $IFACE mode tap &> /dev/null<br />
</nowiki>}}<br />
<br />
Then to launch a VM, do something like this<br />
<br />
$ run-qemu -hda ''myvm.img'' -m 512<br />
<br />
* It is recommended for performance and security reasons to disable the [http://ebtables.netfilter.org/documentation/bridge-nf.html firewall on the bridge]:<br />
<br />
{{hc|/etc/sysctl.d/10-disable-firewall-on-bridge.conf|<nowiki><br />
net.bridge.bridge-nf-call-ip6tables = 0<br />
net.bridge.bridge-nf-call-iptables = 0<br />
net.bridge.bridge-nf-call-arptables = 0<br />
</nowiki>}}<br />
<br />
Run {{ic|sysctl -p /etc/sysctl.d/10-disable-firewall-on-bridge.conf}} to apply the changes immediately.<br />
<br />
See the [http://wiki.libvirt.org/page/Networking#Creating_network_initscripts libvirt wiki] and [https://bugzilla.redhat.com/show_bug.cgi?id=512206 Fedora bug 512206]. If you get errors by sysctl during boot about non-existing files, make the {{ic|bridge}} module load at boot. See [[Kernel modules#Automatic module loading with systemd]].<br />
<br />
Alternatively, you can configure [[iptables]] to allow all traffic to be forwarded across the bridge by adding a rule like this:<br />
<br />
-I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Network sharing between physical device and a Tap device through iptables ====<br />
<br />
{{Merge|Internet_sharing|Duplication, not specific to QEMU.}}<br />
<br />
Bridged networking works fine between a wired interface (Eg. eth0), and it is easy to setup. However if the host gets connected to the network through a wireless device, then bridging is not possible.<br />
<br />
See [[Network bridge#Wireless interface on a bridge]] as a reference.<br />
<br />
One way to overcome that is to setup a tap device with a static IP, making linux automatically handle the routing for it, and then forward traffic between the tap interface and the device connected to the network through iptables rules.<br />
<br />
See [[Internet sharing]] as a reference.<br />
<br />
There you can find what is needed to share the network between devices, included tap and tun ones. The following just hints further on some of the host configurations required. As indicated in the reference above, the client needs to be configured for a static IP, using the IP assigned to the tap interface as the gateway. The caveat is that the DNS servers on the client might need to be manually edited if they change when changing from one host device connected to the network to another.<br />
<br />
To allow IP forwarding on every boot, one need to add the following lines to sysctl configuration file inside {{ic|/etc/sysctl.d}}:<br />
<br />
net.ipv4.ip_forward = 1<br />
net.ipv6.conf.default.forwarding = 1<br />
net.ipv6.conf.all.forwarding = 1<br />
<br />
The iptables rules can look like:<br />
<br />
# Forwarding from/to outside<br />
iptables -A FORWARD -i ${INT} -o ${EXT_0} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_1} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_2} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_0} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_1} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_2} -o ${INT} -j ACCEPT<br />
# NAT/Masquerade (network address translation)<br />
iptables -t nat -A POSTROUTING -o ${EXT_0} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_1} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_2} -j MASQUERADE<br />
<br />
The prior supposes there are 3 devices connected to the network sharing traffic with one internal device, where for example:<br />
<br />
INT=tap0<br />
EXT_0=eth0<br />
EXT_1=wlan0<br />
EXT_2=tun0<br />
<br />
The prior shows a forwarding that would allow sharing wired and wireless connections with the tap device.<br />
<br />
The forwarding rules shown are stateless, and for pure forwarding. One could think of restricting specific traffic, putting a firewall in place to protect the guest and others. However those would decrease the networking performance, while a simple bridge does not include any of that.<br />
<br />
Bonus: Whether the connection is wired or wireless, if one gets connected through VPN to a remote site with a tun device, supposing the tun device opened for that connection is tun0, and the prior iptables rules are applied, then the remote connection gets also shared with the guest. This avoids the need for the guest to also open a VPN connection. Again, as the guest networking needs to be static, then if connecting the host remotely this way, one most probably will need to edit the DNS servers on the guest.<br />
<br />
=== Networking with VDE2 ===<br />
<br />
{{Style|This section needs serious cleanup and may contain out-of-date information.}}<br />
<br />
==== What is VDE? ====<br />
<br />
VDE stands for Virtual Distributed Ethernet. It started as an enhancement of [[User-mode Linux|uml]]_switch. It is a toolbox to manage virtual networks.<br />
<br />
The idea is to create virtual switches, which are basically sockets, and to "plug" both physical and virtual machines in them. The configuration we show here is quite simple; However, VDE is much more powerful than this, it can plug virtual switches together, run them on different hosts and monitor the traffic in the switches. You are invited to read [https://wiki.virtualsquare.org/ the documentation of the project].<br />
<br />
The advantage of this method is you do not have to add sudo privileges to your users. Regular users should not be allowed to run modprobe.<br />
<br />
==== Basics ====<br />
<br />
VDE support can be [[pacman|installed]] via the {{Pkg|vde2}} package.<br />
<br />
In our config, we use tun/tap to create a virtual interface on my host. Load the {{ic|tun}} module (see [[Kernel modules]] for details):<br />
<br />
# modprobe tun<br />
<br />
Now create the virtual switch:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
<br />
This line creates the switch, creates {{ic|tap0}}, "plugs" it, and allows the users of the group {{ic|users}} to use it.<br />
<br />
The interface is plugged in but not configured yet. To configure it, run this command:<br />
<br />
# ip addr add 192.168.100.254/24 dev tap0<br />
<br />
Now, you just have to run KVM with these {{ic|-net}} options as a normal user:<br />
<br />
$ qemu-system-x86_64 -net nic -net vde -hda ''[...]''<br />
<br />
Configure networking for your guest as you would do in a physical network.<br />
<br />
{{Tip|You might want to set up NAT on tap device to access the internet from the virtual machine. See [[Internet sharing#Enable NAT]] for more information.}}<br />
<br />
==== Startup scripts ====<br />
<br />
Example of main script starting VDE:<br />
<br />
{{hc|/etc/systemd/scripts/qemu-network-env|<nowiki><br />
#!/bin/sh<br />
# QEMU/VDE network environment preparation script<br />
<br />
# The IP configuration for the tap device that will be used for<br />
# the virtual machine network:<br />
<br />
TAP_DEV=tap0<br />
TAP_IP=192.168.100.254<br />
TAP_MASK=24<br />
TAP_NETWORK=192.168.100.0<br />
<br />
# Host interface<br />
NIC=eth0<br />
<br />
case "$1" in<br />
start)<br />
echo -n "Starting VDE network for QEMU: "<br />
<br />
# If you want tun kernel module to be loaded by script uncomment here<br />
#modprobe tun 2>/dev/null<br />
## Wait for the module to be loaded<br />
#while ! lsmod | grep -q "^tun"; do echo "Waiting for tun device"; sleep 1; done<br />
<br />
# Start tap switch<br />
vde_switch -tap "$TAP_DEV" -daemon -mod 660 -group users<br />
<br />
# Bring tap interface up<br />
ip address add "$TAP_IP"/"$TAP_MASK" dev "$TAP_DEV"<br />
ip link set "$TAP_DEV" up<br />
<br />
# Start IP Forwarding<br />
echo "1" > /proc/sys/net/ipv4/ip_forward<br />
iptables -t nat -A POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
;;<br />
stop)<br />
echo -n "Stopping VDE network for QEMU: "<br />
# Delete the NAT rules<br />
iptables -t nat -D POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
<br />
# Bring tap interface down<br />
ip link set "$TAP_DEV" down<br />
<br />
# Kill VDE switch<br />
pgrep vde_switch | xargs kill -TERM<br />
;;<br />
restart|reload)<br />
$0 stop<br />
sleep 1<br />
$0 start<br />
;;<br />
*)<br />
echo "Usage: $0 {start|stop|restart|reload}"<br />
exit 1<br />
esac<br />
exit 0<br />
</nowiki>}}<br />
<br />
Example of systemd service using the above script:<br />
<br />
{{hc|/etc/systemd/system/qemu-network-env.service|<nowiki><br />
[Unit]<br />
Description=Manage VDE Switch<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/etc/systemd/scripts/qemu-network-env start<br />
ExecStop=/etc/systemd/scripts/qemu-network-env stop<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
Change permissions for {{ic|qemu-network-env}} to be executable<br />
<br />
# chmod u+x /etc/systemd/scripts/qemu-network-env<br />
<br />
You can [[start]] {{ic|qemu-network-env.service}} as usual.<br />
<br />
====Alternative method====<br />
<br />
If the above method does not work or you do not want to mess with kernel configs, TUN, dnsmasq, and iptables you can do the following for the same result.<br />
<br />
# vde_switch -daemon -mod 660 -group users<br />
# slirpvde --dhcp --daemon<br />
<br />
Then, to start the VM with a connection to the network of the host:<br />
<br />
$ qemu-system-x86_64 -net nic,macaddr=52:54:00:00:EE:03 -net vde ''disk_image''<br />
<br />
=== VDE2 Bridge ===<br />
<br />
Based on [https://selamatpagicikgu.wordpress.com/2011/06/08/quickhowto-qemu-networking-using-vde-tuntap-and-bridge/ quickhowto: qemu networking using vde, tun/tap, and bridge] graphic. Any virtual machine connected to vde is externally exposed. For example, each virtual machine can receive DHCP configuration directly from your ADSL router.<br />
<br />
==== Basics ====<br />
<br />
Remember that you need {{ic|tun}} module and {{Pkg|bridge-utils}} package.<br />
<br />
Create the vde2/tap device:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
# ip link set tap0 up<br />
<br />
Create bridge:<br />
<br />
# brctl addbr br0<br />
<br />
Add devices:<br />
<br />
# brctl addif br0 eth0<br />
# brctl addif br0 tap0<br />
<br />
And configure bridge interface:<br />
<br />
# dhcpcd br0<br />
<br />
==== Startup scripts ====<br />
<br />
All devices must be set up. And only the bridge needs an IP address. For physical devices on the bridge (e.g. {{ic|eth0}}), this can be done with [[netctl]] using a custom Ethernet profile with:<br />
<br />
{{hc|/etc/netctl/ethernet-noip|2=<br />
Description='A more versatile static Ethernet connection'<br />
Interface=eth0<br />
Connection=ethernet<br />
IP=no<br />
}}<br />
<br />
The following custom systemd service can be used to create and activate a VDE2 tap interface for use in the {{ic|users}} user group.<br />
<br />
{{hc|/etc/systemd/system/vde2@.service|2=<br />
[Unit]<br />
Description=Network Connectivity for %i<br />
Wants=network.target<br />
Before=network.target<br />
<br />
[Service]<br />
Type=oneshot<br />
RemainAfterExit=yes<br />
ExecStart=/usr/bin/vde_switch -tap %i -daemon -mod 660 -group users<br />
ExecStart=/usr/bin/ip link set dev %i up<br />
ExecStop=/usr/bin/ip addr flush dev %i<br />
ExecStop=/usr/bin/ip link set dev %i down<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
}}<br />
<br />
And finally, you can create the [[Bridge with netctl|bridge interface with netctl]].<br />
<br />
=== Shorthand configuration ===<br />
<br />
If you are using QEMU with various networking options a lot, you probably have created a lot of {{ic|-netdev}} and {{ic|-device}} argument pairs, which gets quite repetitive. You can instead use the {{ic|-nic}} argument to combine {{ic|-netdev}} and {{ic|-device}} together, so that, for example, these arguments:<br />
<br />
-netdev tap,id=network0,ifname=tap0,script=no,downscript=no,vhost=on -device virtio-net-pci,netdev=network0<br />
<br />
become:<br />
<br />
-nic tap,script=no,downscript=no,vhost=on,model=virtio-net-pci<br />
<br />
Notice the lack of network IDs, and that the device was created with {{ic|1=model=}}. The first half of the {{ic|-nic}} parameters are {{ic|-netdev}} parameters, whereas the second half (after {{ic|1=model=}}) are related with the device. The same parameters (for example, {{ic|1=smb=}}) are used. To completely disable the networking use {{ic|-nic none}}.<br />
<br />
See [https://qemu.weilnetz.de/doc/qemu-doc.html#Network-options QEMU networking documentation] for more information on parameters you can use.<br />
<br />
== Graphic card ==<br />
<br />
QEMU can emulate a standard graphic card text mode using {{ic|-curses}} command line option. This allows to type text and see text output directly inside a text terminal.<br />
<br />
QEMU can emulate several types of VGA card. The card type is passed in the {{ic|-vga ''type''}} command line option and can be {{ic|std}}, {{ic|qxl}}, {{ic|vmware}}, {{ic|virtio}}, {{ic|cirrus}} or {{ic|none}}.<br />
<br />
=== std ===<br />
<br />
With {{ic|-vga std}} you can get a resolution of up to 2560 x 1600 pixels without requiring guest drivers. This is the default since QEMU 2.2.<br />
<br />
=== qxl ===<br />
<br />
QXL is a paravirtual graphics driver with 2D support. To use it, pass the {{ic|-vga qxl}} option and install drivers in the guest. You may want to use [[#SPICE]] for improved graphical performance when using QXL.<br />
<br />
On Linux guests, the {{ic|qxl}} and {{ic|bochs_drm}} kernel modules must be loaded in order to gain a decent performance.<br />
<br />
Default VGA memory size for QXL devices is 16M which is sufficient to drive resolutions approximately up to QHD (2560x1440). To enable higher resolutions, [[#Multi-monitor support|increase vga_memmb]].<br />
<br />
=== vmware ===<br />
<br />
Although it is a bit buggy, it performs better than std and cirrus. Install the VMware drivers {{Pkg|xf86-video-vmware}} and {{Pkg|xf86-input-vmmouse}} for Arch Linux guests.<br />
<br />
=== virtio ===<br />
<br />
{{ic|virtio-vga}} / {{ic|virtio-gpu}} is a paravirtual 3D graphics driver based on [https://virgil3d.github.io/ virgl]. Currently a work in progress, supporting only very recent (>= 4.4) Linux guests with {{Pkg|mesa}} (>=11.2) compiled with the option {{ic|1=gallium-drivers=virgl}}.<br />
<br />
To enable 3D acceleration on the guest system select this vga with {{ic|-vga virtio}} and enable the opengl context in the display device with {{ic|1=-display sdl,gl=on}} or {{ic|1=-display gtk,gl=on}} for the sdl and gtk display output respectively. Successful configuration can be confirmed looking at the kernel log in the guest:<br />
<br />
{{hc|$ dmesg {{!}} grep drm |<br />
[drm] pci: virtio-vga detected<br />
[drm] virgl 3d acceleration enabled<br />
}}<br />
<br />
=== cirrus ===<br />
<br />
The cirrus graphical adapter was the default [http://wiki.qemu.org/ChangeLog/2.2#VGA before 2.2]. It [https://www.kraxel.org/blog/2014/10/qemu-using-cirrus-considered-harmful/ should not] be used on modern systems.<br />
<br />
=== none ===<br />
<br />
This is like a PC that has no VGA card at all. You would not even be able to access it with the {{ic|-vnc}} option. Also, this is different from the {{ic|-nographic}} option which lets QEMU emulate a VGA card, but disables the SDL display.<br />
<br />
== SPICE ==<br />
The [http://spice-space.org/ SPICE project] aims to provide a complete open source solution for remote access to virtual machines in a seamless way.<br />
=== Enabling SPICE support on the host ===<br />
The following is an example of booting with SPICE as the remote desktop protocol, including the support for copy and paste from host:<br />
<br />
$ qemu-system-x86_64 -vga qxl -device virtio-serial-pci -spice port=5930,disable-ticketing -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
The parameters have the following meaning:<br />
<br />
# {{ic|-device virtio-serial-pci}} adds a virtio-serial device<br />
# {{ic|1=-spice port=5930,disable-ticketing}} set TCP port {{ic|5930}} for spice channels listening and allow client to connect without authentication{{Tip|Using [[wikipedia:Unix_socket|Unix sockets]] instead of TCP ports does not involve using network stack on the host system. It does not imply that packets are encapsulated and decapsulated to use the network and the related protocol. The sockets are identified solely by the inodes on the hard drive. It is therefore considered better for performance. Use instead {{ic|1=-spice unix,addr=/tmp/vm_spice.socket,disable-ticketing}}.}}<br />
# {{ic|1=-device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0}} opens a port for spice vdagent in the virtio-serial device,<br />
# {{ic|1=-chardev spicevmc,id=spicechannel0,name=vdagent}} adds a spicevmc chardev for that port. It is important that the {{ic|1=chardev=}} option of the {{ic|virtserialport}} device matches the {{ic|1=id=}} option given to the {{ic|chardev}} option ({{ic|spicechannel0}} in this example). It is also important that the port name is {{ic|com.redhat.spice.0}}, because that is the namespace where vdagent is looking for in the guest. And finally, specify {{ic|1=name=vdagent}} so that spice knows what this channel is for.<br />
<br />
=== Connecting to the guest with a SPICE client ===<br />
<br />
A SPICE client is necessary to connect to the guest. In Arch, the following clients are available:<br />
<br />
{{App|virt-viewer|SPICE client recommended by the protocol developers, a subset of the virt-manager project.|https://virt-manager.org/|{{Pkg|virt-viewer}}}}<br />
<br />
{{App|spice-gtk|SPICE GTK client, a subset of the SPICE project. Embedded into other applications as a widget.|https://www.spice-space.org/|{{Pkg|spice-gtk}}}}<br />
<br />
For clients that run on smartphone or on other platforms, refer to the ''Other clients'' section in [http://www.spice-space.org/download.html spice-space download].<br />
<br />
==== Manually running a SPICE client ====<br />
<br />
One way of connecting to a guest listening on Unix socket {{ic|/tmp/vm_spice.socket}} is to manually run the SPICE client using {{ic|$ remote-viewer spice+unix:///tmp/vm_spice.socket}} or {{ic|1=$ spicy --uri="spice+unix:///tmp/vm_spice.socket"}}, depending on the desired client. Since QEMU in SPICE mode acts similarly to a remote desktop server, it may be more convenient to run QEMU in daemon mode with the {{ic|-daemonize}} parameter.<br />
<br />
{{Tip|To connect to the guest through SSH tunelling, the following type of command can be used: {{bc|$ ssh -fL 5999:localhost:5930 ''my.domain.org'' sleep 10; spicy -h 127.0.0.1 -p 5999}}<br />
This example connects ''spicy'' to the local port {{ic|5999}} which is forwarded through SSH to the guest's SPICE server located at the address ''my.domain.org'', port {{ic|5930}}.<br />
Note the {{ic|-f}} option that requests ssh to execute the command {{ic|sleep 10}} in the background. This way, the ssh session runs while the client is active and auto-closes once the client ends.<br />
}}<br />
<br />
==== Running a SPICE client with QEMU ====<br />
<br />
QEMU can automatically start a SPICE client with an appropriate socket, if the display is set to SPICE with the {{ic|-display spice-app}} parameter. This will use the system's default SPICE client as the viewer, determined by your [[XDG_MIME_Applications#mimeapps.list|mimeapps.list]] files.<br />
<br />
=== Enabling SPICE support on the guest ===<br />
<br />
For '''Arch Linux guests''', for improved support for multiple monitors or clipboard sharing, the following packages should be installed:<br />
* {{Pkg|spice-vdagent}}: Spice agent xorg client that enables copy and paste between client and X-session and more.<br />
* {{Pkg|xf86-video-qxl}}: Xorg X11 qxl video driver<br />
For guests under '''other operating systems''', refer to the ''Guest'' section in [http://www.spice-space.org/download.html spice-space download].<br />
<br />
=== Password authentication with SPICE ===<br />
<br />
If you want to enable password authentication with SPICE you need to remove {{ic|disable-ticketing}} from the {{ic|-spice}} argument and instead add {{ic|1=password=''yourpassword''}}. For example:<br />
<br />
$ qemu-system-x86_64 -vga qxl -spice port=5900,password=''yourpassword'' -device virtio-serial-pci -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
Your SPICE client should now ask for the password to be able to connect to the SPICE server.<br />
<br />
=== TLS encrypted communication with SPICE ===<br />
<br />
You can also configure TLS encryption for communicating with the SPICE server. First, you need to have a directory which contains the following files (the names must be exactly as indicated):<br />
<br />
* {{ic|ca-cert.pem}}: the CA master certificate.<br />
* {{ic|server-cert.pem}}: the server certificate signed with {{ic|ca-cert.pem}}.<br />
* {{ic|server-key.pem}}: the server private key.<br />
<br />
An example of generation of self-signed certificates with your own generated CA for your server is shown in the [https://www.spice-space.org/spice-user-manual.html#_generating_self_signed_certificates Spice User Manual].<br />
<br />
Afterwards, you can run QEMU with SPICE as explained above but using the following {{ic|-spice}} argument: {{ic|1=-spice tls-port=5901,password=''yourpassword'',x509-dir=''/path/to/pki_certs''}}, where {{ic|''/path/to/pki_certs''}} is the directory path that contains the three needed files shown earlier.<br />
<br />
It is now possible to connect to the server using {{pkg|virt-viewer}}:<br />
<br />
$ remote-viewer spice://''hostname''?tls-port=5901 --spice-ca-file=''/path/to/ca-cert.pem'' --spice-host-subject="C=''XX'',L=''city'',O=''organization'',CN=''hostname''" --spice-secure-channels=all<br />
<br />
Keep in mind that the {{ic|--spice-host-subject}} parameter needs to be set according to your {{ic|server-cert.pem}} subject. You also need to copy {{ic|ca-cert.pem}} to every client to verify the server certificate.<br />
<br />
{{Tip|You can get the subject line of the server certificate in the correct format for {{ic|--spice-host-subject}} (with entries separated by commas) using the following command: {{bc|<nowiki>$ openssl x509 -noout -subject -in server-cert.pem | cut -d' ' -f2- | sed 's/\///' | sed 's/\//,/g'</nowiki>}}<br />
}}<br />
<br />
The equivalent {{Pkg|spice-gtk}} command is:<br />
<br />
$ spicy -h ''hostname'' -s 5901 --spice-ca-file=ca-cert.pem --spice-host-subject="C=''XX'',L=''city'',O=''organization'',CN=''hostname''" --spice-secure-channels=all<br />
<br />
== VNC ==<br />
<br />
One can add the {{ic|-vnc :''X''}} option to have QEMU redirect the VGA display to the VNC session. Substitute {{ic|''X''}} for the number of the display (0 will then listen on 5900, 1 on 5901...).<br />
<br />
$ qemu-system-x86_64 -vnc :0<br />
<br />
An example is also provided in the [[#Starting QEMU virtual machines on boot]] section.<br />
{{Warning|The default VNC server setup does not use any form of authentication. Any user can connect from any host.}}<br />
<br />
=== Basic password authentication ===<br />
<br />
An access password can be setup easily by using the {{ic|password}} option. The password must be indicated in the QEMU monitor and connection is only possible once the password is provided.<br />
<br />
$ qemu-system-x86_64 -vnc :0,password -monitor stdio<br />
<br />
In the QEMU monitor, password is set using the command {{ic|change vnc password}} and then indicating the password.<br />
<br />
The following command line directly runs vnc with a password:<br />
<br />
$ printf "change vnc password\n%s\n" MYPASSWORD | qemu-system-x86_64 -vnc :0,password -monitor stdio<br />
<br />
{{Note|The password is limited to 8 characters and can be guessed through brute force attack. More elaborated protection is strongly recommended for public network.}}<br />
<br />
== Audio ==<br />
<br />
=== Host ===<br />
<br />
The {{ic|-audiodev}} flag sets the audio backend driver and its options. The list of available audio backend drivers and their optional settings is detailed in the {{man|1|qemu}}. man page.<br />
<br />
At the bare minimum, you need to choose a driver and set an id.<br />
<br />
-audiodev pa,id=snd0<br />
<br />
=== Guest ===<br />
<br />
==== With audiodev ====<br />
<br />
===== Intel HD Audio =====<br />
<br />
For Intel HD Audio emulation add both controller and codec devices. To list the available Intel HDA Audio devices:<br />
<br />
$ qemu-system-x86_64 -device help | grep hda<br />
<br />
Add the audio controller<br />
<br />
-device ich9-intel-hda<br />
<br />
Add the audio codec and map it to a host audio backend id<br />
<br />
-device hda-output,audiodev=snd0<br />
<br />
===== Intel 82801AA AC97 =====<br />
<br />
For AC97 emulation just add the audio card device and map it to a host audio backend id<br />
<br />
-device AC97,audiodev=snd0<br />
<br />
==== Without audiodev ====<br />
<br />
To get list of the supported emulation audio drivers:<br />
$ qemu-system-x86_64 -soundhw help<br />
<br />
To use e.g. {{ic|intel-hda}} driver for the guest use the {{ic|-device intel-hda -device hda-duplex}} command with QEMU.<br />
<br />
{{Note|Video graphic card emulated drivers for the guest machine may also cause a problem with the sound quality. Test one by one to make it work. You can list possible options with {{ic|<nowiki>qemu-system-x86_64 -h | grep vga</nowiki>}}.}}<br />
<br />
== Installing virtio drivers ==<br />
<br />
QEMU offers guests the ability to use paravirtualized block and network devices using the [http://wiki.libvirt.org/page/Virtio virtio] drivers, which provide better performance and lower overhead.<br />
<br />
* A virtio block device requires the option {{Ic|-drive}} for passing a disk image, with parameter {{Ic|1=if=virtio}}:<br />
$ qemu-system-x86_64 -boot order=c -drive file=''disk_image'',if=virtio<br />
<br />
* Almost the same goes for the network:<br />
$ qemu-system-x86_64 -nic user,model=virtio-net-pci<br />
<br />
{{Note|This will only work if the guest machine has drivers for virtio devices. Linux does, and the required drivers are included in Arch Linux, but there is no guarantee that virtio devices will work with other operating systems.}}<br />
<br />
=== Preparing an (Arch) Linux guest ===<br />
<br />
To use virtio devices after an Arch Linux guest has been installed, the following modules must be loaded in the guest: {{Ic|virtio}}, {{Ic|virtio_pci}}, {{Ic|virtio_blk}}, {{Ic|virtio_net}}, and {{Ic|virtio_ring}}. For 32-bit guests, the specific "virtio" module is not necessary.<br />
<br />
If you want to boot from a virtio disk, the initial ramdisk must contain the necessary modules. By default, this is handled by [[mkinitcpio]]'s {{ic|autodetect}} hook. Otherwise use the {{ic|MODULES}} array in {{ic|/etc/mkinitcpio.conf}} to include the necessary modules and rebuild the initial ramdisk.<br />
<br />
{{hc|/etc/mkinitcpio.conf|2=<br />
MODULES=(virtio virtio_blk virtio_pci virtio_net)}}<br />
<br />
Virtio disks are recognized with the prefix {{ic|'''v'''}} (e.g. {{ic|'''v'''da}}, {{ic|'''v'''db}}, etc.); therefore, changes must be made in at least {{ic|/etc/fstab}} and {{ic|/boot/grub/grub.cfg}} when booting from a virtio disk.<br />
<br />
{{Tip|When referencing disks by [[UUID]] in both {{ic|/etc/fstab}} and bootloader, nothing has to be done.}}<br />
<br />
Further information on paravirtualization with KVM can be found [http://www.linux-kvm.org/page/Boot_from_virtio_block_device here].<br />
<br />
You might also want to install {{Pkg|qemu-guest-agent}} to implement support for QMP commands that will enhance the hypervisor management capabilities. After installing the package you can enable and start the {{ic|qemu-ga.service}}.<br />
<br />
=== Preparing a Windows guest ===<br />
<br />
==== Block device drivers ====<br />
<br />
===== New Install of Windows =====<br />
<br />
Windows does not come with the virtio drivers. Therefore, you will need to load them during installation. There are basically two ways to do this: via Floppy Disk or via ISO files. Both images can be downloaded from the [https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/stable-virtio/virtio-win.iso Fedora repository].<br />
<br />
The floppy disk option is difficult because you will need to press F6 (Shift-F6 on newer Windows) at the very beginning of powering on the QEMU. This is difficult since you need time to connect your VNC console window. You can attempt to add a delay to the boot sequence. See {{man|1|qemu}} for more details about applying a delay at boot.<br />
<br />
The ISO option to load drivers is the preferred way, but it is available only on Windows Vista and Windows Server 2008 and later. The procedure is to load the image with virtio drivers in an additional cdrom device along with the primary disk device and Windows installer:<br />
<br />
$ qemu-system-x86_64 ... \<br />
-drive file=''windows_disk_image'',index=0,media=disk,if=virtio \<br />
-drive file=''windows.iso'',index=2,media=cdrom \<br />
-drive file=''virtio.iso'',index=3,media=cdrom \<br />
...<br />
<br />
During the installation, at some stage, the Windows installer will ask "Where do you want to install Windows?", it will give a warning that no disks are found. Follow the example instructions below (based on Windows Server 2012 R2 with Update).<br />
<br />
* Select the option ''Load Drivers''.<br />
* Uncheck the box for ''Hide drivers that aren't compatible with this computer's hardware''.<br />
* Click the browse button and open the CDROM for the virtio iso, usually named "virtio-win-XX".<br />
* Now browse to {{ic|E:\viostor\[your-os]\amd64}}, select it, and confirm.<br />
<br />
You should now see your virtio disk(s) listed here, ready to be selected, formatted and installed to.<br />
<br />
===== Change Existing Windows VM to use virtio =====<br />
<br />
Modifying an existing Windows guest for booting from virtio disk requires that the virtio driver is available in the guest and that it is loaded at boot time.<br />
<br />
One can find the virtio disk driver in the [https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/stable-virtio/virtio-win.iso Fedora repository].<br />
<br />
Now, create a new disk image that will be used to search for the virtio driver:<br />
<br />
$ qemu-img create -f qcow2 ''fake.qcow2'' 1G<br />
<br />
Run the original Windows guest (with the boot disk still in IDE mode) with the fake disk (in virtio mode) and a CD-ROM with the driver.<br />
<br />
$ qemu-system-x86_64 -m 512 -drive file=''windows_disk_image'',if=ide -drive file=''fake.qcow2'',if=virtio -cdrom virtio-win-0.1-81.iso<br />
<br />
Windows will detect the fake disk and look for a suitable driver. If it fails, go to ''Device Manager'', locate the SCSI drive with an exclamation mark icon (should be open), click ''Update driver'' and select the virtual CD-ROM. Do not navigate to the driver folder within the CD-ROM, simply select the CD-ROM drive and Windows will find the appropriate driver automatically (tested for Windows 7 SP1).<br />
<br />
Request Windows to boot in safe mode next time it starts up. This can be done using the ''msconfig.exe'' tool in Windows. In safe mode all the drivers will be loaded at boot time including the new virtio driver. Once Windows knows that the virtio driver is required at boot it will memorize it for future boot.<br />
<br />
Once instructed to boot in safe mode, you can turn off the virtual machine and launch it again, now with the boot disk attached in virtio mode:<br />
<br />
$ qemu-system-x86_64 -m 512 -drive file=''windows_disk_image'',if=virtio<br />
<br />
You should boot in safe mode with virtio driver loaded, you can now return to ''msconfig.exe'' disable safe mode boot and restart Windows.<br />
<br />
{{Note|If you encounter the blue screen of death using the {{ic|1=if=virtio}} parameter, it probably means the virtio disk driver is not installed or not loaded at boot time, reboot in safe mode and check your driver configuration.}}<br />
<br />
==== Network drivers ====<br />
<br />
Installing virtio network drivers is a bit easier, simply add the {{ic|-nic}} argument.<br />
<br />
$ qemu-system-x86_64 -m 512 -drive file=''windows_disk_image'',if=virtio -nic user,model=virtio-net-pci -cdrom virtio-win-0.1-74.iso<br />
<br />
Windows will detect the network adapter and try to find a driver for it. If it fails, go to the ''Device Manager'', locate the network adapter with an exclamation mark icon (should be open), click ''Update driver'' and select the virtual CD-ROM. Do not forget to select the checkbox which says to search for directories recursively.<br />
<br />
==== Balloon driver ====<br />
<br />
If you want to track you guest memory state (for example via {{ic|virsh}} command {{ic|dommemstat}}) or change guest's memory size in runtime (you still will not be able to change memory size, but can limit memory usage via inflating balloon driver) you will need to install guest balloon driver.<br />
<br />
For this you will need to go to ''Device Manager'', locate ''PCI standard RAM Controller'' in ''System devices'' (or unrecognized PCI controller from ''Other devices'') and choose ''Update driver''. In opened window you will need to choose ''Browse my computer...'' and select the CD-ROM (and do not forget the ''Include subdirectories'' checkbox). Reboot after installation. This will install the driver and you will be able to inflate the balloon (for example via hmp command {{ic|balloon ''memory_size''}}, which will cause balloon to take as much memory as possible in order to shrink the guest's available memory size to ''memory_size''). However, you still will not be able to track guest memory state. In order to do this you will need to install ''Balloon'' service properly. For that open command line as administrator, go to the CD-ROM, ''Balloon'' directory and deeper, depending on your system and architecture. Once you are in ''amd64'' (''x86'') directory, run {{ic|blnsrv.exe -i}} which will do the installation. After that {{ic|virsh}} command {{ic|dommemstat}} should be outputting all supported values.<br />
<br />
=== Preparing a FreeBSD guest ===<br />
<br />
Install the {{ic|emulators/virtio-kmod}} port if you are using FreeBSD 8.3 or later up until 10.0-CURRENT where they are included into the kernel. After installation, add the following to your {{ic|/boot/loader.conf}} file:<br />
<br />
{{bc|1=<br />
virtio_load="YES"<br />
virtio_pci_load="YES"<br />
virtio_blk_load="YES"<br />
if_vtnet_load="YES"<br />
virtio_balloon_load="YES"<br />
}}<br />
<br />
Then modify your {{ic|/etc/fstab}} by doing the following:<br />
<br />
# sed -ibak "s/ada/vtbd/g" /etc/fstab<br />
<br />
And verify that {{ic|/etc/fstab}} is consistent. If anything goes wrong, just boot into a rescue CD and copy {{ic|/etc/fstab.bak}} back to {{ic|/etc/fstab}}.<br />
<br />
== QEMU monitor ==<br />
<br />
While QEMU is running, a monitor console is provided in order to provide several ways to interact with the virtual machine running. The QEMU monitor offers interesting capabilities such as obtaining information about the current virtual machine, hotplugging devices, creating snapshots of the current state of the virtual machine, etc. To see the list of all commands, run {{ic|help}} or {{ic|?}} in the QEMU monitor console or review the relevant section of the [https://qemu.weilnetz.de/doc/qemu-doc.html#pcsys_005fmonitor official QEMU documentation].<br />
<br />
=== Accessing the monitor console ===<br />
<br />
==== Graphical view ====<br />
<br />
When using the {{ic|std}} default graphics option, one can access the QEMU monitor by pressing {{ic|Ctrl+Alt+2}} or by clicking ''View > compatmonitor0'' in the QEMU window. To return to the virtual machine graphical view either press {{ic|Ctrl+Alt+1}} or click ''View > VGA''.<br />
<br />
However, the standard method of accessing the monitor is not always convenient and does not work in all graphic outputs QEMU supports.<br />
<br />
==== Telnet ====<br />
<br />
To enable [[telnet]], run QEMU with the {{ic|-monitor telnet:127.0.0.1:''port'',server,nowait}} parameter. When the virtual machine is started you will be able to access the monitor via telnet:<br />
<br />
$ telnet 127.0.0.1 ''port''<br />
<br />
{{Note|If {{ic|127.0.0.1}} is specified as the IP to listen it will be only possible to connect to the monitor from the same host QEMU is running on. If connecting from remote hosts is desired, QEMU must be told to listen {{ic|0.0.0.0}} as follows: {{ic|-monitor telnet:0.0.0.0:''port'',server,nowait}}. Keep in mind that it is recommended to have a [[firewall]] configured in this case or make sure your local network is completely trustworthy since this connection is completely unauthenticated and unencrypted.}}<br />
<br />
==== UNIX socket ====<br />
<br />
Run QEMU with the {{ic|-monitor unix:''socketfile'',server,nowait}} parameter. Then you can connect with either {{pkg|socat}} or {{pkg|openbsd-netcat}}.<br />
<br />
For example, if QEMU is run via:<br />
<br />
$ qemu-system-x86_64 ''[...]'' -monitor unix:/tmp/monitor.sock,server,nowait ''[...]''<br />
<br />
It is possible to connect to the monitor with:<br />
<br />
$ socat - UNIX-CONNECT:/tmp/monitor.sock<br />
<br />
Or with:<br />
<br />
$ nc -U /tmp/monitor.sock<br />
<br />
==== TCP ====<br />
<br />
You can expose the monitor over TCP with the argument {{ic|-monitor tcp:127.0.0.1:''port'',server,nowait}}. Then connect with netcat, either {{pkg|openbsd-netcat}} or {{pkg|gnu-netcat}} by running:<br />
<br />
$ nc 127.0.0.1 ''port''<br />
<br />
{{Note|In order to be able to connect to the tcp socket from other devices other than the same host QEMU is being run on you need to listen to {{ic|0.0.0.0}} like explained in the telnet case. The same security warnings apply in this case as well.}}<br />
<br />
==== Standard I/O ====<br />
<br />
It is possible to access the monitor automatically from the same terminal QEMU is being run by running it with the argument {{ic|-monitor stdio}}.<br />
<br />
=== Sending keyboard presses to the virtual machine using the monitor console ===<br />
<br />
Some combinations of keys may be difficult to perform on virtual machines due to the host intercepting them instead in some configurations (a notable example is the {{ic|Ctrl+Alt+F*}} key combinations, which change the active tty). To avoid this problem, the problematic combination of keys may be sent via the monitor console instead. Switch to the monitor and use the {{ic|sendkey}} command to forward the necessary keypresses to the virtual machine. For example:<br />
<br />
(qemu) sendkey ctrl-alt-f2<br />
<br />
=== Creating and managing snapshots via the monitor console ===<br />
<br />
{{Note|This feature will '''only''' work when the virtual machine disk image is in ''qcow2'' format. It will not work with ''raw'' images.}}<br />
<br />
It is sometimes desirable to save the current state of a virtual machine and having the possibility of reverting the state of the virtual machine to that of a previously saved snapshot at any time. The QEMU monitor console provides the user with the necessary utilities to create snapshots, manage them, and revert the machine state to a saved snapshot.<br />
<br />
* Use {{ic|savevm ''name''}} in order to create a snapshot with the tag ''name''.<br />
* Use {{ic|loadvm ''name''}} to revert the virtual machine to the state of the snapshot ''name''.<br />
* Use {{ic|delvm ''name''}} to delete the snapshot tagged as ''name''.<br />
* Use {{ic|info snapshots}} to see a list of saved snapshots. Snapshots are identified by both an auto-incremented ID number and a text tag (set by the user on snapshot creation).<br />
<br />
=== Running the virtual machine in immutable mode ===<br />
<br />
It is possible to run a virtual machine in a frozen state so that all changes will be discarded when the virtual machine is powered off just by running QEMU with the {{ic|-snapshot}} parameter. When the disk image is written by the guest, changes will be saved in a temporary file in {{ic|/tmp}} and will be discarded when QEMU halts.<br />
<br />
However, if a machine is running in frozen mode it is still possible to save the changes to the disk image if it is afterwards desired by using the monitor console and running the following command:<br />
<br />
(qemu) commit all<br />
<br />
If snapshots are created when running in frozen mode they will be discarded as soon as QEMU is exited unless changes are explicitly commited to disk, as well.<br />
<br />
=== Pause and power options via the monitor console ===<br />
<br />
Some operations of a physical machine can be emulated by QEMU using some monitor commands:<br />
<br />
* {{ic|system_powerdown}} will send an ACPI shutdown request to the virtual machine. This effect is similar to the power button in a physical machine.<br />
* {{ic|system_reset}} will reset the virtual machine similarly to a reset button in a physical machine. This operation can cause data loss and file system corruption since the virtual machine is not cleanly restarted.<br />
* {{ic|stop}} will pause the virtual machine.<br />
* {{ic|cont}} will resume a virtual machine previously paused.<br />
<br />
=== Taking screenshots of the virtual machine ===<br />
<br />
Screenshots of the virtual machine graphic display can be obtained in the PPM format by running the following command in the monitor console:<br />
<br />
(qemu) screendump ''file.ppm''<br />
<br />
== QEMU machine protocol ==<br />
<br />
The QEMU machine protocol (QMP) is a JSON-based protocol which allows applications to control a QEMU instance. Similarly to the [[#QEMU monitor]] it offers ways to interact with a running machine and the JSON protocol allows to do it programmatically. The description of all the QMP commands can be found in [https://raw.githubusercontent.com/coreos/qemu/master/qmp-commands.hx qmp-commands].<br />
<br />
=== Start QMP ===<br />
<br />
The usual way to control the guest using the QMP protocol, is to open a TCP socket when launching the machine using the {{ic|-qmp}} option. Here it is using for example the TCP port 4444:<br />
<br />
$ qemu-system-x86_64 ''[...]'' -qmp tcp:localhost:4444,server,nowait<br />
<br />
Then one way to communicate with the QMP agent is to use [[netcat]]:<br />
<br />
{{hc|nc localhost 4444|{"QMP": {"version": {"qemu": {"micro": 0, "minor": 1, "major": 3}, "package": ""}, "capabilities": []} } }}<br />
<br />
At this stage, the only command that can be recognized is {{ic|qmp_capabilities}}, so that QMP enters into command mode. Type:<br />
<br />
{"execute": "qmp_capabilities"}<br />
<br />
Now, QMP is ready to receive commands, to retrieve the list of recognized commands, use:<br />
<br />
{"execute": "query-commands"}<br />
<br />
=== Live merging of child image into parent image ===<br />
<br />
It is possible to merge a running snapshot into its parent by issuing a {{ic|block-commit}} command. In its simplest form the following line will commit the child into its parent:<br />
<br />
{"execute": "block-commit", "arguments": {"device": "''devicename''"}}<br />
<br />
Upon reception of this command, the handler looks for the base image and converts it from read only to read write mode and then runs the commit job.<br />
<br />
Once the ''block-commit'' operation has completed, the event {{ic|BLOCK_JOB_READY}} will be emitted, signalling that the synchronization has finished. The job can then be gracefully completed by issuing the command {{ic|block-job-complete}}:<br />
<br />
{"execute": "block-job-complete", "arguments": {"device": "''devicename''"}}<br />
<br />
Until such a command is issued, the ''commit'' operation remains active.<br />
After successful completion, the base image remains in read write mode and becomes the new active layer. On the other hand, the child image becomes invalid and it is the responsibility of the user to clean it up.<br />
<br />
{{Tip|The list of device and their names can be retrieved by executing the command {{ic|query-block}} and parsing the results. The device name is in the {{ic|device}} field, for example {{ic|ide0-hd0}} for the hard disk in this example: {{hc|{"execute": "query-block"}|{"return": [{"io-status": "ok", "device": "'''ide0-hd0'''", "locked": false, "removable": false, "inserted": {"iops_rd": 0, "detect_zeroes": "off", "image": {"backing-image": {"virtual-size": 27074281472, "filename": "parent.qcow2", ... } }} }}<br />
<br />
=== Live creation of a new snapshot ===<br />
<br />
To create a new snapshot out of a running image, run the command:<br />
<br />
{"execute": "blockdev-snapshot-sync", "arguments": {"device": "''devicename''","snapshot-file": "''new_snapshot_name''.qcow2"}}<br />
<br />
This creates an overlay file named {{ic|''new_snapshot_name''.qcow2}} which then becomes the new active layer.<br />
<br />
== Tips and tricks ==<br />
=== Improve virtual machine performance ===<br />
<br />
There are a number of techniques that you can use to improve the performance of the virtual machine. For example:<br />
<br />
* Apply [[#Enabling KVM]]: add {{ic|-enable-kvm}} to the QEMU start command you use.<br />
* Use the {{ic|-cpu host}} option to make QEMU emulate the host's exact CPU. If you do not do this, it may be trying to emulate a more generic CPU.<br />
* Especially for Windows guests, enable [http://blog.wikichoon.com/2014/07/enabling-hyper-v-enlightenments-with-kvm.html Hyper-V enlightenments]: {{ic|1=-cpu host,hv_relaxed,hv_spinlocks=0x1fff,hv_vapic,hv_time}}.<br />
* If the host machine has multiple cores, assign the guest more cores using the {{ic|-smp}} option.<br />
* Make sure you have assigned the virtual machine enough memory. By default, QEMU only assigns 128 MiB of memory to each virtual machine. Use the {{ic|-m}} option to assign more memory. For example, {{ic|-m 1024}} runs a virtual machine with 1024 MiB of memory.<br />
* If supported by drivers in the guest operating system, use [http://wiki.libvirt.org/page/Virtio virtio] for network and/or block devices. For example:<br />
$ qemu-system-x86_64 -net nic,model=virtio -net tap,if=tap0,script=no -drive file=''disk_image'',media=disk,if=virtio<br />
* Use TAP devices instead of user-mode networking. See [[#Tap networking with QEMU]].<br />
* If the guest OS is doing heavy writing to its disk, you may benefit from certain mount options on the host's file system. For example, you can mount an [[Ext4|ext4 file system]] with the option {{ic|1=barrier=0}}. You should read the documentation for any options that you change because sometimes performance-enhancing options for file systems come at the cost of data integrity.<br />
* If you have a raw disk image, you may want to disable the cache:<br />
$ qemu-system-x86_64 -drive file=''disk_image'',if=virtio,'''cache=none'''<br />
* Use the native Linux AIO:<br />
$ qemu-system-x86_64 -drive file=''disk_image'',if=virtio''',aio=native,cache.direct=on'''<br />
* If you are running multiple virtual machines concurrently that all have the same operating system installed, you can save memory by enabling [[wikipedia:Kernel_SamePage_Merging_(KSM)|kernel same-page merging]]. See [[#Enabling KSM]].<br />
* In some cases, memory can be reclaimed from running virtual machines by running a memory ballooning driver in the guest operating system and launching QEMU using {{ic|-device virtio-balloon}}.<br />
* It is possible to use a emulation layer for an ICH-9 AHCI controller (although it may be unstable). The AHCI emulation supports [[Wikipedia:Native_Command_Queuing|NCQ]], so multiple read or write requests can be outstanding at the same time:<br />
$ qemu-system-x86_64 -drive id=disk,file=''disk_image'',if=none -device ich9-ahci,id=ahci -device ide-drive,drive=disk,bus=ahci.0<br />
<br />
See http://www.linux-kvm.org/page/Tuning_KVM for more information.<br />
<br />
=== Starting QEMU virtual machines on boot ===<br />
<br />
==== With libvirt ====<br />
<br />
If a virtual machine is set up with [[libvirt]], it can be configured with {{ic|virsh autostart}} or through the ''virt-manager'' GUI to start at host boot by going to the Boot Options for the virtual machine and selecting "Start virtual machine on host boot up".<br />
<br />
==== With systemd service ====<br />
<br />
To run QEMU VMs on boot, you can use following systemd unit and config.<br />
<br />
{{hc|/etc/systemd/system/qemu@.service|2=<br />
[Unit]<br />
Description=QEMU virtual machine<br />
<br />
[Service]<br />
Environment="haltcmd=kill -INT $MAINPID"<br />
EnvironmentFile=/etc/conf.d/qemu.d/%i<br />
ExecStart=/usr/bin/qemu-system-x86_64 -name %i -enable-kvm -m 512 -nographic $args<br />
ExecStop=/usr/bin/bash -c ${haltcmd}<br />
ExecStop=/usr/bin/bash -c 'while nc localhost 7100; do sleep 1; done'<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
}}<br />
<br />
{{Note|This service will wait for the console port to be released, which means that the VM has been shutdown, to graciously end.}}<br />
<br />
Then create per-VM configuration files, named {{ic|/etc/conf.d/qemu.d/''vm_name''}}, with the variables {{ic|args}} and {{ic|haltcmd}} set. Example configs:<br />
<br />
{{hc|/etc/conf.d/qemu.d/one|2=<br />
args="-hda /dev/vg0/vm1 -serial telnet:localhost:7000,server,nowait,nodelay \<br />
-monitor telnet:localhost:7100,server,nowait,nodelay -vnc :0"<br />
<br />
haltcmd="echo 'system_powerdown' {{!}} nc localhost 7100" # or netcat/ncat}}<br />
<br />
{{hc|/etc/conf.d/qemu.d/two|2=<br />
args="-hda /srv/kvm/vm2 -serial telnet:localhost:7001,server,nowait,nodelay -vnc :1"<br />
<br />
haltcmd="ssh powermanager@vm2 sudo poweroff"}}<br />
<br />
The description of the variables is the following:<br />
<br />
* {{ic|args}} - QEMU command line arguments to be used.<br />
* {{ic|haltcmd}} - Command to shut down a VM safely. In the first example, the QEMU monitor is exposed via telnet using {{ic|-monitor telnet:..}} and the VMs are powered off via ACPI by sending {{ic|system_powerdown}} to monitor with the {{ic|nc}} command. In the other example, SSH is used.<br />
<br />
To set which virtual machines will start on boot-up, [[enable]] the {{ic|qemu@''vm_name''.service}} systemd unit.<br />
<br />
=== Mouse integration ===<br />
<br />
To prevent the mouse from being grabbed when clicking on the guest operating system's window, add the options {{ic|-usb -device usb-tablet}}. This means QEMU is able to report the mouse position without having to grab the mouse. This also overrides PS/2 mouse emulation when activated. For example:<br />
<br />
$ qemu-system-x86_64 -hda ''disk_image'' -m 512 -usb -device usb-tablet<br />
<br />
If that does not work, try using {{ic|-vga qxl}} parameter, also look at the instructions [[#Mouse cursor is jittery or erratic]].<br />
<br />
=== Pass-through host USB device ===<br />
<br />
It is possible to access the physical device connected to a USB port of the host from the guest. The first step is to identify where the device is connected, this can be found running the {{ic|lsusb}} command. For example:<br />
<br />
{{hc|$ lsusb|<br />
...<br />
Bus '''003''' Device '''007''': ID '''0781''':'''5406''' SanDisk Corp. Cruzer Micro U3<br />
}}<br />
<br />
The outputs in bold above will be useful to identify respectively the ''host_bus'' and ''host_addr'' or the ''vendor_id'' and ''product_id''.<br />
<br />
In qemu, the idea is to emulate an EHCI (USB 2) or XHCI (USB 3) controller with the option {{ic|1=-device usb-ehci,id=ehci}} or {{ic|1=-device qemu-xhci,id=xhci}} respectively and then attach the physical device to it with the option {{ic|1=-device usb-host,..}}. We will consider that ''controller_id'' is either {{ic|ehci}} or {{ic|xhci}} for the rest of this section.<br />
<br />
Then, there are two ways to connect to the USB of the host with qemu:<br />
<br />
# Identify the device and connect to it on any bus and address it is attached to on the host, the generic syntax is: {{bc|1=-device usb-host,bus=''controller_id''.0,vendorid=0x''vendor_id'',productid=0x''product_id''}}Applied to the device used in the example above, it becomes:{{bc|1=-device usb-ehci,id=ehci -device usb-host,bus=ehci.0,vendorid=0x'''0781''',productid=0x'''5406'''}}One can also add the {{ic|1=...,port=''port_number''}} setting to the previous option to specify in which physical port of the virtual controller the device should be attached, useful in the case one wants to add multiple usb devices to the VM.<br />
# Starting from QEMU 5.1.0, the {{ic|usb-host}} {{ic|hostdevice}} property can also be used: {{bc|1=-device qemu-xhci,id=xhci -device usb-host,bus=xhci.0,hostdevice=/dev/bus/usb/003/007}}<br />
# Attach whatever is connected to a given USB bus and address, the syntax is:{{bc|1=-device usb-host,bus=''controller_id''.0,hostbus=''host_bus'',host_addr=''host_addr''}}Applied to the bus and the address in the example above, it becomes:{{bc|1=-device usb-ehci,id=ehci -device usb-host,bus=ehci.0,hostbus='''3''',hostaddr='''7'''}}<br />
<br />
{{Note|If you encounter permission errors when running QEMU, see [[udev#About udev rules]] for information on how to set permissions of the device.}}<br />
<br />
=== USB redirection with SPICE ===<br />
<br />
When using [[#SPICE]] it is possible to redirect USB devices from the client to the virtual machine without needing to specify them in the QEMU command. It is possible to configure the number of USB slots available for redirected devices (the number of slots will determine the maximum number of devices which can be redirected simultaneously). The main advantages of using SPICE for redirection compared to the previously-mentioned {{ic|-usbdevice}} method is the possibility of hot-swapping USB devices after the virtual machine has started, without needing to halt it in order to remove USB devices from the redirection or adding new ones. This method of USB redirection also allows us to redirect USB devices over the network, from the client to the server. In summary, it is the most flexible method of using USB devices in a QEMU virtual machine.<br />
<br />
We need to add one EHCI/UHCI controller per available USB redirection slot desired as well as one SPICE redirection channel per slot. For example, adding the following arguments to the QEMU command you use for starting the virtual machine in SPICE mode will start the virtual machine with three available USB slots for redirection:<br />
<br />
{{bc|1=-device ich9-usb-ehci1,id=usb \<br />
-device ich9-usb-uhci1,masterbus=usb.0,firstport=0,multifunction=on \<br />
-device ich9-usb-uhci2,masterbus=usb.0,firstport=2 \<br />
-device ich9-usb-uhci3,masterbus=usb.0,firstport=4 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev1 -device usb-redir,chardev=usbredirchardev1,id=usbredirdev1 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev2 -device usb-redir,chardev=usbredirchardev2,id=usbredirdev2 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev3 -device usb-redir,chardev=usbredirchardev3,id=usbredirdev3}}<br />
See [https://www.spice-space.org/usbredir.html SPICE/usbredir] for more information.<br />
<br />
Both {{ic|spicy}} from {{Pkg|spice-gtk}} (''Input > Select USB Devices for redirection'') and {{ic|remote-viewer}} from {{pkg|virt-viewer}} (''File > USB device selection'') support this feature. Please make sure that you have installed the necessary SPICE Guest Tools on the virtual machine for this functionality to work as expected (see the [[#SPICE]] section for more information).<br />
<br />
{{Warning|Keep in mind that when a USB device is redirected from the client, it will not be usable from the client operating system itself until the redirection is stopped. It is specially important to never redirect the input devices (namely mouse and keyboard), since it will be then difficult to access the SPICE client menus to revert the situation, because the client will not respond to the input devices after being redirected to the virtual machine.}}<br />
<br />
=== Enabling KSM ===<br />
<br />
Kernel Samepage Merging (KSM) is a feature of the Linux kernel that allows for an application to register with the kernel to have its pages merged with other processes that also register to have their pages merged. The KSM mechanism allows for guest virtual machines to share pages with each other. In an environment where many of the guest operating systems are similar, this can result in significant memory savings.<br />
<br />
{{Note|Although KSM may reduce memory usage, it may increase CPU usage. Also note some security issues may occur, see [[Wikipedia:Kernel same-page merging]].}}<br />
<br />
To enable KSM:<br />
<br />
# echo 1 > /sys/kernel/mm/ksm/run<br />
<br />
To make it permanent, use [[systemd#systemd-tmpfiles - temporary files|systemd's temporary files]]:<br />
<br />
{{hc|/etc/tmpfiles.d/ksm.conf|<br />
w /sys/kernel/mm/ksm/run - - - - 1<br />
}}<br />
<br />
If KSM is running, and there are pages to be merged (i.e. at least two similar VMs are running), then {{ic|/sys/kernel/mm/ksm/pages_shared}} should be non-zero. See https://www.kernel.org/doc/html/latest/admin-guide/mm/ksm.html for more information.<br />
<br />
{{Tip|An easy way to see how well KSM is performing is to simply print the contents of all the files in that directory: {{bc|$ grep . /sys/kernel/mm/ksm/*}}}}<br />
<br />
=== Multi-monitor support ===<br />
<br />
The Linux QXL driver supports four heads (virtual screens) by default. This can be changed via the {{ic|1=qxl.heads=N}} kernel parameter.<br />
<br />
The default VGA memory size for QXL devices is 16M (VRAM size is 64M). This is not sufficient if you would like to enable two 1920x1200 monitors since that requires 2 × 1920 × 4 (color depth) × 1200 = 17.6 MiB VGA memory. This can be changed by replacing {{ic|-vga qxl}} by {{ic|<nowiki>-vga none -device qxl-vga,vgamem_mb=32</nowiki>}}. If you ever increase vgamem_mb beyond 64M, then you also have to increase the {{ic|vram_size_mb}} option.<br />
<br />
=== Copy and paste ===<br />
<br />
One way to share the clipboard between the host and the guest is to enable the SPICE remote desktop protocol and access the client with a SPICE client.<br />
One needs to follow the steps described in [[#SPICE]]. A guest run this way will support copy paste with the host.<br />
<br />
=== Windows-specific notes ===<br />
<br />
QEMU can run any version of Windows from Windows 95 through Windows 10.<br />
<br />
It is possible to run [[Windows PE]] in QEMU.<br />
<br />
==== Fast startup ====<br />
<br />
{{Note|An administrator account is required to change power settings.}}<br />
<br />
For Windows 8 (or later) guests it is better to disable "Turn on fast startup (recommended)" from the Power Options of the Control Panel as explained in the following [https://www.tenforums.com/tutorials/4189-turn-off-fast-startup-windows-10-a.html forum page], as it causes the guest to hang during every other boot.<br />
<br />
Fast Startup may also need to be disabled for changes to the {{ic|-smp}} option to be properly applied.<br />
<br />
==== Remote Desktop Protocol ====<br />
<br />
If you use a MS Windows guest, you might want to use RDP to connect to your guest VM. If you are using a VLAN or are not in the same network as the guest, use:<br />
<br />
$ qemu-system-x86_64 -nographic -net user,hostfwd=tcp::5555-:3389<br />
<br />
Then connect with either {{Pkg|rdesktop}} or {{Pkg|freerdp}} to the guest. For example:<br />
<br />
$ xfreerdp -g 2048x1152 localhost:5555 -z -x lan<br />
<br />
=== Clone Linux system installed on physical equipment ===<br />
<br />
Linux system installed on physical equipment can be cloned for running on QEMU vm. See [https://coffeebirthday.wordpress.com/2018/09/14/clone-linux-system-for-qemu-virtual-machine/ Clone Linux system from hardware for QEMU virtual machine]<br />
<br />
=== Chrooting into arm/arm64 environment from x86_64 ===<br />
<br />
Sometimes it is easier to work directly on a disk image instead of the real ARM based device. This can be achieved by mounting an SD card/storage containing the ''root'' partition and chrooting into it.<br />
<br />
Another use case for an ARM chroot is building ARM packages on an x86_64 machine - {{AUR|armutils-git}} can be used for that. Here, the chroot environment can be created from an image tarball from [https://archlinuxarm.org Arch Linux ARM] - see [https://nerdstuff.org/posts/2020/2020-003_simplest_way_to_create_an_arm_chroot/] for a detailed description of this approach.<br />
<br />
Either way, from the chroot it should be possible to run ''pacman'' and install more packages, compile large libraries etc. Since the executables are for the ARM architecture, the translation to x86 needs to be performed by [[QEMU]].<br />
<br />
Install {{AUR|binfmt-qemu-static}} and {{AUR|qemu-user-static}} from the [[AUR]] on the x86_64 machine/host. ''binfmt-qemu-static'' will take care of registering the qemu binaries to binfmt service.<br />
<br />
[[Restart]] {{ic|systemd-binfmt.service}}<br />
<br />
{{AUR|qemu-user-static}} is needed to allow the execution of compiled programs from other architectures. This is similar to what is provided by {{Pkg|qemu-arch-extra}}, but the "static" variant is required for chroot. Examples:<br />
<br />
qemu-arm-static path_to_sdcard/usr/bin/ls<br />
qemu-aarch64-static path_to_sdcard/usr/bin/ls<br />
<br />
These two lines execute the {{ic|ls}} command compiled for 32-bit ARM and 64-bit ARM respectively. Note that this will not work without chrooting, because it will look for libraries not present in the host system.<br />
<br />
{{AUR|qemu-user-static}} allows automatically prefixing the ARM exectuable with {{ic|qemu-arm-static}} or {{ic|qemu-aarch64-static}}.<br />
<br />
Make sure that the ARM executable support is active:<br />
<br />
{{hc|$ ls /proc/sys/fs/binfmt_misc|<br />
qemu-aarch64 qemu-arm qemu-cris qemu-microblaze qemu-mipsel qemu-ppc64 qemu-riscv64 qemu-sh4 qemu-sparc qemu-sparc64 status<br />
qemu-alpha qemu-armeb qemu-m68k qemu-mips qemu-ppc qemu-ppc64abi32 qemu-s390x qemu-sh4eb qemu-sparc32plus register<br />
}}<br />
<br />
Each executable must be listed.<br />
<br />
If it is not active, reinstall ''binfmt-qemu-static'' and restart ''systemd-binfmt''.<br />
<br />
Mount the SD card to {{ic|/mnt/scdard}} (the device name may be different).<br />
<br />
# mkdir -p /mnt/sdcard<br />
# mount /dev/mmcblk0p2 /mnt/sdcard<br />
<br />
Mount boot partition if needed (again, use the suitable device name):<br />
<br />
# mount /dev/mmcblk0p1 /mnt/sdcard/boot<br />
<br />
Finally ''chroot'' into the SD card root as described in [[Change root#Using chroot]]:<br />
<br />
# chroot /mnt/sdcard /bin/bash<br />
<br />
Alternatively, you can use ''arch-chroot'' from {{Pkg|arch-install-scripts}}, as it will provide an easier way to get network support:<br />
# arch-chroot /mnt/sdcard /bin/bash<br />
<br />
You can also use ''systemd-nspawn'' to chroot into the ARM environment:<br />
# systemd-nspawn -D /mnt/sdcard -M myARMMachine --bind-ro=/etc/resolv.conf<br />
<br />
{{ic|1=--bind-ro=/etc/resolv.conf}} is optional and gives a working network DNS inside the chroot<br />
<br />
== Troubleshooting ==<br />
<br />
=== Mouse cursor is jittery or erratic ===<br />
<br />
If the cursor jumps around the screen uncontrollably, entering this on the terminal before starting QEMU might help:<br />
<br />
$ export SDL_VIDEO_X11_DGAMOUSE=0<br />
<br />
If this helps, you can add this to your {{ic|~/.bashrc}} file.<br />
<br />
=== No visible Cursor ===<br />
<br />
Add {{ic|-show-cursor}} to QEMU's options to see a mouse cursor.<br />
<br />
If that still does not work, make sure you have set your display device appropriately, for example: {{ic|-vga qxl}}.<br />
<br />
Another option to try is {{ic|-usb -device usb-tablet}} as mentioned in [[#Mouse integration]]. This overrides the default PS/2 mouse emulation and synchronizes pointer location between host and guest as an added bonus.<br />
<br />
=== Two different mouse cursors are visible ===<br />
<br />
Apply the tip [[#Mouse integration]].<br />
<br />
=== Keyboard issues when using VNC ===<br />
<br />
When using VNC, you might experience keyboard problems described (in gory details) [https://www.berrange.com/posts/2010/07/04/more-than-you-or-i-ever-wanted-to-know-about-virtual-keyboard-handling/ here]. The solution is ''not'' to use the {{ic|-k}} option on QEMU, and to use {{ic|gvncviewer}} from {{Pkg|gtk-vnc}}. See also [http://www.mail-archive.com/libvir-list@redhat.com/msg13340.html this] message posted on libvirt's mailing list.<br />
<br />
=== Keyboard seems broken or the arrow keys do not work ===<br />
<br />
Should you find that some of your keys do not work or "press" the wrong key (in particular, the arrow keys), you likely need to specify your keyboard layout as an option. The keyboard layouts can be found in {{ic|/usr/share/qemu/keymaps}}.<br />
<br />
$ qemu-system-x86_64 -k ''keymap'' ''disk_image''<br />
<br />
=== Guest display stretches on window resize ===<br />
<br />
To restore default window size, press {{ic|Ctrl+Alt+u}}.<br />
<br />
=== ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy ===<br />
<br />
If an error message like this is printed when starting QEMU with {{ic|-enable-kvm}} option:<br />
<br />
ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy<br />
failed to initialize KVM: Device or resource busy<br />
<br />
that means another [[hypervisor]] is currently running. It is not recommended or possible to run several hypervisors in parallel.<br />
<br />
=== libgfapi error message ===<br />
<br />
The error message displayed at startup:<br />
<br />
Failed to open module: libgfapi.so.0: cannot open shared object file: No such file or directory<br />
<br />
[[Install]] {{pkg|glusterfs}} or ignore the error message as GlusterFS is a optional dependency.<br />
<br />
=== Kernel panic on LIVE-environments===<br />
<br />
If you start a live-environment (or better: booting a system) you may encounter this:<br />
<br />
[ end Kernel panic - not syncing: VFS: Unable to mount root fs on unknown block(0,0)<br />
<br />
or some other boot hindering process (e.g. cannot unpack initramfs, cant start service foo).<br />
Try starting the VM with the {{ic|-m VALUE}} switch and an appropriate amount of RAM, if the ram is to low you will probably encounter similar issues as above/without the memory-switch.<br />
<br />
=== Windows 7 guest suffers low-quality sound ===<br />
<br />
Using the {{ic|hda}} audio driver for Windows 7 guest may result in low-quality sound. Changing the audio driver to {{ic|ac97}} by passing the {{ic|-soundhw ac97}} arguments to QEMU and installing the AC97 driver from [https://www.realtek.com/en/component/zoo/category/pc-audio-codecs-ac-97-audio-codecs-software Realtek AC'97 Audio Codecs] in the guest may solve the problem. See [https://bugzilla.redhat.com/show_bug.cgi?id=1176761#c16 Red Hat Bugzilla – Bug 1176761] for more information.<br />
<br />
=== Could not access KVM kernel module: Permission denied ===<br />
<br />
If you encounter the following error:<br />
<br />
libvirtError: internal error: process exited while connecting to monitor: Could not access KVM kernel module: Permission denied failed to initialize KVM: Permission denied<br />
<br />
Systemd 234 assigns a dynamic ID for the {{ic|kvm}} group (see {{Bug|54943}}). To avoid this error, you need edit the file {{ic|/etc/libvirt/qemu.conf}} and change the line with {{ic|1=group = "78"}} to {{ic|1=group = "kvm"}}.<br />
<br />
=== "System Thread Exception Not Handled" when booting a Windows VM ===<br />
<br />
Windows 8 or Windows 10 guests may raise a generic compatibility exception at boot, namely "System Thread Exception Not Handled", which tends to be caused by legacy drivers acting strangely on real machines. On KVM machines this issue can generally be solved by setting the CPU model to {{ic|core2duo}}.<br />
<br />
=== Certain Windows games/applications crashing/causing a bluescreen ===<br />
<br />
Occasionally, applications running in the VM may crash unexpectedly, whereas they would run normally on a physical machine. If, while running {{ic|dmesg -wH}}, you encounter an error mentioning {{ic|MSR}}, the reason for those crashes is that KVM injects a [[wikipedia:General protection fault|General protection fault]] (GPF) when the guest tries to access unsupported [[wikipedia:Model-specific register|Model-specific registers]] (MSRs) - this often results in guest applications/OS crashing. A number of those issues can be solved by passing the {{ic|1=ignore_msrs=1}} option to the KVM module, which will ignore unimplemented MSRs.<br />
<br />
{{hc|/etc/modprobe.d/kvm.conf|2=<br />
...<br />
options kvm ignore_msrs=1<br />
...<br />
}}<br />
<br />
Cases where adding this option might help:<br />
<br />
* GeForce Experience complaining about an unsupported CPU being present.<br />
* StarCraft 2 and L.A. Noire reliably blue-screening Windows 10 with {{ic|KMODE_EXCEPTION_NOT_HANDLED}}. The blue screen information does not identify a driver file in these cases.<br />
<br />
{{Warning|While this is normally safe and some applications might not work without this, silently ignoring unknown MSR accesses could potentially break other software within the VM or other VMs.}}<br />
<br />
=== Applications in the VM experience long delays or take a long time to start ===<br />
<br />
This may be caused by insufficient available entropy in the VM. Consider allowing the guest to access the hosts's entropy pool by adding a [https://wiki.qemu.org/Features/VirtIORNG VirtIO RNG device] to the VM, or by installing an entropy generating daemon such as [[Haveged]].<br />
<br />
Anecdotally, OpenSSH takes a while to start accepting connections under insufficient entropy, without the logs revealing why.<br />
<br />
=== High interrupt latency and microstuttering ===<br />
<br />
This problem manifests itself as small pauses (stutters) and is particularly noticeable in graphics-intensive applications, such as games.<br />
<br />
* One of the causes is CPU power saving features, which are controlled by [[CPU frequency scaling]]. Change this to {{ic|performance}} for all processor cores. <br />
* Another possible cause is PS/2 inputs. Switch from PS/2 to Virtio inputs, see [[PCI passthrough via OVMF#Passing keyboard/mouse via Evdev]].<br />
<br />
=== QXL video causes low resolution ===<br />
<br />
QEMU 4.1.0 introduced a regression where QXL video can fall back to low resolutions, when being displayed through spice. [https://bugs.launchpad.net/qemu/+bug/1843151] For example, when KMS starts, text resolution may become as low as 4x10 characters. When trying to increase GUI resolution, it may go to the lowest supported resolution.<br />
<br />
As a workaround, create your device in this form:<br />
<br />
-device qxl-vga,max_outputs=1...<br />
<br />
=== Hang during VM initramfs ===<br />
<br />
Linux 5.2.11 introduced a KVM regression where under some circumstances a VM may permanently hang during the early boot phase, when the initramfs is being loaded or ran. [https://www.spinics.net/lists/kvm/msg195171.html] Linux 5.3 fixed the regression. The host shows qemu using 100% CPU * number of virtual CPUs. Reported case is with a host using hyperthreading, and a VM being given more than host's {{ic|nproc}}/2 virtual CPUs. It is unknown what exact circumstances trigger one of the threads to delete a memory region to cause this. The workarounds are:<br />
<br />
* Upgrade to Linux 5.3.<br />
* Downgrade to Linux 5.2.10<br />
* Until fixed, try giving the VM no more than the host's {{ic|nproc}}/2 virtual CPUs<br />
* Custom compile linux, reverting commit 2ad350fb4c (note this re-introduces a regression triggered when removing a memslot)<br />
<br />
=== VM does not boot when using a Secure Boot enabled OVMF ===<br />
<br />
{{ic|/usr/share/edk2-ovmf/x64/OVMF_CODE.secboot.fd}} from {{Pkg|edk2-ovmf}} is built with [[Wikipedia:System Management Mode|SMM]] support. If S3 support is not disabled in the VM, then the VM might not boot at all.<br />
<br />
Add the {{ic|1=-global ICH9-LPC.disable_s3=1}} option to the ''qemu'' command.<br />
<br />
See {{Bug|59465}} and https://github.com/tianocore/edk2/blob/master/OvmfPkg/README for more details and the required options to use Secure Boot in QEMU.<br />
<br />
=== Guest CPU interrupts are not firing ===<br />
<br />
If you are writing your own operating system by following the [https://wiki.osdev.org/ OSDev wiki], or are simply getting stepping through the guest architecture assembly code using QEMU's {{ic|gdb}} interface using the {{ic|-s}} flag, it's useful to know that many emulators, QEMU included, usually implement some CPU interrupts leaving many hardware interrupts unimplemented. One way to know if your code if firing an interrupt, is by using:<br />
<br />
-d int<br />
<br />
to enable showing interrupts/exceptions on stdout.<br />
<br />
To see what other guest debugging features QEMU has to offer, see:<br />
<br />
qemu-system-x86_64 -d help<br />
<br />
or replace {{ic|x86_64}} for your chosen guest architecture.<br />
<br />
== See also ==<br />
<br />
* [http://qemu.org Official QEMU website]<br />
* [http://www.linux-kvm.org Official KVM website]<br />
* [http://qemu.weilnetz.de/qemu-doc.html QEMU Emulator User Documentation]<br />
* [[Wikibooks:QEMU|QEMU Wikibook]]<br />
* [http://alien.slackbook.org/dokuwiki/doku.php?id=slackware:qemu Hardware virtualization with QEMU] by AlienBOB (last updated in 2008)<br />
* [http://blog.falconindy.com/articles/build-a-virtual-army.html Building a Virtual Army] by Falconindy<br />
* [http://git.qemu.org/?p=qemu.git;a=tree;f=docs Lastest docs]<br />
* [http://qemu.weilnetz.de/ QEMU on Windows]<br />
* [[wikipedia:Qemu|Wikipedia]]<br />
* [[debian:QEMU|Debian Wiki - QEMU]]<br />
* [https://people.gnome.org/~markmc/qemu-networking.html QEMU Networking on gnome.org]<br />
* [http://bsdwiki.reedmedia.net/wiki/networking_qemu_virtual_bsd_systems.html Networking QEMU Virtual BSD Systems]<br />
* [https://www.gnu.org/software/hurd/hurd/running/qemu.html QEMU on gnu.org]<br />
* [https://wiki.freebsd.org/qemu QEMU on FreeBSD as host]<br />
* [https://wiki.mikejung.biz/KVM_/_Xen KVM/QEMU Virtio Tuning and SSD VM Optimization Guide]<br />
* [https://doc.opensuse.org/documentation/leap/virtualization/html/book-virt/part-virt-qemu.html Managing Virtual Machines with QEMU - openSUSE documentation]<br />
* [https://www.ibm.com/support/knowledgecenter/en/linuxonibm/liaat/liaatkvm.htm KVM on IBM Knowledge Center]</div>Malcontenthttps://wiki.archlinux.org/index.php?title=QEMU&diff=634639QEMU2020-09-08T07:14:42Z<p>Malcontent: Use the bus/dev from the lsusb output above</p>
<hr />
<div>[[Category:Emulation]]<br />
[[Category:Hypervisors]]<br />
[[de:Qemu]]<br />
[[es:QEMU]]<br />
[[fr:Qemu]]<br />
[[ja:QEMU]]<br />
[[zh-hans:QEMU]]<br />
[[zh-hant:QEMU]]<br />
{{Related articles start}}<br />
{{Related|:Category:Hypervisors}}<br />
{{Related|Libvirt}}<br />
{{Related|QEMU/Guest graphics acceleration}}<br />
{{Related|PCI passthrough via OVMF}}<br />
{{Related articles end}}<br />
<br />
According to the [http://wiki.qemu.org/Main_Page QEMU about page], "QEMU is a generic and open source machine emulator and virtualizer."<br />
<br />
When used as a machine emulator, QEMU can run OSes and programs made for one machine (e.g. an ARM board) on a different machine (e.g. your x86 PC). By using dynamic translation, it achieves very good performance.<br />
<br />
QEMU can use other hypervisors like [[Xen]] or [[KVM]] to use CPU extensions ([[Wikipedia:Hardware-assisted virtualization|HVM]]) for virtualization. When used as a virtualizer, QEMU achieves near native performances by executing the guest code directly on the host CPU.<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|qemu}} package (or {{Pkg|qemu-headless}} for the version without GUI) and below optional packages for your needs:<br />
<br />
* {{Pkg|qemu-arch-extra}} - extra architectures support<br />
* {{Pkg|qemu-block-gluster}} - [[Glusterfs]] block support<br />
* {{Pkg|qemu-block-iscsi}} - [[iSCSI]] block support<br />
* {{Pkg|qemu-block-rbd}} - RBD block support <br />
* {{Pkg|samba}} - [[Samba|SMB/CIFS]] server support<br />
<br />
Alternatively, {{AUR|qemu-user-static}} exists as a usermode and static variant.<br />
<br />
=== QEMU variants ===<br />
<br />
QEMU is offered in several variants suited for different use cases.<br />
<br />
As a first classification, QEMU is offered in full-system and usermode emulation modes:<br />
<br />
; Full-system emulation<br />
: In this mode, QEMU emulates a full system, including one or several processors and various peripherals. It is more accurate but slower, and does not require the emulated OS to be Linux.<br />
: QEMU commands for full-system emulation are named {{ic|qemu-system-''target_architecture''}}, e.g. {{ic|qemu-system-x86_64}} for emulating intel 64-bit CPUs, {{ic|qemu-system-i386}} for intel 32 bits CPUs, {{ic|qemu-system-arm}} for ARM (32 bits), {{ic|qemu-system-aarch64}} for ARM64, etc.<br />
: If the target architecture matches the host CPU, this mode may still benefit from a significant speedup by using a hypervisor like [[#Enabling KVM|KVM]] or Xen.<br />
; [https://www.qemu.org/docs/master/user/main.html Usermode emulation]: In this mode, QEMU is able to invoke a Linux executable compiled for a (potentially) different architecture by leveraging the host system resources. There may be compatibility issues, e.g. some features may not be implemented, dynamically linked executables will not work out of the box (see [[#Chrooting into arm/arm64 environment from x86_64|the section below]] to address this) and only Linux is supported (although [https://wiki.winehq.org/Emulation Wine may be used] for running Windows executables).<br />
: QEMU commands for usermode emulation are named {{ic|qemu-''target_architecture''}}, e.g. {{ic|qemu-x86_64}} for emulating intel 64-bit CPUs.<br />
<br />
QEMU is offered in dynamically-linked and statically-linked variants:<br />
<br />
; Dynamically-linked (default): {{ic|qemu-*}} commands depend on the host OS libraries, so executables are smaller.<br />
; Statically-linked: {{ic|qemu-*}} commands can be copied to any Linux system with the same architecture.<br />
<br />
In the case of Arch Linux, full-system emulation is offered as:<br />
<br />
; Non-headless (default): This variant enables GUI features that require additional dependencies (like SDL or GTK).<br />
; Headless: This is a slimmer variant that does not require GUI (this is suitable e.g. for servers).<br />
<br />
Note that headless and non-headless versions install commands with the same name (e.g. {{ic|qemu-system-x86_64}}) and thus cannot be both installed at the same time.<br />
<br />
=== Details on packages offered in Arch Linux ===<br />
<br />
* The {{Pkg|qemu}} package provides the {{ic|x86_64}} architecture emulators for full-system emulation ({{ic|qemu-system-x86_64}}). The {{Pkg|qemu-arch-extra}} package provides the {{ic|x86_64}} usermode variant ({{ic|qemu-x86_64}}) and also for the rest of supported architectures it includes both full-system and usermode variants (e.g. {{ic|qemu-system-arm}} and {{ic|qemu-arm}}).<br />
* The headless versions of these packages (only applicable to full-system emulation) are {{Pkg|qemu-headless}} ({{ic|x86_64}}-only) and {{Pkg|qemu-headless-arch-extra}} (rest of architectures).<br />
* Full-system emulation can be expanded with some QEMU modules present in separate packages: {{Pkg|qemu-block-gluster}}, {{Pkg|qemu-block-iscsi}}, {{Pkg|qemu-block-rbd}} and {{Pkg|qemu-guest-agent}}.<br />
* The unofficial AUR package {{AUR|qemu-user-static}} provides a usermode and static variant for all target architectures supported by QEMU. A precompiled version of this package exists: {{AUR|qemu-user-static-bin}}. The installed QEMU commands are named {{ic|qemu-''target_architecture''-static}}, for example, {{ic|qemu-x86_64-static}} for intel 64-bit CPUs.<br />
<br />
{{Note|At present, Arch does not offer a full-system mode and statically linked variant (neither officially nor via AUR), as this is usually not needed.}}<br />
<br />
== Graphical front-ends for QEMU ==<br />
<br />
Unlike other virtualization programs such as [[VirtualBox]] and [[VMware]], QEMU does not provide a GUI to manage virtual machines (other than the window that appears when running a virtual machine), nor does it provide a way to create persistent virtual machines with saved settings. All parameters to run a virtual machine must be specified on the command line at every launch, unless you have created a custom script to start your virtual machine(s).<br />
<br />
[[Libvirt]] provides a convenient way to manage QEMU virtual machines. See [[Libvirt#Client|list of libvirt clients]] for available front-ends.<br />
<br />
Other GUI front-ends for QEMU:<br />
<br />
* {{App|AQEMU|QEMU GUI written in Qt5.|https://github.com/tobimensch/aqemu|{{AUR|aqemu}}}}<br />
<br />
== Creating new virtualized system ==<br />
<br />
=== Creating a hard disk image ===<br />
<br />
{{Accuracy|If I get the man page right the raw format only allocates the full size if the filesystem does not support "holes" or it is <br />
explicitly told to preallocate. See man qemu-img in section Notes.}} <br />
<br />
{{Tip|See [[Wikibooks:QEMU/Images]] for more information on QEMU images.}}<br />
<br />
To run QEMU you will need a hard disk image, unless you are booting a live system from CD-ROM or the network (and not doing so to install an operating system to a hard disk image). A hard disk image is a file which stores the contents of the emulated hard disk.<br />
<br />
A hard disk image can be ''raw'', so that it is literally byte-by-byte the same as what the guest sees, and will always use the full capacity of the guest hard drive on the host. This method provides the least I/O overhead, but can waste a lot of space, as not-used space on the guest cannot be used on the host.<br />
<br />
Alternatively, the hard disk image can be in a format such as ''qcow2'' which only allocates space to the image file when the guest operating system actually writes to those sectors on its virtual hard disk. The image appears as the full size to the guest operating system, even though it may take up only a very small amount of space on the host system. This image format also supports QEMU snapshotting functionality (see [[#Creating and managing snapshots via the monitor console]] for details). However, using this format instead of ''raw'' will likely affect performance.<br />
<br />
QEMU provides the {{ic|qemu-img}} command to create hard disk images. For example to create a 4 GB image in the ''raw'' format:<br />
<br />
$ qemu-img create -f raw ''image_file'' 4G<br />
<br />
You may use {{ic|-f qcow2}} to create a ''qcow2'' disk instead.<br />
<br />
{{Note|You can also simply create a ''raw'' image by creating a file of the needed size using {{ic|dd}} or {{ic|fallocate}}.}}<br />
<br />
{{Warning|If you store the hard disk images on a [[Btrfs]] file system, you should consider disabling [[Btrfs#Copy-on-Write (CoW)|Copy-on-Write]] for the directory before creating any images.}}<br />
<br />
==== Overlay storage images ====<br />
<br />
You can create a storage image once (the 'backing' image) and have QEMU keep mutations to this image in an overlay image. This allows you to revert to a previous state of this storage image. You could revert by creating a new overlay image at the time you wish to revert, based on the original backing image.<br />
<br />
To create an overlay image, issue a command like:<br />
<br />
$ qemu-img create -o backing_file=''img1.raw'',backing_fmt=''raw'' -f ''qcow2'' ''img1.cow''<br />
<br />
After that you can run your QEMU VM as usual (see [[#Running virtualized system]]):<br />
<br />
$ qemu-system-x86_64 ''img1.cow''<br />
<br />
The backing image will then be left intact and mutations to this storage will be recorded in the overlay image file.<br />
<br />
When the path to the backing image changes, repair is required.<br />
<br />
{{Warning|The backing image's absolute filesystem path is stored in the (binary) overlay image file. Changing the backing image's path requires some effort.}}<br />
<br />
Make sure that the original backing image's path still leads to this image. If necessary, make a symbolic link at the original path to the new path. Then issue a command like:<br />
<br />
$ qemu-img rebase -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
At your discretion, you may alternatively perform an 'unsafe' rebase where the old path to the backing image is not checked:<br />
<br />
$ qemu-img rebase -u -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
==== Resizing an image ====<br />
<br />
{{Warning|Resizing an image containing an NTFS boot file system could make the operating system installed on it unbootable. It is recommended to create a backup first.}}<br />
<br />
The {{ic|qemu-img}} executable has the {{ic|resize}} option, which enables easy resizing of a hard drive image. It works for both ''raw'' and ''qcow2''. For example, to increase image space by 10 GB, run:<br />
<br />
$ qemu-img resize ''disk_image'' +10G<br />
<br />
After enlarging the disk image, you must use file system and partitioning tools inside the virtual machine to actually begin using the new space. When shrinking a disk image, you must '''first reduce the allocated file systems and partition sizes''' using the file system and partitioning tools inside the virtual machine and then shrink the disk image accordingly, otherwise shrinking the disk image will result in data loss! For a Windows guest, open the "create and format hard disk partitions" control panel.<br />
<br />
==== Converting an image ====<br />
<br />
You can convert an image to other formats using {{ic|qemu-img convert}}. This example shows how to convert a ''raw'' image to ''qcow2'':<br />
<br />
$ qemu-img convert -f raw -O qcow2 ''input''.img ''output''.qcow2<br />
<br />
This will not remove the original input file.<br />
<br />
=== Preparing the installation media ===<br />
<br />
To install an operating system into your disk image, you need the installation medium (e.g. optical disk, USB-drive, or ISO image) for the operating system. The installation medium should not be mounted because QEMU accesses the media directly.<br />
<br />
{{Tip|If using an optical disk, it is a good idea to first dump the media to a file because this both improves performance and does not require you to have direct access to the devices (that is, you can run QEMU as a regular user without having to change access permissions on the media's device file). For example, if the CD-ROM device node is named {{ic|/dev/cdrom}}, you can dump it to a file with the command: {{bc|1=$ dd if=/dev/cdrom of=''cd_image.iso'' bs=4k}}}}<br />
<br />
=== Installing the operating system ===<br />
<br />
This is the first time you will need to start the emulator. To install the operating system on the disk image, you must attach both the disk image and the installation media to the virtual machine, and have it boot from the installation media.<br />
<br />
For example on i386 guests, to install from a bootable ISO file as CD-ROM and a raw disk image:<br />
<br />
$ qemu-system-x86_64 -cdrom ''iso_image'' -boot order=d -drive file=''disk_image'',format=raw<br />
<br />
See {{man|1|qemu}} for more information about loading other media types (such as floppy, disk images or physical drives) and [[#Running virtualized system]] for other useful options.<br />
<br />
After the operating system has finished installing, the QEMU image can be booted directly (see [[#Running virtualized system]]).<br />
<br />
{{Note|By default only 128 MB of memory is assigned to the machine. The amount of memory can be adjusted with the {{ic|-m}} switch, for example {{ic|-m 512M}} or {{ic|-m 2G}}.}}<br />
<br />
{{Tip|<br />
* Instead of specifying {{ic|1=-boot order=x}}, some users may feel more comfortable using a boot menu: {{ic|1=-boot menu=on}}, at least during configuration and experimentation.<br />
* When running QEMU in headless mode, it starts a local VNC server on port 5900 per default. You can use [[TigerVNC]] to connect to the guest OS: {{ic|vncviewer :5900}}<br />
* If you need to replace floppies or CDs as part of the installation process, you can use the QEMU machine monitor (press {{ic|Ctrl+Alt+2}} in the virtual machine's window) to remove and attach storage devices to a virtual machine. Type {{ic|info block}} to see the block devices, and use the {{ic|change}} command to swap out a device. Press {{ic|Ctrl+Alt+1}} to go back to the virtual machine.<br />
}}<br />
<br />
== Running virtualized system ==<br />
<br />
{{ic|qemu-system-*}} binaries (for example {{ic|qemu-system-i386}} or {{ic|qemu-system-x86_64}}, depending on guest's architecture) are used to run the virtualized guest. The usage is:<br />
<br />
$ qemu-system-x86_64 ''options'' ''disk_image''<br />
<br />
Options are the same for all {{ic|qemu-system-*}} binaries, see {{man|1|qemu}} for documentation of all options.<br />
<br />
By default, QEMU will show the virtual machine's video output in a window. One thing to keep in mind: when you click inside the QEMU window, the mouse pointer is grabbed. To release it, press {{ic|Ctrl+Alt+g}}.<br />
<br />
{{Warning|QEMU should never be run as root. If you must launch it in a script as root, you should use the {{ic|-runas}} option to make QEMU drop root privileges.}}<br />
<br />
=== Enabling KVM ===<br />
<br />
KVM (''Kernel-based Virtual Machine'') full virtualization must be supported by your Linux kernel and your hardware, and necessary [[kernel modules]] must be loaded. See [[KVM]] for more information.<br />
<br />
To start QEMU in KVM mode, append {{ic|-enable-kvm}} to the additional start options. To check if KVM is enabled for a running VM, enter the [[#QEMU monitor]] and type {{ic|info kvm}}.<br />
<br />
{{Note|<br />
* The argument {{ic|1=accel=kvm}} of the {{ic|-machine}} option is equivalent to the {{ic|-enable-kvm}} or the {{ic|-accel kvm}} option.<br />
* CPU model {{ic|host}} requires KVM<br />
* If you start your VM with a GUI tool and experience very bad performance, you should check for proper KVM support, as QEMU may be falling back to software emulation.<br />
* KVM needs to be enabled in order to start Windows 7 and Windows 8 properly without a ''blue screen''.<br />
}}<br />
<br />
=== Enabling IOMMU (Intel VT-d/AMD-Vi) support ===<br />
<br />
First enable IOMMU, see [[PCI passthrough via OVMF#Setting up IOMMU]].<br />
<br />
Add {{ic|-device intel-iommu}} to create the IOMMU device:<br />
<br />
$ qemu-system-x86_64 '''-enable-kvm -machine q35 -device intel-iommu''' -cpu host ..<br />
<br />
{{Note|<br />
On Intel CPU based systems creating an IOMMU device in a QEMU guest with {{ic|-device intel-iommu}} will disable PCI passthrough with an error like: {{bc|Device at bus pcie.0 addr 09.0 requires iommu notifier which is currently not supported by intel-iommu emulation}} While adding the kernel parameter {{ic|1=intel_iommu=on}} is still needed for remapping IO (e.g. [[PCI passthrough via OVMF#Isolating the GPU|PCI passthrough with vfio-pci]]), {{ic|-device intel-iommu}} should not be set if PCI PCI passthrough is required.<br />
}}<br />
<br />
== Sharing data between host and guest ==<br />
<br />
=== Network ===<br />
<br />
Data can be shared between the host and guest OS using any network protocol that can transfer files, such as [[NFS]], [[SMB]], [[Wikipedia:Network block device|NBD]], HTTP, [[Very Secure FTP Daemon|FTP]], or [[SSH]], provided that you have set up the network appropriately and enabled the appropriate services.<br />
<br />
The default user-mode networking allows the guest to access the host OS at the IP address 10.0.2.2. Any servers that you are running on your host OS, such as a SSH server or SMB server, will be accessible at this IP address. So on the guests, you can mount directories exported on the host via [[SMB]] or [[NFS]], or you can access the host's HTTP server, etc.<br />
It will not be possible for the host OS to access servers running on the guest OS, but this can be done with other network configurations (see [[#Tap networking with QEMU]]).<br />
<br />
=== QEMU's port forwarding ===<br />
<br />
QEMU can forward ports from the host to the guest to enable e.g. connecting from the host to an SSH server running on the guest.<br />
<br />
For example, to bind port 10022 on the host with port 22 (SSH) on the guest, start QEMU with a command like:<br />
<br />
$ qemu-system-x86_64 ''disk_image'' -nic user,hostfwd=tcp::10022-:22<br />
<br />
Make sure the sshd is running on the guest and connect with:<br />
<br />
$ ssh ''guest-user''@localhost -p 10022<br />
<br />
You can use [[SSHFS]] to mount the guest's file system at the host for shared read and write access.<br />
<br />
=== QEMU's built-in SMB server ===<br />
<br />
QEMU's documentation says it has a "built-in" SMB server, but actually it just starts up [[Samba]] on the host with an automatically generated {{ic|smb.conf}} file located in {{ic|/tmp/qemu-smb.''random_string''}} and makes it accessible to the guest at a different IP address (10.0.2.4 by default). This only works for user networking, and is useful when you do not want to start the normal [[Samba]] service on the host, which the guest can also access if you have set up shares on it.<br />
<br />
Only a single directory can be set as shared with the option {{ic|1=smb=}}, but adding more directories (even while the virtual machine is running) could be as easy as creating symbolic links in the shared directory if QEMU configured SMB to follow symbolic links. It does not do so, but the configuration of the running SMB server can be changed as described below.<br />
<br />
''Samba'' must be installed on the host. To enable this feature, start QEMU with a command like:<br />
<br />
$ qemu-system-x86_64 ''disk_image'' -net nic -net user,smb=''shared_dir_path''<br />
<br />
where {{ic|''shared_dir_path''}} is a directory that you want to share between the guest and host.<br />
<br />
Then, in the guest, you will be able to access the shared directory on the host 10.0.2.4 with the share name "qemu". For example, in Windows Explorer you would go to {{ic|\\10.0.2.4\qemu}}.<br />
<br />
{{Note|<br />
* If you are using sharing options multiple times like {{ic|1=-net user,smb=''shared_dir_path1'' -net user,smb=''shared_dir_path2''}} or {{ic|1=-net user,smb=''shared_dir_path1'',smb=''shared_dir_path2''}} then it will share only the last defined one.<br />
* If you cannot access the shared folder and the guest system is Windows, check that the [http://ecross.mvps.org/howto/enable-netbios-over-tcp-ip-with-windows.htm NetBIOS protocol is enabled] and that a firewall does not block [https://technet.microsoft.com/en-us/library/cc940063.aspx ports] used by the NetBIOS protocol.<br />
* If you cannot access the shared folder and the guest system is Windows 10 Enterprise or Education or Windows Server 2016, [https://support.microsoft.com/en-us/help/4046019 enable guest access].<br />
}}<br />
<br />
One way to share multiple directories and to add or remove them while the virtual machine is running, is to share an empty directory and create/remove symbolic links to the directories in the shared directory. For this to work, the configuration of the running SMB server can be changed with the following script, which also allows the execution of files on the guest that are not set executable on the host:<br />
<br />
#!/bin/bash<br />
eval $(ps h -C smbd -o pid,args | grep /tmp/qemu-smb | gawk '{print "pid="$1";conf="$6}')<br />
echo "[global]<br />
allow insecure wide links = yes<br />
[qemu]<br />
follow symlinks = yes<br />
wide links = yes<br />
acl allow execute always = yes" >> $conf<br />
# in case the change is not detected automatically:<br />
smbcontrol --configfile=$conf $pid reload-config<br />
<br />
This can be applied to the running server started by qemu only after the guest has connected to the network drive the first time. An alternative to this method is to add additional shares to the configuration file like so:<br />
<br />
echo "[''myshare'']<br />
path=''another_path''<br />
read only=no<br />
guest ok=yes<br />
force user=''username''" >> $conf<br />
<br />
This share will be available on the guest as {{ic|\\10.0.2.4\''myshare''}}.<br />
<br />
=== Using filesystem passthrough and VirtFS ===<br />
<br />
See the [https://wiki.qemu.org/Documentation/9psetup QEMU documentation].<br />
<br />
=== Mounting a partition of the guest on the host ===<br />
<br />
It can be useful to mount a drive image under the host system, it can be a way to transfer files in and out of the guest. This should be done when the virtual machine is not running.<br />
<br />
The procedure to mount the drive on the host depends on the type of qemu image, ''raw'' or ''qcow2''. We detail thereafter the steps to mount a drive in the two formats in [[#Mounting a partition from a raw image]] and [[#Mounting a partition from a qcow2 image]]. For the full documentation see [[Wikibooks:QEMU/Images#Mounting an image on the host]].<br />
<br />
{{Warning|You must make sure to unmount the partitions before running the virtual machine again. Otherwise, data corruption is very likely to occur.}}<br />
<br />
==== Mounting a partition from a raw image ====<br />
<br />
It is possible to mount partitions that are inside a raw disk image file by setting them up as loopback devices.<br />
<br />
===== With manually specifying byte offset =====<br />
<br />
One way to mount a disk image partition is to mount the disk image at a certain offset using a command like the following:<br />
<br />
# mount -o loop,offset=32256 ''disk_image'' ''mountpoint''<br />
<br />
The {{ic|1=offset=32256}} option is actually passed to the {{ic|losetup}} program to set up a loopback device that starts at byte offset 32256 of the file and continues to the end. This loopback device is then mounted. You may also use the {{ic|sizelimit}} option to specify the exact size of the partition, but this is usually unnecessary.<br />
<br />
Depending on your disk image, the needed partition may not start at offset 32256. Run {{ic|fdisk -l ''disk_image''}} to see the partitions in the image. fdisk gives the start and end offsets in 512-byte sectors, so multiply by 512 to get the correct offset to pass to {{ic|mount}}.<br />
<br />
===== With loop module autodetecting partitions =====<br />
<br />
The Linux loop driver actually supports partitions in loopback devices, but it is disabled by default. To enable it, do the following:<br />
<br />
* Get rid of all your loopback devices (unmount all mounted images, etc.).<br />
* [[Kernel_modules#Manual_module_handling|Unload]] the {{ic|loop}} kernel module, and load it with the {{ic|1=max_part=15}} parameter set. Additionally, the maximum number of loop devices can be controlled with the {{ic|max_loop}} parameter.<br />
<br />
{{Tip|You can put an entry in {{ic|/etc/modprobe.d}} to load the loop module with {{ic|1=max_part=15}} every time, or you can put {{ic|1=loop.max_part=15}} on the kernel command-line, depending on whether you have the {{ic|loop.ko}} module built into your kernel or not.}}<br />
<br />
Set up your image as a loopback device:<br />
<br />
# losetup -f -P ''disk_image''<br />
<br />
Then, if the device created was {{ic|/dev/loop0}}, additional devices {{ic|/dev/loop0pX}} will have been automatically created, where X is the number of the partition. These partition loopback devices can be mounted directly. For example:<br />
<br />
# mount /dev/loop0p1 ''mountpoint''<br />
<br />
To mount the disk image with ''udisksctl'', see [[Udisks#Mount loop devices]].<br />
<br />
===== With kpartx =====<br />
<br />
'''kpartx''' from the {{Pkg|multipath-tools}} package can read a partition table on a device and create a new device for each partition. For example:<br />
<br />
# kpartx -a ''disk_image''<br />
<br />
This will setup the loopback device and create the necessary partition(s) device(s) in {{ic|/dev/mapper/}}.<br />
<br />
==== Mounting a partition from a qcow2 image ====<br />
<br />
We will use {{ic|qemu-nbd}}, which lets use the NBD (''network block device'') protocol to share the disk image.<br />
<br />
First, we need the ''nbd'' module loaded:<br />
<br />
# modprobe nbd max_part=16<br />
<br />
Then, we can share the disk and create the device entries:<br />
<br />
# qemu-nbd -c /dev/nbd0 ''/path/to/image.qcow2''<br />
<br />
Discover the partitions:<br />
<br />
# partprobe /dev/nbd0<br />
<br />
''fdisk'' can be used to get information regarding the different partitions in {{{ic|''nbd0''}}:<br />
<br />
{{hc|# fdisk -l /dev/nbd0|2=<br />
Disk /dev/nbd0: 25.2 GiB, 27074281472 bytes, 52879456 sectors<br />
Units: sectors of 1 * 512 = 512 bytes<br />
Sector size (logical/physical): 512 bytes / 512 bytes<br />
I/O size (minimum/optimal): 512 bytes / 512 bytes<br />
Disklabel type: dos<br />
Disk identifier: 0xa6a4d542<br />
<br />
Device Boot Start End Sectors Size Id Type<br />
/dev/nbd0p1 * 2048 1026047 1024000 500M 7 HPFS/NTFS/exFAT<br />
/dev/nbd0p2 1026048 52877311 51851264 24.7G 7 HPFS/NTFS/exFAT}}<br />
<br />
Then mount any partition of the drive image, for example the partition 2:<br />
<br />
# mount /dev/nbd0'''p2''' ''mountpoint''<br />
<br />
After the usage, it is important to unmount the image and reverse previous steps, i.e. unmount the partition and disconnect the nbd device:<br />
<br />
# umount ''mountpoint''<br />
# qemu-nbd -d /dev/nbd0<br />
<br />
=== Using any real partition as the single primary partition of a hard disk image ===<br />
<br />
Sometimes, you may wish to use one of your system partitions from within QEMU. Using a raw partition for a virtual machine will improve performance, as the read and write operations do not go through the file system layer on the physical host. Such a partition also provides a way to share data between the host and guest.<br />
<br />
In Arch Linux, device files for raw partitions are, by default, owned by ''root'' and the ''disk'' group. If you would like to have a non-root user be able to read and write to a raw partition, you must either change the owner of the partition's device file to that user, add that user to the ''disk'' group, or use [[ACL]] for more fine-grained access control.<br />
<br />
{{Warning|<br />
* Although it is possible, it is not recommended to allow virtual machines to alter critical data on the host system, such as the root partition.<br />
* You must not mount a file system on a partition read-write on both the host and the guest at the same time. Otherwise, data corruption will result.<br />
}}<br />
<br />
After doing so, you can attach the partition to a QEMU virtual machine as a virtual disk.<br />
<br />
However, things are a little more complicated if you want to have the ''entire'' virtual machine contained in a partition. In that case, there would be no disk image file to actually boot the virtual machine since you cannot install a bootloader to a partition that is itself formatted as a file system and not as a partitioned device with an MBR. Such a virtual machine can be booted either by specifying the [[kernel]] and [[initrd]] manually, or by simulating a disk with an MBR by using the [https://www.kernel.org/doc/html/latest/admin-guide/device-mapper/index.html Device-mapper], linear [[RAID]], or a [https://www.kernel.org/doc/html/latest/admin-guide/blockdev/nbd.html Linux Network Block Device].<br />
<br />
==== By specifying kernel and initrd manually ====<br />
<br />
QEMU supports loading [[Kernels|Linux kernels]] and [[initramfs|init ramdisks]] directly, thereby circumventing bootloaders such as [[GRUB]]. It then can be launched with the physical partition containing the root file system as the virtual disk, which will not appear to be partitioned. This is done by issuing a command similar to the following:<br />
<br />
{{Note|In this example, it is the '''host's''' images that are being used, not the guest's. If you wish to use the guest's images, either mount {{ic|/dev/sda3}} read-only (to protect the file system from the host) and specify the {{ic|/full/path/to/images}} or use some kexec hackery in the guest to reload the guest's kernel (extends boot time). }}<br />
<br />
$ qemu-system-x86_64 -kernel /boot/vmlinuz-linux -initrd /boot/initramfs-linux.img -append root=/dev/sda /dev/sda3<br />
<br />
In the above example, the physical partition being used for the guest's root file system is {{ic|/dev/sda3}} on the host, but it shows up as {{ic|/dev/sda}} on the guest.<br />
<br />
You may, of course, specify any kernel and initrd that you want, and not just the ones that come with Arch Linux.<br />
<br />
When there are multiple [[kernel parameters]] to be passed to the {{ic|-append}} option, they need to be quoted using single or double quotes. For example:<br />
<br />
... -append 'root=/dev/sda1 console=ttyS0'<br />
<br />
==== Simulate a virtual disk with MBR ====<br />
<br />
A more complicated way to have a virtual machine use a physical partition, while keeping that partition formatted as a file system and not just having the guest partition the partition as if it were a disk, is to simulate an MBR for it so that it can boot using a bootloader such as GRUB.<br />
<br />
For the following, suppose you have a plain, unmounted {{ic|/dev/hda''N''}} partition with some file system on it you wish to make part of a QEMU disk image. The trick is to dynamically prepend a master boot record (MBR) to the real partition you wish to embed in a QEMU raw disk image. More generally, the partition can be any part of a larger simulated disk, in particular a block device that simulates the original physical disk but only exposes {{ic|/dev/hda''N''}} to the virtual machine.<br />
<br />
A virtual disk of this type can be represented by a VMDK file that contains references to (a copy of) the MBR and the partition, but QEMU does not support this VMDK format. For instance, a virtual disk [https://www.virtualbox.org/manual/ch09.html#rawdisk created by]<br />
<br />
$ VBoxManage internalcommands createrawvmdk -filename ''/path/to/file.vmdk'' -rawdisk /dev/hda<br />
<br />
will be rejected by QEMU with the error message<br />
<br />
Unsupported image type 'partitionedDevice'<br />
<br />
Note that {{ic|VBoxManage}} creates two files, {{ic|''file.vmdk''}} and {{ic|''file-pt.vmdk''}}, the latter being a copy of the MBR, to which the text file {{ic|file.vmdk}} points. Read operations outside the target partition or the MBR would give zeros, while written data would be discarded.<br />
<br />
===== Device Mapper =====<br />
<br />
A method that is similar to the use of a VMDK descriptor file uses the device mapper to prepend a loop device attached to the MBR file to the target partition. In case we do not need our virtual disk to have the same size as the original, we first create a file to hold the MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=2048<br />
<br />
Here, a 1 MB (2048 * 512 bytes) file is created in accordance with partition alignment policies used by modern disk partitioning tools. For compatibility with older partitioning software, 63 sectors instead of 2048 might be required. The MBR only needs a single 512 bytes block, the additional free space can be used for a BIOS boot partition and, in the case of a hybrid partitioning scheme, for a GUID Partition Table. Then, we attach a loop device to the MBR file:<br />
<br />
# losetup --show -f ''/path/to/mbr''<br />
/dev/loop0<br />
<br />
In this example, the resulting device is {{ic|/dev/loop0}}. The device mapper is now used to join the MBR and the partition:<br />
<br />
# echo "0 2048 linear /dev/loop0 0<br />
2048 `blockdev --getsz /dev/hda''N''` linear /dev/hda''N'' 0" | dmsetup create qemu<br />
<br />
The resulting {{ic|/dev/mapper/qemu}} is what we will use as a QEMU raw disk image. Additional steps are required to create a partition table (see the section that describes the use of a linear RAID for an example) and boot loader code on the virtual disk (which will be stored in {{ic|''/path/to/mbr''}}).<br />
<br />
The following setup is an example where the position of {{ic|/dev/hda''N''}} on the virtual disk is to be the same as on the physical disk and the rest of the disk is hidden, except for the MBR, which is provided as a copy:<br />
<br />
# dd if=/dev/hda count=1 of=''/path/to/mbr''<br />
# loop=`losetup --show -f ''/path/to/mbr''`<br />
# start=`blockdev --report /dev/hda''N'' | tail -1 | awk '{print $5}'`<br />
# size=`blockdev --getsz /dev/hda''N''`<br />
# disksize=`blockdev --getsz /dev/hda`<br />
# echo "0 1 linear $loop 0<br />
1 $((start-1)) zero<br />
$start $size linear /dev/hda''N'' 0<br />
$((start+size)) $((disksize-start-size)) zero" | dmsetup create qemu<br />
<br />
The table provided as standard input to {{ic|dmsetup}} has a similar format as the table in a VDMK descriptor file produced by {{ic|VBoxManage}} and can alternatively be loaded from a file with {{ic|dmsetup create qemu --table ''table_file''}}. To the virtual machine, only {{ic|/dev/hda''N''}} is accessible, while the rest of the hard disk reads as zeros and discards written data, except for the first sector. We can print the table for {{ic|/dev/mapper/qemu}} with {{ic|dmsetup table qemu}} (use {{ic|udevadm info -rq name /sys/dev/block/''major'':''minor''}} to translate {{ic|''major'':''minor''}} to the corresponding {{ic|/dev/''blockdevice''}} name). Use {{ic|dmsetup remove qemu}} and {{ic|losetup -d $loop}} to delete the created devices.<br />
<br />
A situation where this example would be useful is an existing Windows XP installation in a multi-boot configuration and maybe a hybrid partitioning scheme (on the physical hardware, Windows XP could be the only operating system that uses the MBR partition table, while more modern operating systems installed on the same computer could use the GUID Partition Table). Windows XP supports hardware profiles, so that that the same installation can be used with different hardware configurations alternatingly (in this case bare metal vs. virtual) with Windows needing to install drivers for newly detected hardware only once for every profile. Note that in this example the boot loader code in the copied MBR needs to be updated to directly load Windows XP from {{ic|/dev/hda''N''}} instead of trying to start the multi-boot capable boot loader (like GRUB) present in the original system. Alternatively, a copy of the boot partition containing the boot loader installation can be included in the virtual disk the same way as the MBR.<br />
<br />
===== Linear RAID =====<br />
<br />
You can also do this using software [[RAID]] in linear mode (you need the {{ic|linear.ko}} kernel driver) and a loopback device: <br />
<br />
First, you create some small file to hold the MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=32<br />
<br />
Here, a 16 KB (32 * 512 bytes) file is created. It is important not to make it too small (even if the MBR only needs a single 512 bytes block), since the smaller it will be, the smaller the chunk size of the software RAID device will have to be, which could have an impact on performance. Then, you setup a loopback device to the MBR file:<br />
<br />
# losetup -f ''/path/to/mbr''<br />
<br />
Let us assume the resulting device is {{ic|/dev/loop0}}, because we would not already have been using other loopbacks. Next step is to create the "merged" MBR + {{ic|/dev/hda''N''}} disk image using software RAID:<br />
<br />
# modprobe linear<br />
# mdadm --build --verbose /dev/md0 --chunk=16 --level=linear --raid-devices=2 /dev/loop0 /dev/hda''N''<br />
<br />
The resulting {{ic|/dev/md0}} is what you will use as a QEMU raw disk image (do not forget to set the permissions so that the emulator can access it). The last (and somewhat tricky) step is to set the disk configuration (disk geometry and partitions table) so that the primary partition start point in the MBR matches the one of {{ic|/dev/hda''N''}} inside {{ic|/dev/md0}} (an offset of exactly 16 * 512 = 16384 bytes in this example). Do this using {{ic|fdisk}} on the host machine, not in the emulator: the default raw disc detection routine from QEMU often results in non-kilobyte-roundable offsets (such as 31.5 KB, as in the previous section) that cannot be managed by the software RAID code. Hence, from the the host:<br />
<br />
# fdisk /dev/md0<br />
<br />
Press {{ic|X}} to enter the expert menu. Set number of 's'ectors per track so that the size of one cylinder matches the size of your MBR file. For two heads and a sector size of 512, the number of sectors per track should be 16, so we get cylinders of size 2x16x512=16k.<br />
<br />
Now, press {{ic|R}} to return to the main menu.<br />
<br />
Press {{ic|P}} and check that the cylinder size is now 16k.<br />
<br />
Now, create a single primary partition corresponding to {{ic|/dev/hda''N''}}. It should start at cylinder 2 and end at the end of the disk (note that the number of cylinders now differs from what it was when you entered fdisk.<br />
<br />
Finally, 'w'rite the result to the file: you are done. You now have a partition you can mount directly from your host, as well as part of a QEMU disk image:<br />
<br />
$ qemu-system-x86_64 -hdc /dev/md0 ''[...]''<br />
<br />
You can, of course, safely set any bootloader on this disk image using QEMU, provided the original {{ic|/dev/hda''N''}} partition contains the necessary tools.<br />
<br />
===== Network Block Device =====<br />
<br />
Instead of the methods decribed above, you may use {{ic|nbd-server}} (from the {{pkg|nbd}} package) to create an MBR wrapper for QEMU.<br />
<br />
Assuming you have already set up your MBR wrapper file like above, rename it to {{ic|wrapper.img.0}}. Then create a symbolic link named {{ic|wrapper.img.1}} in the same directory, pointing to your partition. Then put the following script in the same directory:<br />
<br />
#!/bin/sh<br />
dir="$(realpath "$(dirname "$0")")"<br />
cat >wrapper.conf <<EOF<br />
[generic]<br />
allowlist = true<br />
listenaddr = 127.713705<br />
port = 10809<br />
<br />
[wrap]<br />
exportname = $dir/wrapper.img<br />
multifile = true<br />
EOF<br />
<br />
nbd-server \<br />
-C wrapper.conf \<br />
-p wrapper.pid \<br />
"$@"<br />
<br />
The {{ic|.0}} and {{ic|.1}} suffixes are essential; the rest can be changed. After running the above script (which you may need to do as root to make sure nbd-server is able to access the partition), you can launch QEMU with:<br />
<br />
qemu-system-x86_64 -drive file=nbd:127.713705:10809:exportname=wrap ''[...]''<br />
<br />
== Networking ==<br />
<br />
{{Style|Network topologies (sections [[#Host-only networking]], [[#Internal networking]] and info spread out across other sections) should not be described alongside the various virtual interfaces implementations, such as [[#User-mode networking]], [[#Tap networking with QEMU]], [[#Networking with VDE2]].}}<br />
<br />
The performance of virtual networking should be better with tap devices and bridges than with user-mode networking or vde because tap devices and bridges are implemented in-kernel.<br />
<br />
In addition, networking performance can be improved by assigning virtual machines a [http://wiki.libvirt.org/page/Virtio virtio] network device rather than the default emulation of an e1000 NIC. See [[#Installing virtio drivers]] for more information.<br />
<br />
=== Link-level address caveat ===<br />
<br />
By giving the {{ic|-net nic}} argument to QEMU, it will, by default, assign a virtual machine a network interface with the link-level address {{ic|52:54:00:12:34:56}}. However, when using bridged networking with multiple virtual machines, it is essential that each virtual machine has a unique link-level (MAC) address on the virtual machine side of the tap device. Otherwise, the bridge will not work correctly, because it will receive packets from multiple sources that have the same link-level address. This problem occurs even if the tap devices themselves have unique link-level addresses because the source link-level address is not rewritten as packets pass through the tap device.<br />
<br />
Make sure that each virtual machine has a unique link-level address, but it should always start with {{ic|52:54:}}. Use the following option, replace ''X'' with arbitrary hexadecimal digit:<br />
<br />
$ qemu-system-x86_64 -net nic,macaddr=52:54:''XX:XX:XX:XX'' -net vde ''disk_image''<br />
<br />
Generating unique link-level addresses can be done in several ways:<br />
<br />
* Manually specify unique link-level address for each NIC. The benefit is that the DHCP server will assign the same IP address each time the virtual machine is run, but it is unusable for large number of virtual machines.<br />
* Generate random link-level address each time the virtual machine is run. Practically zero probability of collisions, but the downside is that the DHCP server will assign a different IP address each time. You can use the following command in a script to generate random link-level address in a {{ic|macaddr}} variable:<br />
<br />
{{bc|1=<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
qemu-system-x86_64 -net nic,macaddr="$macaddr" -net vde ''disk_image''<br />
}}<br />
<br />
* Use the following script {{ic|qemu-mac-hasher.py}} to generate the link-level address from the virtual machine name using a hashing function. Given that the names of virtual machines are unique, this method combines the benefits of the aforementioned methods: it generates the same link-level address each time the script is run, yet it preserves the practically zero probability of collisions.<br />
<br />
{{hc|qemu-mac-hasher.py|<nowiki><br />
#!/usr/bin/env python<br />
<br />
import sys<br />
import zlib<br />
<br />
if len(sys.argv) != 2:<br />
print("usage: %s <VM Name>" % sys.argv[0])<br />
sys.exit(1)<br />
<br />
crc = zlib.crc32(sys.argv[1].encode("utf-8")) & 0xffffffff<br />
crc = str(hex(crc))[2:]<br />
print("52:54:%s%s:%s%s:%s%s:%s%s" % tuple(crc))<br />
</nowiki>}}<br />
<br />
In a script, you can use for example:<br />
<br />
vm_name="''VM Name''"<br />
qemu-system-x86_64 -name "$vm_name" -net nic,macaddr=$(qemu-mac-hasher.py "$vm_name") -net vde ''disk_image''<br />
<br />
=== User-mode networking ===<br />
<br />
By default, without any {{ic|-netdev}} arguments, QEMU will use user-mode networking with a built-in DHCP server. Your virtual machines will be assigned an IP address when they run their DHCP client, and they will be able to access the physical host's network through IP masquerading done by QEMU.<br />
<br />
{{warning|This only works with the TCP and UDP protocols, so ICMP, including {{ic|ping}}, will not work. Do not use {{ic|ping}} to test network connectivity. To make ping work in the guest see [[Sysctl#Allow unprivileged users to create IPPROTO_ICMP sockets]].}}<br />
<br />
This default configuration allows your virtual machines to easily access the Internet, provided that the host is connected to it, but the virtual machines will not be directly visible on the external network, nor will virtual machines be able to talk to each other if you start up more than one concurrently.<br />
<br />
QEMU's user-mode networking can offer more capabilities such as built-in TFTP or SMB servers, redirecting host ports to the guest (for example to allow SSH connections to the guest) or attaching guests to VLANs so that they can talk to each other. See the QEMU documentation on the {{ic|-net user}} flag for more details.<br />
<br />
However, user-mode networking has limitations in both utility and performance. More advanced network configurations require the use of tap devices or other methods.<br />
<br />
{{Note|If the host system uses [[systemd-networkd]], make sure to symlink the {{ic|/etc/resolv.conf}} file as described in [[systemd-networkd#Required services and setup]], otherwise the DNS lookup in the guest system will not work.}}<br />
<br />
=== Tap networking with QEMU ===<br />
<br />
[[wikipedia:TUN/TAP|Tap devices]] are a Linux kernel feature that allows you to create virtual network interfaces that appear as real network interfaces. Packets sent to a tap interface are delivered to a userspace program, such as QEMU, that has bound itself to the interface.<br />
<br />
QEMU can use tap networking for a virtual machine so that packets sent to the tap interface will be sent to the virtual machine and appear as coming from a network interface (usually an Ethernet interface) in the virtual machine. Conversely, everything that the virtual machine sends through its network interface will appear on the tap interface.<br />
<br />
Tap devices are supported by the Linux bridge drivers, so it is possible to bridge together tap devices with each other and possibly with other host interfaces such as {{ic|eth0}}. This is desirable if you want your virtual machines to be able to talk to each other, or if you want other machines on your LAN to be able to talk to the virtual machines.<br />
<br />
{{Warning|If you bridge together tap device and some host interface, such as {{ic|eth0}}, your virtual machines will appear directly on the external network, which will expose them to possible attack. Depending on what resources your virtual machines have access to, you may need to take all the [[Firewalls|precautions]] you normally would take in securing a computer to secure your virtual machines. If the risk is too great, virtual machines have little resources or you set up multiple virtual machines, a better solution might be to use [[#Host-only networking|host-only networking]] and set up NAT. In this case you only need one firewall on the host instead of multiple firewalls for each guest.}}<br />
<br />
As indicated in the user-mode networking section, tap devices offer higher networking performance than user-mode. If the guest OS supports virtio network driver, then the networking performance will be increased considerably as well. Supposing the use of the tap0 device, that the virtio driver is used on the guest, and that no scripts are used to help start/stop networking, next is part of the qemu command one should see:<br />
<br />
-device virtio-net,netdev=network0 -netdev tap,id=network0,ifname=tap0,script=no,downscript=no<br />
<br />
But if already using a tap device with virtio networking driver, one can even boost the networking performance by enabling vhost, like:<br />
<br />
-device virtio-net,netdev=network0 -netdev tap,id=network0,ifname=tap0,script=no,downscript=no,vhost=on<br />
<br />
See [https://web.archive.org/web/20160222161955/http://www.linux-kvm.com:80/content/how-maximize-virtio-net-performance-vhost-net] for more information.<br />
<br />
==== Host-only networking ====<br />
<br />
If the bridge is given an IP address and traffic destined for it is allowed, but no real interface (e.g. {{ic|eth0}}) is connected to the bridge, then the virtual machines will be able to talk to each other and the host system. However, they will not be able to talk to anything on the external network, provided that you do not set up IP masquerading on the physical host. This configuration is called ''host-only networking'' by other virtualization software such as [[VirtualBox]].<br />
<br />
{{Tip|<br />
* If you want to set up IP masquerading, e.g. NAT for virtual machines, see the [[Internet sharing#Enable NAT]] page.<br />
* See [[Network bridge]] for information on creating bridge.<br />
* You may want to have a DHCP server running on the bridge interface to service the virtual network. For example, to use the {{ic|172.20.0.1/16}} subnet with [[dnsmasq]] as the DHCP server:<br />
<br />
{{bc|1=<br />
# ip addr add 172.20.0.1/16 dev br0<br />
# ip link set br0 up<br />
# dnsmasq --interface=br0 --bind-interfaces --dhcp-range=172.20.0.2,172.20.255.254<br />
}}<br />
}}<br />
<br />
==== Internal networking ====<br />
<br />
If you do not give the bridge an IP address and add an [[iptables]] rule to drop all traffic to the bridge in the INPUT chain, then the virtual machines will be able to talk to each other, but not to the physical host or to the outside network. This configuration is called ''internal networking'' by other virtualization software such as [[VirtualBox]]. You will need to either assign static IP addresses to the virtual machines or run a DHCP server on one of them.<br />
<br />
By default iptables would drop packets in the bridge network. You may need to use such iptables rule to allow packets in a bridged network:<br />
<br />
# iptables -I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Bridged networking using qemu-bridge-helper ====<br />
<br />
{{Note|This method is available since QEMU 1.1, see http://wiki.qemu.org/Features/HelperNetworking.}}<br />
<br />
This method does not require a start-up script and readily accommodates multiple taps and multiple bridges. It uses {{ic|/usr/lib/qemu/qemu-bridge-helper}} binary, which allows creating tap devices on an existing bridge.<br />
<br />
{{Tip|See [[Network bridge]] for information on creating bridge.}}<br />
<br />
First, create a configuration file containing the names of all bridges to be used by QEMU:<br />
<br />
{{hc|/etc/qemu/bridge.conf|<br />
allow ''bridge0''<br />
allow ''bridge1''<br />
...}}<br />
<br />
Now start the VM. The most basic usage would be:<br />
<br />
$ qemu-system-x86_64 -net nic -net bridge,br=''bridge0'' ''[...]''<br />
<br />
With multiple taps, the most basic usage requires specifying the VLAN for all additional NICs:<br />
<br />
$ qemu-system-x86_64 -net nic -net bridge,br=''bridge0'' -net nic,vlan=1 -net bridge,vlan=1,br=''bridge1'' ''[...]''<br />
<br />
==== Creating bridge manually ====<br />
<br />
{{Style|This section needs serious cleanup and may contain out-of-date information.}}<br />
<br />
{{Tip|Since QEMU 1.1, the [http://wiki.qemu.org/Features/HelperNetworking network bridge helper] can set tun/tap up for you without the need for additional scripting. See [[#Bridged networking using qemu-bridge-helper]].}}<br />
<br />
The following describes how to bridge a virtual machine to a host interface such as {{ic|eth0}}, which is probably the most common configuration. This configuration makes it appear that the virtual machine is located directly on the external network, on the same Ethernet segment as the physical host machine.<br />
<br />
We will replace the normal Ethernet adapter with a bridge adapter and bind the normal Ethernet adapter to it.<br />
<br />
* Install {{Pkg|bridge-utils}}, which provides {{ic|brctl}} to manipulate bridges.<br />
<br />
* Enable IPv4 forwarding:<br />
# sysctl -w net.ipv4.ip_forward=1<br />
<br />
To make the change permanent, change {{ic|1=net.ipv4.ip_forward = 0}} to {{ic|1=net.ipv4.ip_forward = 1}} in {{ic|/etc/sysctl.d/99-sysctl.conf}}.<br />
<br />
* Load the {{ic|tun}} module and configure it to be loaded on boot. See [[Kernel modules]] for details.<br />
<br />
* Now create the bridge. See [[Bridge with netctl]] for details. Remember to name your bridge as {{ic|br0}}, or change the scripts below to your bridge's name.<br />
<br />
* Create the script that QEMU uses to bring up the tap adapter with {{ic|root:kvm}} 750 permissions:<br />
<br />
{{hc|/etc/qemu-ifup|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifup"<br />
echo "Bringing up $1 for bridged mode..."<br />
sudo /usr/bin/ip link set $1 up promisc on<br />
echo "Adding $1 to br0..."<br />
sudo /usr/bin/brctl addif br0 $1<br />
sleep 2<br />
</nowiki>}}<br />
<br />
* Create the script that QEMU uses to bring down the tap adapter in {{ic|/etc/qemu-ifdown}} with {{ic|root:kvm}} 750 permissions:<br />
{{hc|/etc/qemu-ifdown|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifdown"<br />
sudo /usr/bin/ip link set $1 down<br />
sudo /usr/bin/brctl delif br0 $1<br />
sudo /usr/bin/ip link delete dev $1<br />
</nowiki>}}<br />
<br />
* Use {{ic|visudo}} to add the following to your {{ic|sudoers}} file:<br />
<br />
{{bc|<nowiki><br />
Cmnd_Alias QEMU=/usr/bin/ip,/usr/bin/modprobe,/usr/bin/brctl<br />
%kvm ALL=NOPASSWD: QEMU<br />
</nowiki>}}<br />
<br />
* You launch QEMU using the following {{ic|run-qemu}} script:<br />
<br />
{{hc|run-qemu|<nowiki><br />
#!/bin/bash<br />
USERID=$(whoami)<br />
<br />
# Get name of newly created TAP device; see https://bbs.archlinux.org/viewtopic.php?pid=1285079#p1285079<br />
precreationg=$(/usr/bin/ip tuntap list | /usr/bin/cut -d: -f1 | /usr/bin/sort)<br />
sudo /usr/bin/ip tuntap add user $USERID mode tap<br />
postcreation=$(/usr/bin/ip tuntap list | /usr/bin/cut -d: -f1 | /usr/bin/sort)<br />
IFACE=$(comm -13 <(echo "$precreationg") <(echo "$postcreation"))<br />
<br />
# This line creates a random MAC address. The downside is the DHCP server will assign a different IP address each time<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
# Instead, uncomment and edit this line to set a static MAC address. The benefit is that the DHCP server will assign the same IP address.<br />
# macaddr='52:54:be:36:42:a9'<br />
<br />
qemu-system-x86_64 -net nic,macaddr=$macaddr -net tap,ifname="$IFACE" $*<br />
<br />
sudo ip link set dev $IFACE down &> /dev/null<br />
sudo ip tuntap del $IFACE mode tap &> /dev/null<br />
</nowiki>}}<br />
<br />
Then to launch a VM, do something like this<br />
<br />
$ run-qemu -hda ''myvm.img'' -m 512<br />
<br />
* It is recommended for performance and security reasons to disable the [http://ebtables.netfilter.org/documentation/bridge-nf.html firewall on the bridge]:<br />
<br />
{{hc|/etc/sysctl.d/10-disable-firewall-on-bridge.conf|<nowiki><br />
net.bridge.bridge-nf-call-ip6tables = 0<br />
net.bridge.bridge-nf-call-iptables = 0<br />
net.bridge.bridge-nf-call-arptables = 0<br />
</nowiki>}}<br />
<br />
Run {{ic|sysctl -p /etc/sysctl.d/10-disable-firewall-on-bridge.conf}} to apply the changes immediately.<br />
<br />
See the [http://wiki.libvirt.org/page/Networking#Creating_network_initscripts libvirt wiki] and [https://bugzilla.redhat.com/show_bug.cgi?id=512206 Fedora bug 512206]. If you get errors by sysctl during boot about non-existing files, make the {{ic|bridge}} module load at boot. See [[Kernel modules#Automatic module loading with systemd]].<br />
<br />
Alternatively, you can configure [[iptables]] to allow all traffic to be forwarded across the bridge by adding a rule like this:<br />
<br />
-I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Network sharing between physical device and a Tap device through iptables ====<br />
<br />
{{Merge|Internet_sharing|Duplication, not specific to QEMU.}}<br />
<br />
Bridged networking works fine between a wired interface (Eg. eth0), and it is easy to setup. However if the host gets connected to the network through a wireless device, then bridging is not possible.<br />
<br />
See [[Network bridge#Wireless interface on a bridge]] as a reference.<br />
<br />
One way to overcome that is to setup a tap device with a static IP, making linux automatically handle the routing for it, and then forward traffic between the tap interface and the device connected to the network through iptables rules.<br />
<br />
See [[Internet sharing]] as a reference.<br />
<br />
There you can find what is needed to share the network between devices, included tap and tun ones. The following just hints further on some of the host configurations required. As indicated in the reference above, the client needs to be configured for a static IP, using the IP assigned to the tap interface as the gateway. The caveat is that the DNS servers on the client might need to be manually edited if they change when changing from one host device connected to the network to another.<br />
<br />
To allow IP forwarding on every boot, one need to add the following lines to sysctl configuration file inside {{ic|/etc/sysctl.d}}:<br />
<br />
net.ipv4.ip_forward = 1<br />
net.ipv6.conf.default.forwarding = 1<br />
net.ipv6.conf.all.forwarding = 1<br />
<br />
The iptables rules can look like:<br />
<br />
# Forwarding from/to outside<br />
iptables -A FORWARD -i ${INT} -o ${EXT_0} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_1} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_2} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_0} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_1} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_2} -o ${INT} -j ACCEPT<br />
# NAT/Masquerade (network address translation)<br />
iptables -t nat -A POSTROUTING -o ${EXT_0} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_1} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_2} -j MASQUERADE<br />
<br />
The prior supposes there are 3 devices connected to the network sharing traffic with one internal device, where for example:<br />
<br />
INT=tap0<br />
EXT_0=eth0<br />
EXT_1=wlan0<br />
EXT_2=tun0<br />
<br />
The prior shows a forwarding that would allow sharing wired and wireless connections with the tap device.<br />
<br />
The forwarding rules shown are stateless, and for pure forwarding. One could think of restricting specific traffic, putting a firewall in place to protect the guest and others. However those would decrease the networking performance, while a simple bridge does not include any of that.<br />
<br />
Bonus: Whether the connection is wired or wireless, if one gets connected through VPN to a remote site with a tun device, supposing the tun device opened for that connection is tun0, and the prior iptables rules are applied, then the remote connection gets also shared with the guest. This avoids the need for the guest to also open a VPN connection. Again, as the guest networking needs to be static, then if connecting the host remotely this way, one most probably will need to edit the DNS servers on the guest.<br />
<br />
=== Networking with VDE2 ===<br />
<br />
{{Style|This section needs serious cleanup and may contain out-of-date information.}}<br />
<br />
==== What is VDE? ====<br />
<br />
VDE stands for Virtual Distributed Ethernet. It started as an enhancement of [[User-mode Linux|uml]]_switch. It is a toolbox to manage virtual networks.<br />
<br />
The idea is to create virtual switches, which are basically sockets, and to "plug" both physical and virtual machines in them. The configuration we show here is quite simple; However, VDE is much more powerful than this, it can plug virtual switches together, run them on different hosts and monitor the traffic in the switches. You are invited to read [https://wiki.virtualsquare.org/ the documentation of the project].<br />
<br />
The advantage of this method is you do not have to add sudo privileges to your users. Regular users should not be allowed to run modprobe.<br />
<br />
==== Basics ====<br />
<br />
VDE support can be [[pacman|installed]] via the {{Pkg|vde2}} package.<br />
<br />
In our config, we use tun/tap to create a virtual interface on my host. Load the {{ic|tun}} module (see [[Kernel modules]] for details):<br />
<br />
# modprobe tun<br />
<br />
Now create the virtual switch:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
<br />
This line creates the switch, creates {{ic|tap0}}, "plugs" it, and allows the users of the group {{ic|users}} to use it.<br />
<br />
The interface is plugged in but not configured yet. To configure it, run this command:<br />
<br />
# ip addr add 192.168.100.254/24 dev tap0<br />
<br />
Now, you just have to run KVM with these {{ic|-net}} options as a normal user:<br />
<br />
$ qemu-system-x86_64 -net nic -net vde -hda ''[...]''<br />
<br />
Configure networking for your guest as you would do in a physical network.<br />
<br />
{{Tip|You might want to set up NAT on tap device to access the internet from the virtual machine. See [[Internet sharing#Enable NAT]] for more information.}}<br />
<br />
==== Startup scripts ====<br />
<br />
Example of main script starting VDE:<br />
<br />
{{hc|/etc/systemd/scripts/qemu-network-env|<nowiki><br />
#!/bin/sh<br />
# QEMU/VDE network environment preparation script<br />
<br />
# The IP configuration for the tap device that will be used for<br />
# the virtual machine network:<br />
<br />
TAP_DEV=tap0<br />
TAP_IP=192.168.100.254<br />
TAP_MASK=24<br />
TAP_NETWORK=192.168.100.0<br />
<br />
# Host interface<br />
NIC=eth0<br />
<br />
case "$1" in<br />
start)<br />
echo -n "Starting VDE network for QEMU: "<br />
<br />
# If you want tun kernel module to be loaded by script uncomment here<br />
#modprobe tun 2>/dev/null<br />
## Wait for the module to be loaded<br />
#while ! lsmod | grep -q "^tun"; do echo "Waiting for tun device"; sleep 1; done<br />
<br />
# Start tap switch<br />
vde_switch -tap "$TAP_DEV" -daemon -mod 660 -group users<br />
<br />
# Bring tap interface up<br />
ip address add "$TAP_IP"/"$TAP_MASK" dev "$TAP_DEV"<br />
ip link set "$TAP_DEV" up<br />
<br />
# Start IP Forwarding<br />
echo "1" > /proc/sys/net/ipv4/ip_forward<br />
iptables -t nat -A POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
;;<br />
stop)<br />
echo -n "Stopping VDE network for QEMU: "<br />
# Delete the NAT rules<br />
iptables -t nat -D POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
<br />
# Bring tap interface down<br />
ip link set "$TAP_DEV" down<br />
<br />
# Kill VDE switch<br />
pgrep vde_switch | xargs kill -TERM<br />
;;<br />
restart|reload)<br />
$0 stop<br />
sleep 1<br />
$0 start<br />
;;<br />
*)<br />
echo "Usage: $0 {start|stop|restart|reload}"<br />
exit 1<br />
esac<br />
exit 0<br />
</nowiki>}}<br />
<br />
Example of systemd service using the above script:<br />
<br />
{{hc|/etc/systemd/system/qemu-network-env.service|<nowiki><br />
[Unit]<br />
Description=Manage VDE Switch<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/etc/systemd/scripts/qemu-network-env start<br />
ExecStop=/etc/systemd/scripts/qemu-network-env stop<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
Change permissions for {{ic|qemu-network-env}} to be executable<br />
<br />
# chmod u+x /etc/systemd/scripts/qemu-network-env<br />
<br />
You can [[start]] {{ic|qemu-network-env.service}} as usual.<br />
<br />
====Alternative method====<br />
<br />
If the above method does not work or you do not want to mess with kernel configs, TUN, dnsmasq, and iptables you can do the following for the same result.<br />
<br />
# vde_switch -daemon -mod 660 -group users<br />
# slirpvde --dhcp --daemon<br />
<br />
Then, to start the VM with a connection to the network of the host:<br />
<br />
$ qemu-system-x86_64 -net nic,macaddr=52:54:00:00:EE:03 -net vde ''disk_image''<br />
<br />
=== VDE2 Bridge ===<br />
<br />
Based on [https://selamatpagicikgu.wordpress.com/2011/06/08/quickhowto-qemu-networking-using-vde-tuntap-and-bridge/ quickhowto: qemu networking using vde, tun/tap, and bridge] graphic. Any virtual machine connected to vde is externally exposed. For example, each virtual machine can receive DHCP configuration directly from your ADSL router.<br />
<br />
==== Basics ====<br />
<br />
Remember that you need {{ic|tun}} module and {{Pkg|bridge-utils}} package.<br />
<br />
Create the vde2/tap device:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
# ip link set tap0 up<br />
<br />
Create bridge:<br />
<br />
# brctl addbr br0<br />
<br />
Add devices:<br />
<br />
# brctl addif br0 eth0<br />
# brctl addif br0 tap0<br />
<br />
And configure bridge interface:<br />
<br />
# dhcpcd br0<br />
<br />
==== Startup scripts ====<br />
<br />
All devices must be set up. And only the bridge needs an IP address. For physical devices on the bridge (e.g. {{ic|eth0}}), this can be done with [[netctl]] using a custom Ethernet profile with:<br />
<br />
{{hc|/etc/netctl/ethernet-noip|2=<br />
Description='A more versatile static Ethernet connection'<br />
Interface=eth0<br />
Connection=ethernet<br />
IP=no<br />
}}<br />
<br />
The following custom systemd service can be used to create and activate a VDE2 tap interface for use in the {{ic|users}} user group.<br />
<br />
{{hc|/etc/systemd/system/vde2@.service|2=<br />
[Unit]<br />
Description=Network Connectivity for %i<br />
Wants=network.target<br />
Before=network.target<br />
<br />
[Service]<br />
Type=oneshot<br />
RemainAfterExit=yes<br />
ExecStart=/usr/bin/vde_switch -tap %i -daemon -mod 660 -group users<br />
ExecStart=/usr/bin/ip link set dev %i up<br />
ExecStop=/usr/bin/ip addr flush dev %i<br />
ExecStop=/usr/bin/ip link set dev %i down<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
}}<br />
<br />
And finally, you can create the [[Bridge with netctl|bridge interface with netctl]].<br />
<br />
=== Shorthand configuration ===<br />
<br />
If you are using QEMU with various networking options a lot, you probably have created a lot of {{ic|-netdev}} and {{ic|-device}} argument pairs, which gets quite repetitive. You can instead use the {{ic|-nic}} argument to combine {{ic|-netdev}} and {{ic|-device}} together, so that, for example, these arguments:<br />
<br />
-netdev tap,id=network0,ifname=tap0,script=no,downscript=no,vhost=on -device virtio-net-pci,netdev=network0<br />
<br />
become:<br />
<br />
-nic tap,script=no,downscript=no,vhost=on,model=virtio-net-pci<br />
<br />
Notice the lack of network IDs, and that the device was created with {{ic|1=model=}}. The first half of the {{ic|-nic}} parameters are {{ic|-netdev}} parameters, whereas the second half (after {{ic|1=model=}}) are related with the device. The same parameters (for example, {{ic|1=smb=}}) are used. To completely disable the networking use {{ic|-nic none}}.<br />
<br />
See [https://qemu.weilnetz.de/doc/qemu-doc.html#Network-options QEMU networking documentation] for more information on parameters you can use.<br />
<br />
== Graphic card ==<br />
<br />
QEMU can emulate a standard graphic card text mode using {{ic|-curses}} command line option. This allows to type text and see text output directly inside a text terminal.<br />
<br />
QEMU can emulate several types of VGA card. The card type is passed in the {{ic|-vga ''type''}} command line option and can be {{ic|std}}, {{ic|qxl}}, {{ic|vmware}}, {{ic|virtio}}, {{ic|cirrus}} or {{ic|none}}.<br />
<br />
=== std ===<br />
<br />
With {{ic|-vga std}} you can get a resolution of up to 2560 x 1600 pixels without requiring guest drivers. This is the default since QEMU 2.2.<br />
<br />
=== qxl ===<br />
<br />
QXL is a paravirtual graphics driver with 2D support. To use it, pass the {{ic|-vga qxl}} option and install drivers in the guest. You may want to use [[#SPICE]] for improved graphical performance when using QXL.<br />
<br />
On Linux guests, the {{ic|qxl}} and {{ic|bochs_drm}} kernel modules must be loaded in order to gain a decent performance.<br />
<br />
Default VGA memory size for QXL devices is 16M which is sufficient to drive resolutions approximately up to QHD (2560x1440). To enable higher resolutions, [[#Multi-monitor support|increase vga_memmb]].<br />
<br />
=== vmware ===<br />
<br />
Although it is a bit buggy, it performs better than std and cirrus. Install the VMware drivers {{Pkg|xf86-video-vmware}} and {{Pkg|xf86-input-vmmouse}} for Arch Linux guests.<br />
<br />
=== virtio ===<br />
<br />
{{ic|virtio-vga}} / {{ic|virtio-gpu}} is a paravirtual 3D graphics driver based on [https://virgil3d.github.io/ virgl]. Currently a work in progress, supporting only very recent (>= 4.4) Linux guests with {{Pkg|mesa}} (>=11.2) compiled with the option {{ic|1=gallium-drivers=virgl}}.<br />
<br />
To enable 3D acceleration on the guest system select this vga with {{ic|-vga virtio}} and enable the opengl context in the display device with {{ic|1=-display sdl,gl=on}} or {{ic|1=-display gtk,gl=on}} for the sdl and gtk display output respectively. Successful configuration can be confirmed looking at the kernel log in the guest:<br />
<br />
{{hc|$ dmesg {{!}} grep drm |<br />
[drm] pci: virtio-vga detected<br />
[drm] virgl 3d acceleration enabled<br />
}}<br />
<br />
=== cirrus ===<br />
<br />
The cirrus graphical adapter was the default [http://wiki.qemu.org/ChangeLog/2.2#VGA before 2.2]. It [https://www.kraxel.org/blog/2014/10/qemu-using-cirrus-considered-harmful/ should not] be used on modern systems.<br />
<br />
=== none ===<br />
<br />
This is like a PC that has no VGA card at all. You would not even be able to access it with the {{ic|-vnc}} option. Also, this is different from the {{ic|-nographic}} option which lets QEMU emulate a VGA card, but disables the SDL display.<br />
<br />
== SPICE ==<br />
The [http://spice-space.org/ SPICE project] aims to provide a complete open source solution for remote access to virtual machines in a seamless way.<br />
=== Enabling SPICE support on the host ===<br />
The following is an example of booting with SPICE as the remote desktop protocol, including the support for copy and paste from host:<br />
<br />
$ qemu-system-x86_64 -vga qxl -device virtio-serial-pci -spice port=5930,disable-ticketing -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
The parameters have the following meaning:<br />
<br />
# {{ic|-device virtio-serial-pci}} adds a virtio-serial device<br />
# {{ic|1=-spice port=5930,disable-ticketing}} set TCP port {{ic|5930}} for spice channels listening and allow client to connect without authentication{{Tip|Using [[wikipedia:Unix_socket|Unix sockets]] instead of TCP ports does not involve using network stack on the host system. It does not imply that packets are encapsulated and decapsulated to use the network and the related protocol. The sockets are identified solely by the inodes on the hard drive. It is therefore considered better for performance. Use instead {{ic|1=-spice unix,addr=/tmp/vm_spice.socket,disable-ticketing}}.}}<br />
# {{ic|1=-device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0}} opens a port for spice vdagent in the virtio-serial device,<br />
# {{ic|1=-chardev spicevmc,id=spicechannel0,name=vdagent}} adds a spicevmc chardev for that port. It is important that the {{ic|1=chardev=}} option of the {{ic|virtserialport}} device matches the {{ic|1=id=}} option given to the {{ic|chardev}} option ({{ic|spicechannel0}} in this example). It is also important that the port name is {{ic|com.redhat.spice.0}}, because that is the namespace where vdagent is looking for in the guest. And finally, specify {{ic|1=name=vdagent}} so that spice knows what this channel is for.<br />
<br />
=== Connecting to the guest with a SPICE client ===<br />
<br />
A SPICE client is necessary to connect to the guest. In Arch, the following clients are available:<br />
<br />
{{App|virt-viewer|SPICE client recommended by the protocol developers, a subset of the virt-manager project.|https://virt-manager.org/|{{Pkg|virt-viewer}}}}<br />
<br />
{{App|spice-gtk|SPICE GTK client, a subset of the SPICE project. Embedded into other applications as a widget.|https://www.spice-space.org/|{{Pkg|spice-gtk}}}}<br />
<br />
For clients that run on smartphone or on other platforms, refer to the ''Other clients'' section in [http://www.spice-space.org/download.html spice-space download].<br />
<br />
==== Manually running a SPICE client ====<br />
<br />
One way of connecting to a guest listening on Unix socket {{ic|/tmp/vm_spice.socket}} is to manually run the SPICE client using {{ic|$ remote-viewer spice+unix:///tmp/vm_spice.socket}} or {{ic|1=$ spicy --uri="spice+unix:///tmp/vm_spice.socket"}}, depending on the desired client. Since QEMU in SPICE mode acts similarly to a remote desktop server, it may be more convenient to run QEMU in daemon mode with the {{ic|-daemonize}} parameter.<br />
<br />
{{Tip|To connect to the guest through SSH tunelling, the following type of command can be used: {{bc|$ ssh -fL 5999:localhost:5930 ''my.domain.org'' sleep 10; spicy -h 127.0.0.1 -p 5999}}<br />
This example connects ''spicy'' to the local port {{ic|5999}} which is forwarded through SSH to the guest's SPICE server located at the address ''my.domain.org'', port {{ic|5930}}.<br />
Note the {{ic|-f}} option that requests ssh to execute the command {{ic|sleep 10}} in the background. This way, the ssh session runs while the client is active and auto-closes once the client ends.<br />
}}<br />
<br />
==== Running a SPICE client with QEMU ====<br />
<br />
QEMU can automatically start a SPICE client with an appropriate socket, if the display is set to SPICE with the {{ic|-display spice-app}} parameter. This will use the system's default SPICE client as the viewer, determined by your [[XDG_MIME_Applications#mimeapps.list|mimeapps.list]] files.<br />
<br />
=== Enabling SPICE support on the guest ===<br />
<br />
For '''Arch Linux guests''', for improved support for multiple monitors or clipboard sharing, the following packages should be installed:<br />
* {{Pkg|spice-vdagent}}: Spice agent xorg client that enables copy and paste between client and X-session and more.<br />
* {{Pkg|xf86-video-qxl}}: Xorg X11 qxl video driver<br />
For guests under '''other operating systems''', refer to the ''Guest'' section in [http://www.spice-space.org/download.html spice-space download].<br />
<br />
=== Password authentication with SPICE ===<br />
<br />
If you want to enable password authentication with SPICE you need to remove {{ic|disable-ticketing}} from the {{ic|-spice}} argument and instead add {{ic|1=password=''yourpassword''}}. For example:<br />
<br />
$ qemu-system-x86_64 -vga qxl -spice port=5900,password=''yourpassword'' -device virtio-serial-pci -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
Your SPICE client should now ask for the password to be able to connect to the SPICE server.<br />
<br />
=== TLS encrypted communication with SPICE ===<br />
<br />
You can also configure TLS encryption for communicating with the SPICE server. First, you need to have a directory which contains the following files (the names must be exactly as indicated):<br />
<br />
* {{ic|ca-cert.pem}}: the CA master certificate.<br />
* {{ic|server-cert.pem}}: the server certificate signed with {{ic|ca-cert.pem}}.<br />
* {{ic|server-key.pem}}: the server private key.<br />
<br />
An example of generation of self-signed certificates with your own generated CA for your server is shown in the [https://www.spice-space.org/spice-user-manual.html#_generating_self_signed_certificates Spice User Manual].<br />
<br />
Afterwards, you can run QEMU with SPICE as explained above but using the following {{ic|-spice}} argument: {{ic|1=-spice tls-port=5901,password=''yourpassword'',x509-dir=''/path/to/pki_certs''}}, where {{ic|''/path/to/pki_certs''}} is the directory path that contains the three needed files shown earlier.<br />
<br />
It is now possible to connect to the server using {{pkg|virt-viewer}}:<br />
<br />
$ remote-viewer spice://''hostname''?tls-port=5901 --spice-ca-file=''/path/to/ca-cert.pem'' --spice-host-subject="C=''XX'',L=''city'',O=''organization'',CN=''hostname''" --spice-secure-channels=all<br />
<br />
Keep in mind that the {{ic|--spice-host-subject}} parameter needs to be set according to your {{ic|server-cert.pem}} subject. You also need to copy {{ic|ca-cert.pem}} to every client to verify the server certificate.<br />
<br />
{{Tip|You can get the subject line of the server certificate in the correct format for {{ic|--spice-host-subject}} (with entries separated by commas) using the following command: {{bc|<nowiki>$ openssl x509 -noout -subject -in server-cert.pem | cut -d' ' -f2- | sed 's/\///' | sed 's/\//,/g'</nowiki>}}<br />
}}<br />
<br />
The equivalent {{Pkg|spice-gtk}} command is:<br />
<br />
$ spicy -h ''hostname'' -s 5901 --spice-ca-file=ca-cert.pem --spice-host-subject="C=''XX'',L=''city'',O=''organization'',CN=''hostname''" --spice-secure-channels=all<br />
<br />
== VNC ==<br />
<br />
One can add the {{ic|-vnc :''X''}} option to have QEMU redirect the VGA display to the VNC session. Substitute {{ic|''X''}} for the number of the display (0 will then listen on 5900, 1 on 5901...).<br />
<br />
$ qemu-system-x86_64 -vnc :0<br />
<br />
An example is also provided in the [[#Starting QEMU virtual machines on boot]] section.<br />
{{Warning|The default VNC server setup does not use any form of authentication. Any user can connect from any host.}}<br />
<br />
=== Basic password authentication ===<br />
<br />
An access password can be setup easily by using the {{ic|password}} option. The password must be indicated in the QEMU monitor and connection is only possible once the password is provided.<br />
<br />
$ qemu-system-x86_64 -vnc :0,password -monitor stdio<br />
<br />
In the QEMU monitor, password is set using the command {{ic|change vnc password}} and then indicating the password.<br />
<br />
The following command line directly runs vnc with a password:<br />
<br />
$ printf "change vnc password\n%s\n" MYPASSWORD | qemu-system-x86_64 -vnc :0,password -monitor stdio<br />
<br />
{{Note|The password is limited to 8 characters and can be guessed through brute force attack. More elaborated protection is strongly recommended for public network.}}<br />
<br />
== Audio ==<br />
<br />
=== Host ===<br />
<br />
The {{ic|-audiodev}} flag sets the audio backend driver and its options. The list of available audio backend drivers and their optional settings is detailed in the {{man|1|qemu}}. man page.<br />
<br />
At the bare minimum, you need to choose a driver and set an id.<br />
<br />
-audiodev pa,id=snd0<br />
<br />
=== Guest ===<br />
<br />
==== With audiodev ====<br />
<br />
===== Intel HD Audio =====<br />
<br />
For Intel HD Audio emulation add both controller and codec devices. To list the available Intel HDA Audio devices:<br />
<br />
$ qemu-system-x86_64 -device help | grep hda<br />
<br />
Add the audio controller<br />
<br />
-device ich9-intel-hda<br />
<br />
Add the audio codec and map it to a host audio backend id<br />
<br />
-device hda-output,audiodev=snd0<br />
<br />
===== Intel 82801AA AC97 =====<br />
<br />
For AC97 emulation just add the audio card device and map it to a host audio backend id<br />
<br />
-device AC97,audiodev=snd0<br />
<br />
==== Without audiodev ====<br />
<br />
To get list of the supported emulation audio drivers:<br />
$ qemu-system-x86_64 -soundhw help<br />
<br />
To use e.g. {{ic|hda}} driver for the guest use the {{ic|-soundhw hda}} command with QEMU.<br />
<br />
{{Note|Video graphic card emulated drivers for the guest machine may also cause a problem with the sound quality. Test one by one to make it work. You can list possible options with {{ic|<nowiki>qemu-system-x86_64 -h | grep vga</nowiki>}}.}}<br />
<br />
== Installing virtio drivers ==<br />
<br />
QEMU offers guests the ability to use paravirtualized block and network devices using the [http://wiki.libvirt.org/page/Virtio virtio] drivers, which provide better performance and lower overhead.<br />
<br />
* A virtio block device requires the option {{Ic|-drive}} for passing a disk image, with parameter {{Ic|1=if=virtio}}:<br />
$ qemu-system-x86_64 -boot order=c -drive file=''disk_image'',if=virtio<br />
<br />
* Almost the same goes for the network:<br />
$ qemu-system-x86_64 -nic user,model=virtio-net-pci<br />
<br />
{{Note|This will only work if the guest machine has drivers for virtio devices. Linux does, and the required drivers are included in Arch Linux, but there is no guarantee that virtio devices will work with other operating systems.}}<br />
<br />
=== Preparing an (Arch) Linux guest ===<br />
<br />
To use virtio devices after an Arch Linux guest has been installed, the following modules must be loaded in the guest: {{Ic|virtio}}, {{Ic|virtio_pci}}, {{Ic|virtio_blk}}, {{Ic|virtio_net}}, and {{Ic|virtio_ring}}. For 32-bit guests, the specific "virtio" module is not necessary.<br />
<br />
If you want to boot from a virtio disk, the initial ramdisk must contain the necessary modules. By default, this is handled by [[mkinitcpio]]'s {{ic|autodetect}} hook. Otherwise use the {{ic|MODULES}} array in {{ic|/etc/mkinitcpio.conf}} to include the necessary modules and rebuild the initial ramdisk.<br />
<br />
{{hc|/etc/mkinitcpio.conf|2=<br />
MODULES=(virtio virtio_blk virtio_pci virtio_net)}}<br />
<br />
Virtio disks are recognized with the prefix {{ic|'''v'''}} (e.g. {{ic|'''v'''da}}, {{ic|'''v'''db}}, etc.); therefore, changes must be made in at least {{ic|/etc/fstab}} and {{ic|/boot/grub/grub.cfg}} when booting from a virtio disk.<br />
<br />
{{Tip|When referencing disks by [[UUID]] in both {{ic|/etc/fstab}} and bootloader, nothing has to be done.}}<br />
<br />
Further information on paravirtualization with KVM can be found [http://www.linux-kvm.org/page/Boot_from_virtio_block_device here].<br />
<br />
You might also want to install {{Pkg|qemu-guest-agent}} to implement support for QMP commands that will enhance the hypervisor management capabilities. After installing the package you can enable and start the {{ic|qemu-ga.service}}.<br />
<br />
=== Preparing a Windows guest ===<br />
<br />
==== Block device drivers ====<br />
<br />
===== New Install of Windows =====<br />
<br />
Windows does not come with the virtio drivers. Therefore, you will need to load them during installation. There are basically two ways to do this: via Floppy Disk or via ISO files. Both images can be downloaded from the [https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/stable-virtio/virtio-win.iso Fedora repository].<br />
<br />
The floppy disk option is difficult because you will need to press F6 (Shift-F6 on newer Windows) at the very beginning of powering on the QEMU. This is difficult since you need time to connect your VNC console window. You can attempt to add a delay to the boot sequence. See {{man|1|qemu}} for more details about applying a delay at boot.<br />
<br />
The ISO option to load drivers is the preferred way, but it is available only on Windows Vista and Windows Server 2008 and later. The procedure is to load the image with virtio drivers in an additional cdrom device along with the primary disk device and Windows installer:<br />
<br />
$ qemu-system-x86_64 ... \<br />
-drive file=''windows_disk_image'',index=0,media=disk,if=virtio \<br />
-drive file=''windows.iso'',index=2,media=cdrom \<br />
-drive file=''virtio.iso'',index=3,media=cdrom \<br />
...<br />
<br />
During the installation, at some stage, the Windows installer will ask "Where do you want to install Windows?", it will give a warning that no disks are found. Follow the example instructions below (based on Windows Server 2012 R2 with Update).<br />
<br />
* Select the option ''Load Drivers''.<br />
* Uncheck the box for ''Hide drivers that aren't compatible with this computer's hardware''.<br />
* Click the browse button and open the CDROM for the virtio iso, usually named "virtio-win-XX".<br />
* Now browse to {{ic|E:\viostor\[your-os]\amd64}}, select it, and confirm.<br />
<br />
You should now see your virtio disk(s) listed here, ready to be selected, formatted and installed to.<br />
<br />
===== Change Existing Windows VM to use virtio =====<br />
<br />
Modifying an existing Windows guest for booting from virtio disk requires that the virtio driver is available in the guest and that it is loaded at boot time.<br />
<br />
One can find the virtio disk driver in the [https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/stable-virtio/virtio-win.iso Fedora repository].<br />
<br />
Now, create a new disk image that will be used to search for the virtio driver:<br />
<br />
$ qemu-img create -f qcow2 ''fake.qcow2'' 1G<br />
<br />
Run the original Windows guest (with the boot disk still in IDE mode) with the fake disk (in virtio mode) and a CD-ROM with the driver.<br />
<br />
$ qemu-system-x86_64 -m 512 -drive file=''windows_disk_image'',if=ide -drive file=''fake.qcow2'',if=virtio -cdrom virtio-win-0.1-81.iso<br />
<br />
Windows will detect the fake disk and look for a suitable driver. If it fails, go to ''Device Manager'', locate the SCSI drive with an exclamation mark icon (should be open), click ''Update driver'' and select the virtual CD-ROM. Do not navigate to the driver folder within the CD-ROM, simply select the CD-ROM drive and Windows will find the appropriate driver automatically (tested for Windows 7 SP1).<br />
<br />
Request Windows to boot in safe mode next time it starts up. This can be done using the ''msconfig.exe'' tool in Windows. In safe mode all the drivers will be loaded at boot time including the new virtio driver. Once Windows knows that the virtio driver is required at boot it will memorize it for future boot.<br />
<br />
Once instructed to boot in safe mode, you can turn off the virtual machine and launch it again, now with the boot disk attached in virtio mode:<br />
<br />
$ qemu-system-x86_64 -m 512 -drive file=''windows_disk_image'',if=virtio<br />
<br />
You should boot in safe mode with virtio driver loaded, you can now return to ''msconfig.exe'' disable safe mode boot and restart Windows.<br />
<br />
{{Note|If you encounter the blue screen of death using the {{ic|1=if=virtio}} parameter, it probably means the virtio disk driver is not installed or not loaded at boot time, reboot in safe mode and check your driver configuration.}}<br />
<br />
==== Network drivers ====<br />
<br />
Installing virtio network drivers is a bit easier, simply add the {{ic|-nic}} argument.<br />
<br />
$ qemu-system-x86_64 -m 512 -drive file=''windows_disk_image'',if=virtio -nic user,model=virtio-net-pci -cdrom virtio-win-0.1-74.iso<br />
<br />
Windows will detect the network adapter and try to find a driver for it. If it fails, go to the ''Device Manager'', locate the network adapter with an exclamation mark icon (should be open), click ''Update driver'' and select the virtual CD-ROM. Do not forget to select the checkbox which says to search for directories recursively.<br />
<br />
==== Balloon driver ====<br />
<br />
If you want to track you guest memory state (for example via {{ic|virsh}} command {{ic|dommemstat}}) or change guest's memory size in runtime (you still will not be able to change memory size, but can limit memory usage via inflating balloon driver) you will need to install guest balloon driver.<br />
<br />
For this you will need to go to ''Device Manager'', locate ''PCI standard RAM Controller'' in ''System devices'' (or unrecognized PCI controller from ''Other devices'') and choose ''Update driver''. In opened window you will need to choose ''Browse my computer...'' and select the CD-ROM (and do not forget the ''Include subdirectories'' checkbox). Reboot after installation. This will install the driver and you will be able to inflate the balloon (for example via hmp command {{ic|balloon ''memory_size''}}, which will cause balloon to take as much memory as possible in order to shrink the guest's available memory size to ''memory_size''). However, you still will not be able to track guest memory state. In order to do this you will need to install ''Balloon'' service properly. For that open command line as administrator, go to the CD-ROM, ''Balloon'' directory and deeper, depending on your system and architecture. Once you are in ''amd64'' (''x86'') directory, run {{ic|blnsrv.exe -i}} which will do the installation. After that {{ic|virsh}} command {{ic|dommemstat}} should be outputting all supported values.<br />
<br />
=== Preparing a FreeBSD guest ===<br />
<br />
Install the {{ic|emulators/virtio-kmod}} port if you are using FreeBSD 8.3 or later up until 10.0-CURRENT where they are included into the kernel. After installation, add the following to your {{ic|/boot/loader.conf}} file:<br />
<br />
{{bc|1=<br />
virtio_load="YES"<br />
virtio_pci_load="YES"<br />
virtio_blk_load="YES"<br />
if_vtnet_load="YES"<br />
virtio_balloon_load="YES"<br />
}}<br />
<br />
Then modify your {{ic|/etc/fstab}} by doing the following:<br />
<br />
# sed -ibak "s/ada/vtbd/g" /etc/fstab<br />
<br />
And verify that {{ic|/etc/fstab}} is consistent. If anything goes wrong, just boot into a rescue CD and copy {{ic|/etc/fstab.bak}} back to {{ic|/etc/fstab}}.<br />
<br />
== QEMU monitor ==<br />
<br />
While QEMU is running, a monitor console is provided in order to provide several ways to interact with the virtual machine running. The QEMU monitor offers interesting capabilities such as obtaining information about the current virtual machine, hotplugging devices, creating snapshots of the current state of the virtual machine, etc. To see the list of all commands, run {{ic|help}} or {{ic|?}} in the QEMU monitor console or review the relevant section of the [https://qemu.weilnetz.de/doc/qemu-doc.html#pcsys_005fmonitor official QEMU documentation].<br />
<br />
=== Accessing the monitor console ===<br />
<br />
==== Graphical view ====<br />
<br />
When using the {{ic|std}} default graphics option, one can access the QEMU monitor by pressing {{ic|Ctrl+Alt+2}} or by clicking ''View > compatmonitor0'' in the QEMU window. To return to the virtual machine graphical view either press {{ic|Ctrl+Alt+1}} or click ''View > VGA''.<br />
<br />
However, the standard method of accessing the monitor is not always convenient and does not work in all graphic outputs QEMU supports.<br />
<br />
==== Telnet ====<br />
<br />
To enable [[telnet]], run QEMU with the {{ic|-monitor telnet:127.0.0.1:''port'',server,nowait}} parameter. When the virtual machine is started you will be able to access the monitor via telnet:<br />
<br />
$ telnet 127.0.0.1 ''port''<br />
<br />
{{Note|If {{ic|127.0.0.1}} is specified as the IP to listen it will be only possible to connect to the monitor from the same host QEMU is running on. If connecting from remote hosts is desired, QEMU must be told to listen {{ic|0.0.0.0}} as follows: {{ic|-monitor telnet:0.0.0.0:''port'',server,nowait}}. Keep in mind that it is recommended to have a [[firewall]] configured in this case or make sure your local network is completely trustworthy since this connection is completely unauthenticated and unencrypted.}}<br />
<br />
==== UNIX socket ====<br />
<br />
Run QEMU with the {{ic|-monitor unix:''socketfile'',server,nowait}} parameter. Then you can connect with either {{pkg|socat}} or {{pkg|openbsd-netcat}}.<br />
<br />
For example, if QEMU is run via:<br />
<br />
$ qemu-system-x86_64 ''[...]'' -monitor unix:/tmp/monitor.sock,server,nowait ''[...]''<br />
<br />
It is possible to connect to the monitor with:<br />
<br />
$ socat - UNIX-CONNECT:/tmp/monitor.sock<br />
<br />
Or with:<br />
<br />
$ nc -U /tmp/monitor.sock<br />
<br />
==== TCP ====<br />
<br />
You can expose the monitor over TCP with the argument {{ic|-monitor tcp:127.0.0.1:''port'',server,nowait}}. Then connect with netcat, either {{pkg|openbsd-netcat}} or {{pkg|gnu-netcat}} by running:<br />
<br />
$ nc 127.0.0.1 ''port''<br />
<br />
{{Note|In order to be able to connect to the tcp socket from other devices other than the same host QEMU is being run on you need to listen to {{ic|0.0.0.0}} like explained in the telnet case. The same security warnings apply in this case as well.}}<br />
<br />
==== Standard I/O ====<br />
<br />
It is possible to access the monitor automatically from the same terminal QEMU is being run by running it with the argument {{ic|-monitor stdio}}.<br />
<br />
=== Sending keyboard presses to the virtual machine using the monitor console ===<br />
<br />
Some combinations of keys may be difficult to perform on virtual machines due to the host intercepting them instead in some configurations (a notable example is the {{ic|Ctrl+Alt+F*}} key combinations, which change the active tty). To avoid this problem, the problematic combination of keys may be sent via the monitor console instead. Switch to the monitor and use the {{ic|sendkey}} command to forward the necessary keypresses to the virtual machine. For example:<br />
<br />
(qemu) sendkey ctrl-alt-f2<br />
<br />
=== Creating and managing snapshots via the monitor console ===<br />
<br />
{{Note|This feature will '''only''' work when the virtual machine disk image is in ''qcow2'' format. It will not work with ''raw'' images.}}<br />
<br />
It is sometimes desirable to save the current state of a virtual machine and having the possibility of reverting the state of the virtual machine to that of a previously saved snapshot at any time. The QEMU monitor console provides the user with the necessary utilities to create snapshots, manage them, and revert the machine state to a saved snapshot.<br />
<br />
* Use {{ic|savevm ''name''}} in order to create a snapshot with the tag ''name''.<br />
* Use {{ic|loadvm ''name''}} to revert the virtual machine to the state of the snapshot ''name''.<br />
* Use {{ic|delvm ''name''}} to delete the snapshot tagged as ''name''.<br />
* Use {{ic|info snapshots}} to see a list of saved snapshots. Snapshots are identified by both an auto-incremented ID number and a text tag (set by the user on snapshot creation).<br />
<br />
=== Running the virtual machine in immutable mode ===<br />
<br />
It is possible to run a virtual machine in a frozen state so that all changes will be discarded when the virtual machine is powered off just by running QEMU with the {{ic|-snapshot}} parameter. When the disk image is written by the guest, changes will be saved in a temporary file in {{ic|/tmp}} and will be discarded when QEMU halts.<br />
<br />
However, if a machine is running in frozen mode it is still possible to save the changes to the disk image if it is afterwards desired by using the monitor console and running the following command:<br />
<br />
(qemu) commit all<br />
<br />
If snapshots are created when running in frozen mode they will be discarded as soon as QEMU is exited unless changes are explicitly commited to disk, as well.<br />
<br />
=== Pause and power options via the monitor console ===<br />
<br />
Some operations of a physical machine can be emulated by QEMU using some monitor commands:<br />
<br />
* {{ic|system_powerdown}} will send an ACPI shutdown request to the virtual machine. This effect is similar to the power button in a physical machine.<br />
* {{ic|system_reset}} will reset the virtual machine similarly to a reset button in a physical machine. This operation can cause data loss and file system corruption since the virtual machine is not cleanly restarted.<br />
* {{ic|stop}} will pause the virtual machine.<br />
* {{ic|cont}} will resume a virtual machine previously paused.<br />
<br />
=== Taking screenshots of the virtual machine ===<br />
<br />
Screenshots of the virtual machine graphic display can be obtained in the PPM format by running the following command in the monitor console:<br />
<br />
(qemu) screendump ''file.ppm''<br />
<br />
== QEMU machine protocol ==<br />
<br />
The QEMU machine protocol (QMP) is a JSON-based protocol which allows applications to control a QEMU instance. Similarly to the [[#QEMU monitor]] it offers ways to interact with a running machine and the JSON protocol allows to do it programmatically. The description of all the QMP commands can be found in [https://raw.githubusercontent.com/coreos/qemu/master/qmp-commands.hx qmp-commands].<br />
<br />
=== Start QMP ===<br />
<br />
The usual way to control the guest using the QMP protocol, is to open a TCP socket when launching the machine using the {{ic|-qmp}} option. Here it is using for example the TCP port 4444:<br />
<br />
$ qemu-system-x86_64 ''[...]'' -qmp tcp:localhost:4444,server,nowait<br />
<br />
Then one way to communicate with the QMP agent is to use [[netcat]]:<br />
<br />
{{hc|nc localhost 4444|{"QMP": {"version": {"qemu": {"micro": 0, "minor": 1, "major": 3}, "package": ""}, "capabilities": []} } }}<br />
<br />
At this stage, the only command that can be recognized is {{ic|qmp_capabilities}}, so that QMP enters into command mode. Type:<br />
<br />
{"execute": "qmp_capabilities"}<br />
<br />
Now, QMP is ready to receive commands, to retrieve the list of recognized commands, use:<br />
<br />
{"execute": "query-commands"}<br />
<br />
=== Live merging of child image into parent image ===<br />
<br />
It is possible to merge a running snapshot into its parent by issuing a {{ic|block-commit}} command. In its simplest form the following line will commit the child into its parent:<br />
<br />
{"execute": "block-commit", "arguments": {"device": "''devicename''"}}<br />
<br />
Upon reception of this command, the handler looks for the base image and converts it from read only to read write mode and then runs the commit job.<br />
<br />
Once the ''block-commit'' operation has completed, the event {{ic|BLOCK_JOB_READY}} will be emitted, signalling that the synchronization has finished. The job can then be gracefully completed by issuing the command {{ic|block-job-complete}}:<br />
<br />
{"execute": "block-job-complete", "arguments": {"device": "''devicename''"}}<br />
<br />
Until such a command is issued, the ''commit'' operation remains active.<br />
After successful completion, the base image remains in read write mode and becomes the new active layer. On the other hand, the child image becomes invalid and it is the responsibility of the user to clean it up.<br />
<br />
{{Tip|The list of device and their names can be retrieved by executing the command {{ic|query-block}} and parsing the results. The device name is in the {{ic|device}} field, for example {{ic|ide0-hd0}} for the hard disk in this example: {{hc|{"execute": "query-block"}|{"return": [{"io-status": "ok", "device": "'''ide0-hd0'''", "locked": false, "removable": false, "inserted": {"iops_rd": 0, "detect_zeroes": "off", "image": {"backing-image": {"virtual-size": 27074281472, "filename": "parent.qcow2", ... } }} }}<br />
<br />
=== Live creation of a new snapshot ===<br />
<br />
To create a new snapshot out of a running image, run the command:<br />
<br />
{"execute": "blockdev-snapshot-sync", "arguments": {"device": "''devicename''","snapshot-file": "''new_snapshot_name''.qcow2"}}<br />
<br />
This creates an overlay file named {{ic|''new_snapshot_name''.qcow2}} which then becomes the new active layer.<br />
<br />
== Tips and tricks ==<br />
=== Improve virtual machine performance ===<br />
<br />
There are a number of techniques that you can use to improve the performance of the virtual machine. For example:<br />
<br />
* Apply [[#Enabling KVM]]: add {{ic|-enable-kvm}} to the QEMU start command you use.<br />
* Use the {{ic|-cpu host}} option to make QEMU emulate the host's exact CPU. If you do not do this, it may be trying to emulate a more generic CPU.<br />
* Especially for Windows guests, enable [http://blog.wikichoon.com/2014/07/enabling-hyper-v-enlightenments-with-kvm.html Hyper-V enlightenments]: {{ic|1=-cpu host,hv_relaxed,hv_spinlocks=0x1fff,hv_vapic,hv_time}}.<br />
* If the host machine has multiple cores, assign the guest more cores using the {{ic|-smp}} option.<br />
* Make sure you have assigned the virtual machine enough memory. By default, QEMU only assigns 128 MiB of memory to each virtual machine. Use the {{ic|-m}} option to assign more memory. For example, {{ic|-m 1024}} runs a virtual machine with 1024 MiB of memory.<br />
* If supported by drivers in the guest operating system, use [http://wiki.libvirt.org/page/Virtio virtio] for network and/or block devices. For example:<br />
$ qemu-system-x86_64 -net nic,model=virtio -net tap,if=tap0,script=no -drive file=''disk_image'',media=disk,if=virtio<br />
* Use TAP devices instead of user-mode networking. See [[#Tap networking with QEMU]].<br />
* If the guest OS is doing heavy writing to its disk, you may benefit from certain mount options on the host's file system. For example, you can mount an [[Ext4|ext4 file system]] with the option {{ic|1=barrier=0}}. You should read the documentation for any options that you change because sometimes performance-enhancing options for file systems come at the cost of data integrity.<br />
* If you have a raw disk image, you may want to disable the cache:<br />
$ qemu-system-x86_64 -drive file=''disk_image'',if=virtio,'''cache=none'''<br />
* Use the native Linux AIO:<br />
$ qemu-system-x86_64 -drive file=''disk_image'',if=virtio''',aio=native,cache.direct=on'''<br />
* If you are running multiple virtual machines concurrently that all have the same operating system installed, you can save memory by enabling [[wikipedia:Kernel_SamePage_Merging_(KSM)|kernel same-page merging]]. See [[#Enabling KSM]].<br />
* In some cases, memory can be reclaimed from running virtual machines by running a memory ballooning driver in the guest operating system and launching QEMU using {{ic|-device virtio-balloon}}.<br />
* It is possible to use a emulation layer for an ICH-9 AHCI controller (although it may be unstable). The AHCI emulation supports [[Wikipedia:Native_Command_Queuing|NCQ]], so multiple read or write requests can be outstanding at the same time:<br />
$ qemu-system-x86_64 -drive id=disk,file=''disk_image'',if=none -device ich9-ahci,id=ahci -device ide-drive,drive=disk,bus=ahci.0<br />
<br />
See http://www.linux-kvm.org/page/Tuning_KVM for more information.<br />
<br />
=== Starting QEMU virtual machines on boot ===<br />
<br />
==== With libvirt ====<br />
<br />
If a virtual machine is set up with [[libvirt]], it can be configured with {{ic|virsh autostart}} or through the ''virt-manager'' GUI to start at host boot by going to the Boot Options for the virtual machine and selecting "Start virtual machine on host boot up".<br />
<br />
==== With systemd service ====<br />
<br />
To run QEMU VMs on boot, you can use following systemd unit and config.<br />
<br />
{{hc|/etc/systemd/system/qemu@.service|2=<br />
[Unit]<br />
Description=QEMU virtual machine<br />
<br />
[Service]<br />
Environment="haltcmd=kill -INT $MAINPID"<br />
EnvironmentFile=/etc/conf.d/qemu.d/%i<br />
ExecStart=/usr/bin/qemu-system-x86_64 -name %i -enable-kvm -m 512 -nographic $args<br />
ExecStop=/usr/bin/bash -c ${haltcmd}<br />
ExecStop=/usr/bin/bash -c 'while nc localhost 7100; do sleep 1; done'<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
}}<br />
<br />
{{Note|This service will wait for the console port to be released, which means that the VM has been shutdown, to graciously end.}}<br />
<br />
Then create per-VM configuration files, named {{ic|/etc/conf.d/qemu.d/''vm_name''}}, with the variables {{ic|args}} and {{ic|haltcmd}} set. Example configs:<br />
<br />
{{hc|/etc/conf.d/qemu.d/one|2=<br />
args="-hda /dev/vg0/vm1 -serial telnet:localhost:7000,server,nowait,nodelay \<br />
-monitor telnet:localhost:7100,server,nowait,nodelay -vnc :0"<br />
<br />
haltcmd="echo 'system_powerdown' {{!}} nc localhost 7100" # or netcat/ncat}}<br />
<br />
{{hc|/etc/conf.d/qemu.d/two|2=<br />
args="-hda /srv/kvm/vm2 -serial telnet:localhost:7001,server,nowait,nodelay -vnc :1"<br />
<br />
haltcmd="ssh powermanager@vm2 sudo poweroff"}}<br />
<br />
The description of the variables is the following:<br />
<br />
* {{ic|args}} - QEMU command line arguments to be used.<br />
* {{ic|haltcmd}} - Command to shut down a VM safely. In the first example, the QEMU monitor is exposed via telnet using {{ic|-monitor telnet:..}} and the VMs are powered off via ACPI by sending {{ic|system_powerdown}} to monitor with the {{ic|nc}} command. In the other example, SSH is used.<br />
<br />
To set which virtual machines will start on boot-up, [[enable]] the {{ic|qemu@''vm_name''.service}} systemd unit.<br />
<br />
=== Mouse integration ===<br />
<br />
To prevent the mouse from being grabbed when clicking on the guest operating system's window, add the options {{ic|-usb -device usb-tablet}}. This means QEMU is able to report the mouse position without having to grab the mouse. This also overrides PS/2 mouse emulation when activated. For example:<br />
<br />
$ qemu-system-x86_64 -hda ''disk_image'' -m 512 -usb -device usb-tablet<br />
<br />
If that does not work, try using {{ic|-vga qxl}} parameter, also look at the instructions [[#Mouse cursor is jittery or erratic]].<br />
<br />
=== Pass-through host USB device ===<br />
<br />
It is possible to access the physical device connected to a USB port of the host from the guest. The first step is to identify where the device is connected, this can be found running the {{ic|lsusb}} command. For example:<br />
<br />
{{hc|$ lsusb|<br />
...<br />
Bus '''003''' Device '''007''': ID '''0781''':'''5406''' SanDisk Corp. Cruzer Micro U3<br />
}}<br />
<br />
The outputs in bold above will be useful to identify respectively the ''host_bus'' and ''host_addr'' or the ''vendor_id'' and ''product_id''.<br />
<br />
In qemu, the idea is to emulate an EHCI (USB 2) or XHCI (USB 3) controller with the option {{ic|1=-device usb-ehci,id=ehci}} or {{ic|1=-device qemu-xhci,id=xhci}} respectively and then attach the physical device to it with the option {{ic|1=-device usb-host,..}}. We will consider that ''controller_id'' is either {{ic|ehci}} or {{ic|xhci}} for the rest of this section.<br />
<br />
Then, there are two ways to connect to the USB of the host with qemu:<br />
<br />
# Identify the device and connect to it on any bus and address it is attached to on the host, the generic syntax is: {{bc|1=-device usb-host,bus=''controller_id''.0,vendorid=0x''vendor_id'',productid=0x''product_id''}}Applied to the device used in the example above, it becomes:{{bc|1=-device usb-ehci,id=ehci -device usb-host,bus=ehci.0,vendorid=0x'''0781''',productid=0x'''5406'''}}One can also add the {{ic|1=...,port=''port_number''}} setting to the previous option to specify in which physical port of the virtual controller the device should be attached, useful in the case one wants to add multiple usb devices to the VM.<br />
# Starting from QEMU 5.1.0, the {{ic|usb-host}} {{ic|hostdevice}} property can also be used: {{bc|1=-device qemu-xhci,id=xhci -device usb-host,bus=xhci.0,hostdevice=/dev/bus/usb/003/007}}<br />
# Attach whatever is connected to a given USB bus and address, the syntax is:{{bc|1=-device usb-host,bus=''controller_id''.0,hostbus=''host_bus'',host_addr=''host_addr''}}Applied to the bus and the address in the example above, it becomes:{{bc|1=-device usb-ehci,id=ehci -device usb-host,bus=ehci.0,hostbus='''3''',hostaddr='''7'''}}<br />
<br />
{{Note|If you encounter permission errors when running QEMU, see [[udev#About udev rules]] for information on how to set permissions of the device.}}<br />
<br />
=== USB redirection with SPICE ===<br />
<br />
When using [[#SPICE]] it is possible to redirect USB devices from the client to the virtual machine without needing to specify them in the QEMU command. It is possible to configure the number of USB slots available for redirected devices (the number of slots will determine the maximum number of devices which can be redirected simultaneously). The main advantages of using SPICE for redirection compared to the previously-mentioned {{ic|-usbdevice}} method is the possibility of hot-swapping USB devices after the virtual machine has started, without needing to halt it in order to remove USB devices from the redirection or adding new ones. This method of USB redirection also allows us to redirect USB devices over the network, from the client to the server. In summary, it is the most flexible method of using USB devices in a QEMU virtual machine.<br />
<br />
We need to add one EHCI/UHCI controller per available USB redirection slot desired as well as one SPICE redirection channel per slot. For example, adding the following arguments to the QEMU command you use for starting the virtual machine in SPICE mode will start the virtual machine with three available USB slots for redirection:<br />
<br />
{{bc|1=-device ich9-usb-ehci1,id=usb \<br />
-device ich9-usb-uhci1,masterbus=usb.0,firstport=0,multifunction=on \<br />
-device ich9-usb-uhci2,masterbus=usb.0,firstport=2 \<br />
-device ich9-usb-uhci3,masterbus=usb.0,firstport=4 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev1 -device usb-redir,chardev=usbredirchardev1,id=usbredirdev1 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev2 -device usb-redir,chardev=usbredirchardev2,id=usbredirdev2 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev3 -device usb-redir,chardev=usbredirchardev3,id=usbredirdev3}}<br />
See [https://www.spice-space.org/usbredir.html SPICE/usbredir] for more information.<br />
<br />
Both {{ic|spicy}} from {{Pkg|spice-gtk}} (''Input > Select USB Devices for redirection'') and {{ic|remote-viewer}} from {{pkg|virt-viewer}} (''File > USB device selection'') support this feature. Please make sure that you have installed the necessary SPICE Guest Tools on the virtual machine for this functionality to work as expected (see the [[#SPICE]] section for more information).<br />
<br />
{{Warning|Keep in mind that when a USB device is redirected from the client, it will not be usable from the client operating system itself until the redirection is stopped. It is specially important to never redirect the input devices (namely mouse and keyboard), since it will be then difficult to access the SPICE client menus to revert the situation, because the client will not respond to the input devices after being redirected to the virtual machine.}}<br />
<br />
=== Enabling KSM ===<br />
<br />
Kernel Samepage Merging (KSM) is a feature of the Linux kernel that allows for an application to register with the kernel to have its pages merged with other processes that also register to have their pages merged. The KSM mechanism allows for guest virtual machines to share pages with each other. In an environment where many of the guest operating systems are similar, this can result in significant memory savings.<br />
<br />
{{Note|Although KSM may reduce memory usage, it may increase CPU usage. Also note some security issues may occur, see [[Wikipedia:Kernel same-page merging]].}}<br />
<br />
To enable KSM:<br />
<br />
# echo 1 > /sys/kernel/mm/ksm/run<br />
<br />
To make it permanent, use [[systemd#systemd-tmpfiles - temporary files|systemd's temporary files]]:<br />
<br />
{{hc|/etc/tmpfiles.d/ksm.conf|<br />
w /sys/kernel/mm/ksm/run - - - - 1<br />
}}<br />
<br />
If KSM is running, and there are pages to be merged (i.e. at least two similar VMs are running), then {{ic|/sys/kernel/mm/ksm/pages_shared}} should be non-zero. See https://www.kernel.org/doc/html/latest/admin-guide/mm/ksm.html for more information.<br />
<br />
{{Tip|An easy way to see how well KSM is performing is to simply print the contents of all the files in that directory: {{bc|$ grep . /sys/kernel/mm/ksm/*}}}}<br />
<br />
=== Multi-monitor support ===<br />
<br />
The Linux QXL driver supports four heads (virtual screens) by default. This can be changed via the {{ic|1=qxl.heads=N}} kernel parameter.<br />
<br />
The default VGA memory size for QXL devices is 16M (VRAM size is 64M). This is not sufficient if you would like to enable two 1920x1200 monitors since that requires 2 × 1920 × 4 (color depth) × 1200 = 17.6 MiB VGA memory. This can be changed by replacing {{ic|-vga qxl}} by {{ic|<nowiki>-vga none -device qxl-vga,vgamem_mb=32</nowiki>}}. If you ever increase vgamem_mb beyond 64M, then you also have to increase the {{ic|vram_size_mb}} option.<br />
<br />
=== Copy and paste ===<br />
<br />
One way to share the clipboard between the host and the guest is to enable the SPICE remote desktop protocol and access the client with a SPICE client.<br />
One needs to follow the steps described in [[#SPICE]]. A guest run this way will support copy paste with the host.<br />
<br />
=== Windows-specific notes ===<br />
<br />
QEMU can run any version of Windows from Windows 95 through Windows 10.<br />
<br />
It is possible to run [[Windows PE]] in QEMU.<br />
<br />
==== Fast startup ====<br />
<br />
{{Note|An administrator account is required to change power settings.}}<br />
<br />
For Windows 8 (or later) guests it is better to disable "Turn on fast startup (recommended)" from the Power Options of the Control Panel as explained in the following [https://www.tenforums.com/tutorials/4189-turn-off-fast-startup-windows-10-a.html forum page], as it causes the guest to hang during every other boot.<br />
<br />
Fast Startup may also need to be disabled for changes to the {{ic|-smp}} option to be properly applied.<br />
<br />
==== Remote Desktop Protocol ====<br />
<br />
If you use a MS Windows guest, you might want to use RDP to connect to your guest VM. If you are using a VLAN or are not in the same network as the guest, use:<br />
<br />
$ qemu-system-x86_64 -nographic -net user,hostfwd=tcp::5555-:3389<br />
<br />
Then connect with either {{Pkg|rdesktop}} or {{Pkg|freerdp}} to the guest. For example:<br />
<br />
$ xfreerdp -g 2048x1152 localhost:5555 -z -x lan<br />
<br />
=== Clone Linux system installed on physical equipment ===<br />
<br />
Linux system installed on physical equipment can be cloned for running on QEMU vm. See [https://coffeebirthday.wordpress.com/2018/09/14/clone-linux-system-for-qemu-virtual-machine/ Clone Linux system from hardware for QEMU virtual machine]<br />
<br />
=== Chrooting into arm/arm64 environment from x86_64 ===<br />
<br />
Sometimes it is easier to work directly on a disk image instead of the real ARM based device. This can be achieved by mounting an SD card/storage containing the ''root'' partition and chrooting into it.<br />
<br />
Another use case for an ARM chroot is building ARM packages on an x86_64 machine - {{AUR|armutils-git}} can be used for that. Here, the chroot environment can be created from an image tarball from [https://archlinuxarm.org Arch Linux ARM] - see [https://nerdstuff.org/posts/2020/2020-003_simplest_way_to_create_an_arm_chroot/] for a detailed description of this approach.<br />
<br />
Either way, from the chroot it should be possible to run ''pacman'' and install more packages, compile large libraries etc. Since the executables are for the ARM architecture, the translation to x86 needs to be performed by [[QEMU]].<br />
<br />
Install {{AUR|binfmt-qemu-static}} and {{AUR|qemu-user-static}} from the [[AUR]] on the x86_64 machine/host. ''binfmt-qemu-static'' will take care of registering the qemu binaries to binfmt service.<br />
<br />
[[Restart]] {{ic|systemd-binfmt.service}}<br />
<br />
{{AUR|qemu-user-static}} is needed to allow the execution of compiled programs from other architectures. This is similar to what is provided by {{Pkg|qemu-arch-extra}}, but the "static" variant is required for chroot. Examples:<br />
<br />
qemu-arm-static path_to_sdcard/usr/bin/ls<br />
qemu-aarch64-static path_to_sdcard/usr/bin/ls<br />
<br />
These two lines execute the {{ic|ls}} command compiled for 32-bit ARM and 64-bit ARM respectively. Note that this will not work without chrooting, because it will look for libraries not present in the host system.<br />
<br />
{{AUR|qemu-user-static}} allows automatically prefixing the ARM exectuable with {{ic|qemu-arm-static}} or {{ic|qemu-aarch64-static}}.<br />
<br />
Make sure that the ARM executable support is active:<br />
<br />
{{hc|$ ls /proc/sys/fs/binfmt_misc|<br />
qemu-aarch64 qemu-arm qemu-cris qemu-microblaze qemu-mipsel qemu-ppc64 qemu-riscv64 qemu-sh4 qemu-sparc qemu-sparc64 status<br />
qemu-alpha qemu-armeb qemu-m68k qemu-mips qemu-ppc qemu-ppc64abi32 qemu-s390x qemu-sh4eb qemu-sparc32plus register<br />
}}<br />
<br />
Each executable must be listed.<br />
<br />
If it is not active, reinstall ''binfmt-qemu-static'' and restart ''systemd-binfmt''.<br />
<br />
Mount the SD card to {{ic|/mnt/scdard}} (the device name may be different).<br />
<br />
# mkdir -p /mnt/sdcard<br />
# mount /dev/mmcblk0p2 /mnt/sdcard<br />
<br />
Mount boot partition if needed (again, use the suitable device name):<br />
<br />
# mount /dev/mmcblk0p1 /mnt/sdcard/boot<br />
<br />
Finally ''chroot'' into the SD card root as described in [[Change root#Using chroot]]:<br />
<br />
# chroot /mnt/sdcard /bin/bash<br />
<br />
Alternatively, you can use ''arch-chroot'' from {{Pkg|arch-install-scripts}}, as it will provide an easier way to get network support:<br />
# arch-chroot /mnt/sdcard /bin/bash<br />
<br />
You can also use ''systemd-nspawn'' to chroot into the ARM environment:<br />
# systemd-nspawn -D /mnt/sdcard -M myARMMachine --bind-ro=/etc/resolv.conf<br />
<br />
{{ic|1=--bind-ro=/etc/resolv.conf}} is optional and gives a working network DNS inside the chroot<br />
<br />
== Troubleshooting ==<br />
<br />
=== Mouse cursor is jittery or erratic ===<br />
<br />
If the cursor jumps around the screen uncontrollably, entering this on the terminal before starting QEMU might help:<br />
<br />
$ export SDL_VIDEO_X11_DGAMOUSE=0<br />
<br />
If this helps, you can add this to your {{ic|~/.bashrc}} file.<br />
<br />
=== No visible Cursor ===<br />
<br />
Add {{ic|-show-cursor}} to QEMU's options to see a mouse cursor.<br />
<br />
If that still does not work, make sure you have set your display device appropriately, for example: {{ic|-vga qxl}}.<br />
<br />
Another option to try is {{ic|-usb -device usb-tablet}} as mentioned in [[#Mouse integration]]. This overrides the default PS/2 mouse emulation and synchronizes pointer location between host and guest as an added bonus.<br />
<br />
=== Two different mouse cursors are visible ===<br />
<br />
Apply the tip [[#Mouse integration]].<br />
<br />
=== Keyboard issues when using VNC ===<br />
<br />
When using VNC, you might experience keyboard problems described (in gory details) [https://www.berrange.com/posts/2010/07/04/more-than-you-or-i-ever-wanted-to-know-about-virtual-keyboard-handling/ here]. The solution is ''not'' to use the {{ic|-k}} option on QEMU, and to use {{ic|gvncviewer}} from {{Pkg|gtk-vnc}}. See also [http://www.mail-archive.com/libvir-list@redhat.com/msg13340.html this] message posted on libvirt's mailing list.<br />
<br />
=== Keyboard seems broken or the arrow keys do not work ===<br />
<br />
Should you find that some of your keys do not work or "press" the wrong key (in particular, the arrow keys), you likely need to specify your keyboard layout as an option. The keyboard layouts can be found in {{ic|/usr/share/qemu/keymaps}}.<br />
<br />
$ qemu-system-x86_64 -k ''keymap'' ''disk_image''<br />
<br />
=== Guest display stretches on window resize ===<br />
<br />
To restore default window size, press {{ic|Ctrl+Alt+u}}.<br />
<br />
=== ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy ===<br />
<br />
If an error message like this is printed when starting QEMU with {{ic|-enable-kvm}} option:<br />
<br />
ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy<br />
failed to initialize KVM: Device or resource busy<br />
<br />
that means another [[hypervisor]] is currently running. It is not recommended or possible to run several hypervisors in parallel.<br />
<br />
=== libgfapi error message ===<br />
<br />
The error message displayed at startup:<br />
<br />
Failed to open module: libgfapi.so.0: cannot open shared object file: No such file or directory<br />
<br />
[[Install]] {{pkg|glusterfs}} or ignore the error message as GlusterFS is a optional dependency.<br />
<br />
=== Kernel panic on LIVE-environments===<br />
<br />
If you start a live-environment (or better: booting a system) you may encounter this:<br />
<br />
[ end Kernel panic - not syncing: VFS: Unable to mount root fs on unknown block(0,0)<br />
<br />
or some other boot hindering process (e.g. cannot unpack initramfs, cant start service foo).<br />
Try starting the VM with the {{ic|-m VALUE}} switch and an appropriate amount of RAM, if the ram is to low you will probably encounter similar issues as above/without the memory-switch.<br />
<br />
=== Windows 7 guest suffers low-quality sound ===<br />
<br />
Using the {{ic|hda}} audio driver for Windows 7 guest may result in low-quality sound. Changing the audio driver to {{ic|ac97}} by passing the {{ic|-soundhw ac97}} arguments to QEMU and installing the AC97 driver from [https://www.realtek.com/en/component/zoo/category/pc-audio-codecs-ac-97-audio-codecs-software Realtek AC'97 Audio Codecs] in the guest may solve the problem. See [https://bugzilla.redhat.com/show_bug.cgi?id=1176761#c16 Red Hat Bugzilla – Bug 1176761] for more information.<br />
<br />
=== Could not access KVM kernel module: Permission denied ===<br />
<br />
If you encounter the following error:<br />
<br />
libvirtError: internal error: process exited while connecting to monitor: Could not access KVM kernel module: Permission denied failed to initialize KVM: Permission denied<br />
<br />
Systemd 234 assigns a dynamic ID for the {{ic|kvm}} group (see {{Bug|54943}}). To avoid this error, you need edit the file {{ic|/etc/libvirt/qemu.conf}} and change the line with {{ic|1=group = "78"}} to {{ic|1=group = "kvm"}}.<br />
<br />
=== "System Thread Exception Not Handled" when booting a Windows VM ===<br />
<br />
Windows 8 or Windows 10 guests may raise a generic compatibility exception at boot, namely "System Thread Exception Not Handled", which tends to be caused by legacy drivers acting strangely on real machines. On KVM machines this issue can generally be solved by setting the CPU model to {{ic|core2duo}}.<br />
<br />
=== Certain Windows games/applications crashing/causing a bluescreen ===<br />
<br />
Occasionally, applications running in the VM may crash unexpectedly, whereas they would run normally on a physical machine. If, while running {{ic|dmesg -wH}}, you encounter an error mentioning {{ic|MSR}}, the reason for those crashes is that KVM injects a [[wikipedia:General protection fault|General protection fault]] (GPF) when the guest tries to access unsupported [[wikipedia:Model-specific register|Model-specific registers]] (MSRs) - this often results in guest applications/OS crashing. A number of those issues can be solved by passing the {{ic|1=ignore_msrs=1}} option to the KVM module, which will ignore unimplemented MSRs.<br />
<br />
{{hc|/etc/modprobe.d/kvm.conf|2=<br />
...<br />
options kvm ignore_msrs=1<br />
...<br />
}}<br />
<br />
Cases where adding this option might help:<br />
<br />
* GeForce Experience complaining about an unsupported CPU being present.<br />
* StarCraft 2 and L.A. Noire reliably blue-screening Windows 10 with {{ic|KMODE_EXCEPTION_NOT_HANDLED}}. The blue screen information does not identify a driver file in these cases.<br />
<br />
{{Warning|While this is normally safe and some applications might not work without this, silently ignoring unknown MSR accesses could potentially break other software within the VM or other VMs.}}<br />
<br />
=== Applications in the VM experience long delays or take a long time to start ===<br />
<br />
This may be caused by insufficient available entropy in the VM. Consider allowing the guest to access the hosts's entropy pool by adding a [https://wiki.qemu.org/Features/VirtIORNG VirtIO RNG device] to the VM, or by installing an entropy generating daemon such as [[Haveged]].<br />
<br />
Anecdotally, OpenSSH takes a while to start accepting connections under insufficient entropy, without the logs revealing why.<br />
<br />
=== High interrupt latency and microstuttering ===<br />
<br />
This problem manifests itself as small pauses (stutters) and is particularly noticeable in graphics-intensive applications, such as games.<br />
<br />
* One of the causes is CPU power saving features, which are controlled by [[CPU frequency scaling]]. Change this to {{ic|performance}} for all processor cores. <br />
* Another possible cause is PS/2 inputs. Switch from PS/2 to Virtio inputs, see [[PCI passthrough via OVMF#Passing keyboard/mouse via Evdev]].<br />
<br />
=== QXL video causes low resolution ===<br />
<br />
QEMU 4.1.0 introduced a regression where QXL video can fall back to low resolutions, when being displayed through spice. [https://bugs.launchpad.net/qemu/+bug/1843151] For example, when KMS starts, text resolution may become as low as 4x10 characters. When trying to increase GUI resolution, it may go to the lowest supported resolution.<br />
<br />
As a workaround, create your device in this form:<br />
<br />
-device qxl-vga,max_outputs=1...<br />
<br />
=== Hang during VM initramfs ===<br />
<br />
Linux 5.2.11 introduced a KVM regression where under some circumstances a VM may permanently hang during the early boot phase, when the initramfs is being loaded or ran. [https://www.spinics.net/lists/kvm/msg195171.html] Linux 5.3 fixed the regression. The host shows qemu using 100% CPU * number of virtual CPUs. Reported case is with a host using hyperthreading, and a VM being given more than host's {{ic|nproc}}/2 virtual CPUs. It is unknown what exact circumstances trigger one of the threads to delete a memory region to cause this. The workarounds are:<br />
<br />
* Upgrade to Linux 5.3.<br />
* Downgrade to Linux 5.2.10<br />
* Until fixed, try giving the VM no more than the host's {{ic|nproc}}/2 virtual CPUs<br />
* Custom compile linux, reverting commit 2ad350fb4c (note this re-introduces a regression triggered when removing a memslot)<br />
<br />
=== VM does not boot when using a Secure Boot enabled OVMF ===<br />
<br />
{{ic|/usr/share/edk2-ovmf/x64/OVMF_CODE.secboot.fd}} from {{Pkg|edk2-ovmf}} is built with [[Wikipedia:System Management Mode|SMM]] support. If S3 support is not disabled in the VM, then the VM might not boot at all.<br />
<br />
Add the {{ic|1=-global ICH9-LPC.disable_s3=1}} option to the ''qemu'' command.<br />
<br />
See {{Bug|59465}} and https://github.com/tianocore/edk2/blob/master/OvmfPkg/README for more details and the required options to use Secure Boot in QEMU.<br />
<br />
=== Guest CPU interrupts are not firing ===<br />
<br />
If you are writing your own operating system by following the [https://wiki.osdev.org/ OSDev wiki], or are simply getting stepping through the guest architecture assembly code using QEMU's {{ic|gdb}} interface using the {{ic|-s}} flag, it's useful to know that many emulators, QEMU included, usually implement some CPU interrupts leaving many hardware interrupts unimplemented. One way to know if your code if firing an interrupt, is by using:<br />
<br />
-d int<br />
<br />
to enable showing interrupts/exceptions on stdout.<br />
<br />
To see what other guest debugging features QEMU has to offer, see:<br />
<br />
qemu-system-x86_64 -d help<br />
<br />
or replace {{ic|x86_64}} for your chosen guest architecture.<br />
<br />
== See also ==<br />
<br />
* [http://qemu.org Official QEMU website]<br />
* [http://www.linux-kvm.org Official KVM website]<br />
* [http://qemu.weilnetz.de/qemu-doc.html QEMU Emulator User Documentation]<br />
* [[Wikibooks:QEMU|QEMU Wikibook]]<br />
* [http://alien.slackbook.org/dokuwiki/doku.php?id=slackware:qemu Hardware virtualization with QEMU] by AlienBOB (last updated in 2008)<br />
* [http://blog.falconindy.com/articles/build-a-virtual-army.html Building a Virtual Army] by Falconindy<br />
* [http://git.qemu.org/?p=qemu.git;a=tree;f=docs Lastest docs]<br />
* [http://qemu.weilnetz.de/ QEMU on Windows]<br />
* [[wikipedia:Qemu|Wikipedia]]<br />
* [[debian:QEMU|Debian Wiki - QEMU]]<br />
* [https://people.gnome.org/~markmc/qemu-networking.html QEMU Networking on gnome.org]<br />
* [http://bsdwiki.reedmedia.net/wiki/networking_qemu_virtual_bsd_systems.html Networking QEMU Virtual BSD Systems]<br />
* [https://www.gnu.org/software/hurd/hurd/running/qemu.html QEMU on gnu.org]<br />
* [https://wiki.freebsd.org/qemu QEMU on FreeBSD as host]<br />
* [https://wiki.mikejung.biz/KVM_/_Xen KVM/QEMU Virtio Tuning and SSD VM Optimization Guide]<br />
* [https://doc.opensuse.org/documentation/leap/virtualization/html/book-virt/part-virt-qemu.html Managing Virtual Machines with QEMU - openSUSE documentation]<br />
* [https://www.ibm.com/support/knowledgecenter/en/linuxonibm/liaat/liaatkvm.htm KVM on IBM Knowledge Center]</div>Malcontenthttps://wiki.archlinux.org/index.php?title=QEMU&diff=634638QEMU2020-09-08T07:03:27Z<p>Malcontent: Use the same command example from the commit (e.g. /dev/bus/usb/$bus/$dev)</p>
<hr />
<div>[[Category:Emulation]]<br />
[[Category:Hypervisors]]<br />
[[de:Qemu]]<br />
[[es:QEMU]]<br />
[[fr:Qemu]]<br />
[[ja:QEMU]]<br />
[[zh-hans:QEMU]]<br />
[[zh-hant:QEMU]]<br />
{{Related articles start}}<br />
{{Related|:Category:Hypervisors}}<br />
{{Related|Libvirt}}<br />
{{Related|QEMU/Guest graphics acceleration}}<br />
{{Related|PCI passthrough via OVMF}}<br />
{{Related articles end}}<br />
<br />
According to the [http://wiki.qemu.org/Main_Page QEMU about page], "QEMU is a generic and open source machine emulator and virtualizer."<br />
<br />
When used as a machine emulator, QEMU can run OSes and programs made for one machine (e.g. an ARM board) on a different machine (e.g. your x86 PC). By using dynamic translation, it achieves very good performance.<br />
<br />
QEMU can use other hypervisors like [[Xen]] or [[KVM]] to use CPU extensions ([[Wikipedia:Hardware-assisted virtualization|HVM]]) for virtualization. When used as a virtualizer, QEMU achieves near native performances by executing the guest code directly on the host CPU.<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|qemu}} package (or {{Pkg|qemu-headless}} for the version without GUI) and below optional packages for your needs:<br />
<br />
* {{Pkg|qemu-arch-extra}} - extra architectures support<br />
* {{Pkg|qemu-block-gluster}} - [[Glusterfs]] block support<br />
* {{Pkg|qemu-block-iscsi}} - [[iSCSI]] block support<br />
* {{Pkg|qemu-block-rbd}} - RBD block support <br />
* {{Pkg|samba}} - [[Samba|SMB/CIFS]] server support<br />
<br />
Alternatively, {{AUR|qemu-user-static}} exists as a usermode and static variant.<br />
<br />
=== QEMU variants ===<br />
<br />
QEMU is offered in several variants suited for different use cases.<br />
<br />
As a first classification, QEMU is offered in full-system and usermode emulation modes:<br />
<br />
; Full-system emulation<br />
: In this mode, QEMU emulates a full system, including one or several processors and various peripherals. It is more accurate but slower, and does not require the emulated OS to be Linux.<br />
: QEMU commands for full-system emulation are named {{ic|qemu-system-''target_architecture''}}, e.g. {{ic|qemu-system-x86_64}} for emulating intel 64-bit CPUs, {{ic|qemu-system-i386}} for intel 32 bits CPUs, {{ic|qemu-system-arm}} for ARM (32 bits), {{ic|qemu-system-aarch64}} for ARM64, etc.<br />
: If the target architecture matches the host CPU, this mode may still benefit from a significant speedup by using a hypervisor like [[#Enabling KVM|KVM]] or Xen.<br />
; [https://www.qemu.org/docs/master/user/main.html Usermode emulation]: In this mode, QEMU is able to invoke a Linux executable compiled for a (potentially) different architecture by leveraging the host system resources. There may be compatibility issues, e.g. some features may not be implemented, dynamically linked executables will not work out of the box (see [[#Chrooting into arm/arm64 environment from x86_64|the section below]] to address this) and only Linux is supported (although [https://wiki.winehq.org/Emulation Wine may be used] for running Windows executables).<br />
: QEMU commands for usermode emulation are named {{ic|qemu-''target_architecture''}}, e.g. {{ic|qemu-x86_64}} for emulating intel 64-bit CPUs.<br />
<br />
QEMU is offered in dynamically-linked and statically-linked variants:<br />
<br />
; Dynamically-linked (default): {{ic|qemu-*}} commands depend on the host OS libraries, so executables are smaller.<br />
; Statically-linked: {{ic|qemu-*}} commands can be copied to any Linux system with the same architecture.<br />
<br />
In the case of Arch Linux, full-system emulation is offered as:<br />
<br />
; Non-headless (default): This variant enables GUI features that require additional dependencies (like SDL or GTK).<br />
; Headless: This is a slimmer variant that does not require GUI (this is suitable e.g. for servers).<br />
<br />
Note that headless and non-headless versions install commands with the same name (e.g. {{ic|qemu-system-x86_64}}) and thus cannot be both installed at the same time.<br />
<br />
=== Details on packages offered in Arch Linux ===<br />
<br />
* The {{Pkg|qemu}} package provides the {{ic|x86_64}} architecture emulators for full-system emulation ({{ic|qemu-system-x86_64}}). The {{Pkg|qemu-arch-extra}} package provides the {{ic|x86_64}} usermode variant ({{ic|qemu-x86_64}}) and also for the rest of supported architectures it includes both full-system and usermode variants (e.g. {{ic|qemu-system-arm}} and {{ic|qemu-arm}}).<br />
* The headless versions of these packages (only applicable to full-system emulation) are {{Pkg|qemu-headless}} ({{ic|x86_64}}-only) and {{Pkg|qemu-headless-arch-extra}} (rest of architectures).<br />
* Full-system emulation can be expanded with some QEMU modules present in separate packages: {{Pkg|qemu-block-gluster}}, {{Pkg|qemu-block-iscsi}}, {{Pkg|qemu-block-rbd}} and {{Pkg|qemu-guest-agent}}.<br />
* The unofficial AUR package {{AUR|qemu-user-static}} provides a usermode and static variant for all target architectures supported by QEMU. A precompiled version of this package exists: {{AUR|qemu-user-static-bin}}. The installed QEMU commands are named {{ic|qemu-''target_architecture''-static}}, for example, {{ic|qemu-x86_64-static}} for intel 64-bit CPUs.<br />
<br />
{{Note|At present, Arch does not offer a full-system mode and statically linked variant (neither officially nor via AUR), as this is usually not needed.}}<br />
<br />
== Graphical front-ends for QEMU ==<br />
<br />
Unlike other virtualization programs such as [[VirtualBox]] and [[VMware]], QEMU does not provide a GUI to manage virtual machines (other than the window that appears when running a virtual machine), nor does it provide a way to create persistent virtual machines with saved settings. All parameters to run a virtual machine must be specified on the command line at every launch, unless you have created a custom script to start your virtual machine(s).<br />
<br />
[[Libvirt]] provides a convenient way to manage QEMU virtual machines. See [[Libvirt#Client|list of libvirt clients]] for available front-ends.<br />
<br />
Other GUI front-ends for QEMU:<br />
<br />
* {{App|AQEMU|QEMU GUI written in Qt5.|https://github.com/tobimensch/aqemu|{{AUR|aqemu}}}}<br />
<br />
== Creating new virtualized system ==<br />
<br />
=== Creating a hard disk image ===<br />
<br />
{{Accuracy|If I get the man page right the raw format only allocates the full size if the filesystem does not support "holes" or it is <br />
explicitly told to preallocate. See man qemu-img in section Notes.}} <br />
<br />
{{Tip|See [[Wikibooks:QEMU/Images]] for more information on QEMU images.}}<br />
<br />
To run QEMU you will need a hard disk image, unless you are booting a live system from CD-ROM or the network (and not doing so to install an operating system to a hard disk image). A hard disk image is a file which stores the contents of the emulated hard disk.<br />
<br />
A hard disk image can be ''raw'', so that it is literally byte-by-byte the same as what the guest sees, and will always use the full capacity of the guest hard drive on the host. This method provides the least I/O overhead, but can waste a lot of space, as not-used space on the guest cannot be used on the host.<br />
<br />
Alternatively, the hard disk image can be in a format such as ''qcow2'' which only allocates space to the image file when the guest operating system actually writes to those sectors on its virtual hard disk. The image appears as the full size to the guest operating system, even though it may take up only a very small amount of space on the host system. This image format also supports QEMU snapshotting functionality (see [[#Creating and managing snapshots via the monitor console]] for details). However, using this format instead of ''raw'' will likely affect performance.<br />
<br />
QEMU provides the {{ic|qemu-img}} command to create hard disk images. For example to create a 4 GB image in the ''raw'' format:<br />
<br />
$ qemu-img create -f raw ''image_file'' 4G<br />
<br />
You may use {{ic|-f qcow2}} to create a ''qcow2'' disk instead.<br />
<br />
{{Note|You can also simply create a ''raw'' image by creating a file of the needed size using {{ic|dd}} or {{ic|fallocate}}.}}<br />
<br />
{{Warning|If you store the hard disk images on a [[Btrfs]] file system, you should consider disabling [[Btrfs#Copy-on-Write (CoW)|Copy-on-Write]] for the directory before creating any images.}}<br />
<br />
==== Overlay storage images ====<br />
<br />
You can create a storage image once (the 'backing' image) and have QEMU keep mutations to this image in an overlay image. This allows you to revert to a previous state of this storage image. You could revert by creating a new overlay image at the time you wish to revert, based on the original backing image.<br />
<br />
To create an overlay image, issue a command like:<br />
<br />
$ qemu-img create -o backing_file=''img1.raw'',backing_fmt=''raw'' -f ''qcow2'' ''img1.cow''<br />
<br />
After that you can run your QEMU VM as usual (see [[#Running virtualized system]]):<br />
<br />
$ qemu-system-x86_64 ''img1.cow''<br />
<br />
The backing image will then be left intact and mutations to this storage will be recorded in the overlay image file.<br />
<br />
When the path to the backing image changes, repair is required.<br />
<br />
{{Warning|The backing image's absolute filesystem path is stored in the (binary) overlay image file. Changing the backing image's path requires some effort.}}<br />
<br />
Make sure that the original backing image's path still leads to this image. If necessary, make a symbolic link at the original path to the new path. Then issue a command like:<br />
<br />
$ qemu-img rebase -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
At your discretion, you may alternatively perform an 'unsafe' rebase where the old path to the backing image is not checked:<br />
<br />
$ qemu-img rebase -u -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
==== Resizing an image ====<br />
<br />
{{Warning|Resizing an image containing an NTFS boot file system could make the operating system installed on it unbootable. It is recommended to create a backup first.}}<br />
<br />
The {{ic|qemu-img}} executable has the {{ic|resize}} option, which enables easy resizing of a hard drive image. It works for both ''raw'' and ''qcow2''. For example, to increase image space by 10 GB, run:<br />
<br />
$ qemu-img resize ''disk_image'' +10G<br />
<br />
After enlarging the disk image, you must use file system and partitioning tools inside the virtual machine to actually begin using the new space. When shrinking a disk image, you must '''first reduce the allocated file systems and partition sizes''' using the file system and partitioning tools inside the virtual machine and then shrink the disk image accordingly, otherwise shrinking the disk image will result in data loss! For a Windows guest, open the "create and format hard disk partitions" control panel.<br />
<br />
==== Converting an image ====<br />
<br />
You can convert an image to other formats using {{ic|qemu-img convert}}. This example shows how to convert a ''raw'' image to ''qcow2'':<br />
<br />
$ qemu-img convert -f raw -O qcow2 ''input''.img ''output''.qcow2<br />
<br />
This will not remove the original input file.<br />
<br />
=== Preparing the installation media ===<br />
<br />
To install an operating system into your disk image, you need the installation medium (e.g. optical disk, USB-drive, or ISO image) for the operating system. The installation medium should not be mounted because QEMU accesses the media directly.<br />
<br />
{{Tip|If using an optical disk, it is a good idea to first dump the media to a file because this both improves performance and does not require you to have direct access to the devices (that is, you can run QEMU as a regular user without having to change access permissions on the media's device file). For example, if the CD-ROM device node is named {{ic|/dev/cdrom}}, you can dump it to a file with the command: {{bc|1=$ dd if=/dev/cdrom of=''cd_image.iso'' bs=4k}}}}<br />
<br />
=== Installing the operating system ===<br />
<br />
This is the first time you will need to start the emulator. To install the operating system on the disk image, you must attach both the disk image and the installation media to the virtual machine, and have it boot from the installation media.<br />
<br />
For example on i386 guests, to install from a bootable ISO file as CD-ROM and a raw disk image:<br />
<br />
$ qemu-system-x86_64 -cdrom ''iso_image'' -boot order=d -drive file=''disk_image'',format=raw<br />
<br />
See {{man|1|qemu}} for more information about loading other media types (such as floppy, disk images or physical drives) and [[#Running virtualized system]] for other useful options.<br />
<br />
After the operating system has finished installing, the QEMU image can be booted directly (see [[#Running virtualized system]]).<br />
<br />
{{Note|By default only 128 MB of memory is assigned to the machine. The amount of memory can be adjusted with the {{ic|-m}} switch, for example {{ic|-m 512M}} or {{ic|-m 2G}}.}}<br />
<br />
{{Tip|<br />
* Instead of specifying {{ic|1=-boot order=x}}, some users may feel more comfortable using a boot menu: {{ic|1=-boot menu=on}}, at least during configuration and experimentation.<br />
* When running QEMU in headless mode, it starts a local VNC server on port 5900 per default. You can use [[TigerVNC]] to connect to the guest OS: {{ic|vncviewer :5900}}<br />
* If you need to replace floppies or CDs as part of the installation process, you can use the QEMU machine monitor (press {{ic|Ctrl+Alt+2}} in the virtual machine's window) to remove and attach storage devices to a virtual machine. Type {{ic|info block}} to see the block devices, and use the {{ic|change}} command to swap out a device. Press {{ic|Ctrl+Alt+1}} to go back to the virtual machine.<br />
}}<br />
<br />
== Running virtualized system ==<br />
<br />
{{ic|qemu-system-*}} binaries (for example {{ic|qemu-system-i386}} or {{ic|qemu-system-x86_64}}, depending on guest's architecture) are used to run the virtualized guest. The usage is:<br />
<br />
$ qemu-system-x86_64 ''options'' ''disk_image''<br />
<br />
Options are the same for all {{ic|qemu-system-*}} binaries, see {{man|1|qemu}} for documentation of all options.<br />
<br />
By default, QEMU will show the virtual machine's video output in a window. One thing to keep in mind: when you click inside the QEMU window, the mouse pointer is grabbed. To release it, press {{ic|Ctrl+Alt+g}}.<br />
<br />
{{Warning|QEMU should never be run as root. If you must launch it in a script as root, you should use the {{ic|-runas}} option to make QEMU drop root privileges.}}<br />
<br />
=== Enabling KVM ===<br />
<br />
KVM (''Kernel-based Virtual Machine'') full virtualization must be supported by your Linux kernel and your hardware, and necessary [[kernel modules]] must be loaded. See [[KVM]] for more information.<br />
<br />
To start QEMU in KVM mode, append {{ic|-enable-kvm}} to the additional start options. To check if KVM is enabled for a running VM, enter the [[#QEMU monitor]] and type {{ic|info kvm}}.<br />
<br />
{{Note|<br />
* The argument {{ic|1=accel=kvm}} of the {{ic|-machine}} option is equivalent to the {{ic|-enable-kvm}} or the {{ic|-accel kvm}} option.<br />
* CPU model {{ic|host}} requires KVM<br />
* If you start your VM with a GUI tool and experience very bad performance, you should check for proper KVM support, as QEMU may be falling back to software emulation.<br />
* KVM needs to be enabled in order to start Windows 7 and Windows 8 properly without a ''blue screen''.<br />
}}<br />
<br />
=== Enabling IOMMU (Intel VT-d/AMD-Vi) support ===<br />
<br />
First enable IOMMU, see [[PCI passthrough via OVMF#Setting up IOMMU]].<br />
<br />
Add {{ic|-device intel-iommu}} to create the IOMMU device:<br />
<br />
$ qemu-system-x86_64 '''-enable-kvm -machine q35 -device intel-iommu''' -cpu host ..<br />
<br />
{{Note|<br />
On Intel CPU based systems creating an IOMMU device in a QEMU guest with {{ic|-device intel-iommu}} will disable PCI passthrough with an error like: {{bc|Device at bus pcie.0 addr 09.0 requires iommu notifier which is currently not supported by intel-iommu emulation}} While adding the kernel parameter {{ic|1=intel_iommu=on}} is still needed for remapping IO (e.g. [[PCI passthrough via OVMF#Isolating the GPU|PCI passthrough with vfio-pci]]), {{ic|-device intel-iommu}} should not be set if PCI PCI passthrough is required.<br />
}}<br />
<br />
== Sharing data between host and guest ==<br />
<br />
=== Network ===<br />
<br />
Data can be shared between the host and guest OS using any network protocol that can transfer files, such as [[NFS]], [[SMB]], [[Wikipedia:Network block device|NBD]], HTTP, [[Very Secure FTP Daemon|FTP]], or [[SSH]], provided that you have set up the network appropriately and enabled the appropriate services.<br />
<br />
The default user-mode networking allows the guest to access the host OS at the IP address 10.0.2.2. Any servers that you are running on your host OS, such as a SSH server or SMB server, will be accessible at this IP address. So on the guests, you can mount directories exported on the host via [[SMB]] or [[NFS]], or you can access the host's HTTP server, etc.<br />
It will not be possible for the host OS to access servers running on the guest OS, but this can be done with other network configurations (see [[#Tap networking with QEMU]]).<br />
<br />
=== QEMU's port forwarding ===<br />
<br />
QEMU can forward ports from the host to the guest to enable e.g. connecting from the host to an SSH server running on the guest.<br />
<br />
For example, to bind port 10022 on the host with port 22 (SSH) on the guest, start QEMU with a command like:<br />
<br />
$ qemu-system-x86_64 ''disk_image'' -nic user,hostfwd=tcp::10022-:22<br />
<br />
Make sure the sshd is running on the guest and connect with:<br />
<br />
$ ssh ''guest-user''@localhost -p 10022<br />
<br />
You can use [[SSHFS]] to mount the guest's file system at the host for shared read and write access.<br />
<br />
=== QEMU's built-in SMB server ===<br />
<br />
QEMU's documentation says it has a "built-in" SMB server, but actually it just starts up [[Samba]] on the host with an automatically generated {{ic|smb.conf}} file located in {{ic|/tmp/qemu-smb.''random_string''}} and makes it accessible to the guest at a different IP address (10.0.2.4 by default). This only works for user networking, and is useful when you do not want to start the normal [[Samba]] service on the host, which the guest can also access if you have set up shares on it.<br />
<br />
Only a single directory can be set as shared with the option {{ic|1=smb=}}, but adding more directories (even while the virtual machine is running) could be as easy as creating symbolic links in the shared directory if QEMU configured SMB to follow symbolic links. It does not do so, but the configuration of the running SMB server can be changed as described below.<br />
<br />
''Samba'' must be installed on the host. To enable this feature, start QEMU with a command like:<br />
<br />
$ qemu-system-x86_64 ''disk_image'' -net nic -net user,smb=''shared_dir_path''<br />
<br />
where {{ic|''shared_dir_path''}} is a directory that you want to share between the guest and host.<br />
<br />
Then, in the guest, you will be able to access the shared directory on the host 10.0.2.4 with the share name "qemu". For example, in Windows Explorer you would go to {{ic|\\10.0.2.4\qemu}}.<br />
<br />
{{Note|<br />
* If you are using sharing options multiple times like {{ic|1=-net user,smb=''shared_dir_path1'' -net user,smb=''shared_dir_path2''}} or {{ic|1=-net user,smb=''shared_dir_path1'',smb=''shared_dir_path2''}} then it will share only the last defined one.<br />
* If you cannot access the shared folder and the guest system is Windows, check that the [http://ecross.mvps.org/howto/enable-netbios-over-tcp-ip-with-windows.htm NetBIOS protocol is enabled] and that a firewall does not block [https://technet.microsoft.com/en-us/library/cc940063.aspx ports] used by the NetBIOS protocol.<br />
* If you cannot access the shared folder and the guest system is Windows 10 Enterprise or Education or Windows Server 2016, [https://support.microsoft.com/en-us/help/4046019 enable guest access].<br />
}}<br />
<br />
One way to share multiple directories and to add or remove them while the virtual machine is running, is to share an empty directory and create/remove symbolic links to the directories in the shared directory. For this to work, the configuration of the running SMB server can be changed with the following script, which also allows the execution of files on the guest that are not set executable on the host:<br />
<br />
#!/bin/bash<br />
eval $(ps h -C smbd -o pid,args | grep /tmp/qemu-smb | gawk '{print "pid="$1";conf="$6}')<br />
echo "[global]<br />
allow insecure wide links = yes<br />
[qemu]<br />
follow symlinks = yes<br />
wide links = yes<br />
acl allow execute always = yes" >> $conf<br />
# in case the change is not detected automatically:<br />
smbcontrol --configfile=$conf $pid reload-config<br />
<br />
This can be applied to the running server started by qemu only after the guest has connected to the network drive the first time. An alternative to this method is to add additional shares to the configuration file like so:<br />
<br />
echo "[''myshare'']<br />
path=''another_path''<br />
read only=no<br />
guest ok=yes<br />
force user=''username''" >> $conf<br />
<br />
This share will be available on the guest as {{ic|\\10.0.2.4\''myshare''}}.<br />
<br />
=== Using filesystem passthrough and VirtFS ===<br />
<br />
See the [https://wiki.qemu.org/Documentation/9psetup QEMU documentation].<br />
<br />
=== Mounting a partition of the guest on the host ===<br />
<br />
It can be useful to mount a drive image under the host system, it can be a way to transfer files in and out of the guest. This should be done when the virtual machine is not running.<br />
<br />
The procedure to mount the drive on the host depends on the type of qemu image, ''raw'' or ''qcow2''. We detail thereafter the steps to mount a drive in the two formats in [[#Mounting a partition from a raw image]] and [[#Mounting a partition from a qcow2 image]]. For the full documentation see [[Wikibooks:QEMU/Images#Mounting an image on the host]].<br />
<br />
{{Warning|You must make sure to unmount the partitions before running the virtual machine again. Otherwise, data corruption is very likely to occur.}}<br />
<br />
==== Mounting a partition from a raw image ====<br />
<br />
It is possible to mount partitions that are inside a raw disk image file by setting them up as loopback devices.<br />
<br />
===== With manually specifying byte offset =====<br />
<br />
One way to mount a disk image partition is to mount the disk image at a certain offset using a command like the following:<br />
<br />
# mount -o loop,offset=32256 ''disk_image'' ''mountpoint''<br />
<br />
The {{ic|1=offset=32256}} option is actually passed to the {{ic|losetup}} program to set up a loopback device that starts at byte offset 32256 of the file and continues to the end. This loopback device is then mounted. You may also use the {{ic|sizelimit}} option to specify the exact size of the partition, but this is usually unnecessary.<br />
<br />
Depending on your disk image, the needed partition may not start at offset 32256. Run {{ic|fdisk -l ''disk_image''}} to see the partitions in the image. fdisk gives the start and end offsets in 512-byte sectors, so multiply by 512 to get the correct offset to pass to {{ic|mount}}.<br />
<br />
===== With loop module autodetecting partitions =====<br />
<br />
The Linux loop driver actually supports partitions in loopback devices, but it is disabled by default. To enable it, do the following:<br />
<br />
* Get rid of all your loopback devices (unmount all mounted images, etc.).<br />
* [[Kernel_modules#Manual_module_handling|Unload]] the {{ic|loop}} kernel module, and load it with the {{ic|1=max_part=15}} parameter set. Additionally, the maximum number of loop devices can be controlled with the {{ic|max_loop}} parameter.<br />
<br />
{{Tip|You can put an entry in {{ic|/etc/modprobe.d}} to load the loop module with {{ic|1=max_part=15}} every time, or you can put {{ic|1=loop.max_part=15}} on the kernel command-line, depending on whether you have the {{ic|loop.ko}} module built into your kernel or not.}}<br />
<br />
Set up your image as a loopback device:<br />
<br />
# losetup -f -P ''disk_image''<br />
<br />
Then, if the device created was {{ic|/dev/loop0}}, additional devices {{ic|/dev/loop0pX}} will have been automatically created, where X is the number of the partition. These partition loopback devices can be mounted directly. For example:<br />
<br />
# mount /dev/loop0p1 ''mountpoint''<br />
<br />
To mount the disk image with ''udisksctl'', see [[Udisks#Mount loop devices]].<br />
<br />
===== With kpartx =====<br />
<br />
'''kpartx''' from the {{Pkg|multipath-tools}} package can read a partition table on a device and create a new device for each partition. For example:<br />
<br />
# kpartx -a ''disk_image''<br />
<br />
This will setup the loopback device and create the necessary partition(s) device(s) in {{ic|/dev/mapper/}}.<br />
<br />
==== Mounting a partition from a qcow2 image ====<br />
<br />
We will use {{ic|qemu-nbd}}, which lets use the NBD (''network block device'') protocol to share the disk image.<br />
<br />
First, we need the ''nbd'' module loaded:<br />
<br />
# modprobe nbd max_part=16<br />
<br />
Then, we can share the disk and create the device entries:<br />
<br />
# qemu-nbd -c /dev/nbd0 ''/path/to/image.qcow2''<br />
<br />
Discover the partitions:<br />
<br />
# partprobe /dev/nbd0<br />
<br />
''fdisk'' can be used to get information regarding the different partitions in {{{ic|''nbd0''}}:<br />
<br />
{{hc|# fdisk -l /dev/nbd0|2=<br />
Disk /dev/nbd0: 25.2 GiB, 27074281472 bytes, 52879456 sectors<br />
Units: sectors of 1 * 512 = 512 bytes<br />
Sector size (logical/physical): 512 bytes / 512 bytes<br />
I/O size (minimum/optimal): 512 bytes / 512 bytes<br />
Disklabel type: dos<br />
Disk identifier: 0xa6a4d542<br />
<br />
Device Boot Start End Sectors Size Id Type<br />
/dev/nbd0p1 * 2048 1026047 1024000 500M 7 HPFS/NTFS/exFAT<br />
/dev/nbd0p2 1026048 52877311 51851264 24.7G 7 HPFS/NTFS/exFAT}}<br />
<br />
Then mount any partition of the drive image, for example the partition 2:<br />
<br />
# mount /dev/nbd0'''p2''' ''mountpoint''<br />
<br />
After the usage, it is important to unmount the image and reverse previous steps, i.e. unmount the partition and disconnect the nbd device:<br />
<br />
# umount ''mountpoint''<br />
# qemu-nbd -d /dev/nbd0<br />
<br />
=== Using any real partition as the single primary partition of a hard disk image ===<br />
<br />
Sometimes, you may wish to use one of your system partitions from within QEMU. Using a raw partition for a virtual machine will improve performance, as the read and write operations do not go through the file system layer on the physical host. Such a partition also provides a way to share data between the host and guest.<br />
<br />
In Arch Linux, device files for raw partitions are, by default, owned by ''root'' and the ''disk'' group. If you would like to have a non-root user be able to read and write to a raw partition, you must either change the owner of the partition's device file to that user, add that user to the ''disk'' group, or use [[ACL]] for more fine-grained access control.<br />
<br />
{{Warning|<br />
* Although it is possible, it is not recommended to allow virtual machines to alter critical data on the host system, such as the root partition.<br />
* You must not mount a file system on a partition read-write on both the host and the guest at the same time. Otherwise, data corruption will result.<br />
}}<br />
<br />
After doing so, you can attach the partition to a QEMU virtual machine as a virtual disk.<br />
<br />
However, things are a little more complicated if you want to have the ''entire'' virtual machine contained in a partition. In that case, there would be no disk image file to actually boot the virtual machine since you cannot install a bootloader to a partition that is itself formatted as a file system and not as a partitioned device with an MBR. Such a virtual machine can be booted either by specifying the [[kernel]] and [[initrd]] manually, or by simulating a disk with an MBR by using the [https://www.kernel.org/doc/html/latest/admin-guide/device-mapper/index.html Device-mapper], linear [[RAID]], or a [https://www.kernel.org/doc/html/latest/admin-guide/blockdev/nbd.html Linux Network Block Device].<br />
<br />
==== By specifying kernel and initrd manually ====<br />
<br />
QEMU supports loading [[Kernels|Linux kernels]] and [[initramfs|init ramdisks]] directly, thereby circumventing bootloaders such as [[GRUB]]. It then can be launched with the physical partition containing the root file system as the virtual disk, which will not appear to be partitioned. This is done by issuing a command similar to the following:<br />
<br />
{{Note|In this example, it is the '''host's''' images that are being used, not the guest's. If you wish to use the guest's images, either mount {{ic|/dev/sda3}} read-only (to protect the file system from the host) and specify the {{ic|/full/path/to/images}} or use some kexec hackery in the guest to reload the guest's kernel (extends boot time). }}<br />
<br />
$ qemu-system-x86_64 -kernel /boot/vmlinuz-linux -initrd /boot/initramfs-linux.img -append root=/dev/sda /dev/sda3<br />
<br />
In the above example, the physical partition being used for the guest's root file system is {{ic|/dev/sda3}} on the host, but it shows up as {{ic|/dev/sda}} on the guest.<br />
<br />
You may, of course, specify any kernel and initrd that you want, and not just the ones that come with Arch Linux.<br />
<br />
When there are multiple [[kernel parameters]] to be passed to the {{ic|-append}} option, they need to be quoted using single or double quotes. For example:<br />
<br />
... -append 'root=/dev/sda1 console=ttyS0'<br />
<br />
==== Simulate a virtual disk with MBR ====<br />
<br />
A more complicated way to have a virtual machine use a physical partition, while keeping that partition formatted as a file system and not just having the guest partition the partition as if it were a disk, is to simulate an MBR for it so that it can boot using a bootloader such as GRUB.<br />
<br />
For the following, suppose you have a plain, unmounted {{ic|/dev/hda''N''}} partition with some file system on it you wish to make part of a QEMU disk image. The trick is to dynamically prepend a master boot record (MBR) to the real partition you wish to embed in a QEMU raw disk image. More generally, the partition can be any part of a larger simulated disk, in particular a block device that simulates the original physical disk but only exposes {{ic|/dev/hda''N''}} to the virtual machine.<br />
<br />
A virtual disk of this type can be represented by a VMDK file that contains references to (a copy of) the MBR and the partition, but QEMU does not support this VMDK format. For instance, a virtual disk [https://www.virtualbox.org/manual/ch09.html#rawdisk created by]<br />
<br />
$ VBoxManage internalcommands createrawvmdk -filename ''/path/to/file.vmdk'' -rawdisk /dev/hda<br />
<br />
will be rejected by QEMU with the error message<br />
<br />
Unsupported image type 'partitionedDevice'<br />
<br />
Note that {{ic|VBoxManage}} creates two files, {{ic|''file.vmdk''}} and {{ic|''file-pt.vmdk''}}, the latter being a copy of the MBR, to which the text file {{ic|file.vmdk}} points. Read operations outside the target partition or the MBR would give zeros, while written data would be discarded.<br />
<br />
===== Device Mapper =====<br />
<br />
A method that is similar to the use of a VMDK descriptor file uses the device mapper to prepend a loop device attached to the MBR file to the target partition. In case we do not need our virtual disk to have the same size as the original, we first create a file to hold the MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=2048<br />
<br />
Here, a 1 MB (2048 * 512 bytes) file is created in accordance with partition alignment policies used by modern disk partitioning tools. For compatibility with older partitioning software, 63 sectors instead of 2048 might be required. The MBR only needs a single 512 bytes block, the additional free space can be used for a BIOS boot partition and, in the case of a hybrid partitioning scheme, for a GUID Partition Table. Then, we attach a loop device to the MBR file:<br />
<br />
# losetup --show -f ''/path/to/mbr''<br />
/dev/loop0<br />
<br />
In this example, the resulting device is {{ic|/dev/loop0}}. The device mapper is now used to join the MBR and the partition:<br />
<br />
# echo "0 2048 linear /dev/loop0 0<br />
2048 `blockdev --getsz /dev/hda''N''` linear /dev/hda''N'' 0" | dmsetup create qemu<br />
<br />
The resulting {{ic|/dev/mapper/qemu}} is what we will use as a QEMU raw disk image. Additional steps are required to create a partition table (see the section that describes the use of a linear RAID for an example) and boot loader code on the virtual disk (which will be stored in {{ic|''/path/to/mbr''}}).<br />
<br />
The following setup is an example where the position of {{ic|/dev/hda''N''}} on the virtual disk is to be the same as on the physical disk and the rest of the disk is hidden, except for the MBR, which is provided as a copy:<br />
<br />
# dd if=/dev/hda count=1 of=''/path/to/mbr''<br />
# loop=`losetup --show -f ''/path/to/mbr''`<br />
# start=`blockdev --report /dev/hda''N'' | tail -1 | awk '{print $5}'`<br />
# size=`blockdev --getsz /dev/hda''N''`<br />
# disksize=`blockdev --getsz /dev/hda`<br />
# echo "0 1 linear $loop 0<br />
1 $((start-1)) zero<br />
$start $size linear /dev/hda''N'' 0<br />
$((start+size)) $((disksize-start-size)) zero" | dmsetup create qemu<br />
<br />
The table provided as standard input to {{ic|dmsetup}} has a similar format as the table in a VDMK descriptor file produced by {{ic|VBoxManage}} and can alternatively be loaded from a file with {{ic|dmsetup create qemu --table ''table_file''}}. To the virtual machine, only {{ic|/dev/hda''N''}} is accessible, while the rest of the hard disk reads as zeros and discards written data, except for the first sector. We can print the table for {{ic|/dev/mapper/qemu}} with {{ic|dmsetup table qemu}} (use {{ic|udevadm info -rq name /sys/dev/block/''major'':''minor''}} to translate {{ic|''major'':''minor''}} to the corresponding {{ic|/dev/''blockdevice''}} name). Use {{ic|dmsetup remove qemu}} and {{ic|losetup -d $loop}} to delete the created devices.<br />
<br />
A situation where this example would be useful is an existing Windows XP installation in a multi-boot configuration and maybe a hybrid partitioning scheme (on the physical hardware, Windows XP could be the only operating system that uses the MBR partition table, while more modern operating systems installed on the same computer could use the GUID Partition Table). Windows XP supports hardware profiles, so that that the same installation can be used with different hardware configurations alternatingly (in this case bare metal vs. virtual) with Windows needing to install drivers for newly detected hardware only once for every profile. Note that in this example the boot loader code in the copied MBR needs to be updated to directly load Windows XP from {{ic|/dev/hda''N''}} instead of trying to start the multi-boot capable boot loader (like GRUB) present in the original system. Alternatively, a copy of the boot partition containing the boot loader installation can be included in the virtual disk the same way as the MBR.<br />
<br />
===== Linear RAID =====<br />
<br />
You can also do this using software [[RAID]] in linear mode (you need the {{ic|linear.ko}} kernel driver) and a loopback device: <br />
<br />
First, you create some small file to hold the MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=32<br />
<br />
Here, a 16 KB (32 * 512 bytes) file is created. It is important not to make it too small (even if the MBR only needs a single 512 bytes block), since the smaller it will be, the smaller the chunk size of the software RAID device will have to be, which could have an impact on performance. Then, you setup a loopback device to the MBR file:<br />
<br />
# losetup -f ''/path/to/mbr''<br />
<br />
Let us assume the resulting device is {{ic|/dev/loop0}}, because we would not already have been using other loopbacks. Next step is to create the "merged" MBR + {{ic|/dev/hda''N''}} disk image using software RAID:<br />
<br />
# modprobe linear<br />
# mdadm --build --verbose /dev/md0 --chunk=16 --level=linear --raid-devices=2 /dev/loop0 /dev/hda''N''<br />
<br />
The resulting {{ic|/dev/md0}} is what you will use as a QEMU raw disk image (do not forget to set the permissions so that the emulator can access it). The last (and somewhat tricky) step is to set the disk configuration (disk geometry and partitions table) so that the primary partition start point in the MBR matches the one of {{ic|/dev/hda''N''}} inside {{ic|/dev/md0}} (an offset of exactly 16 * 512 = 16384 bytes in this example). Do this using {{ic|fdisk}} on the host machine, not in the emulator: the default raw disc detection routine from QEMU often results in non-kilobyte-roundable offsets (such as 31.5 KB, as in the previous section) that cannot be managed by the software RAID code. Hence, from the the host:<br />
<br />
# fdisk /dev/md0<br />
<br />
Press {{ic|X}} to enter the expert menu. Set number of 's'ectors per track so that the size of one cylinder matches the size of your MBR file. For two heads and a sector size of 512, the number of sectors per track should be 16, so we get cylinders of size 2x16x512=16k.<br />
<br />
Now, press {{ic|R}} to return to the main menu.<br />
<br />
Press {{ic|P}} and check that the cylinder size is now 16k.<br />
<br />
Now, create a single primary partition corresponding to {{ic|/dev/hda''N''}}. It should start at cylinder 2 and end at the end of the disk (note that the number of cylinders now differs from what it was when you entered fdisk.<br />
<br />
Finally, 'w'rite the result to the file: you are done. You now have a partition you can mount directly from your host, as well as part of a QEMU disk image:<br />
<br />
$ qemu-system-x86_64 -hdc /dev/md0 ''[...]''<br />
<br />
You can, of course, safely set any bootloader on this disk image using QEMU, provided the original {{ic|/dev/hda''N''}} partition contains the necessary tools.<br />
<br />
===== Network Block Device =====<br />
<br />
Instead of the methods decribed above, you may use {{ic|nbd-server}} (from the {{pkg|nbd}} package) to create an MBR wrapper for QEMU.<br />
<br />
Assuming you have already set up your MBR wrapper file like above, rename it to {{ic|wrapper.img.0}}. Then create a symbolic link named {{ic|wrapper.img.1}} in the same directory, pointing to your partition. Then put the following script in the same directory:<br />
<br />
#!/bin/sh<br />
dir="$(realpath "$(dirname "$0")")"<br />
cat >wrapper.conf <<EOF<br />
[generic]<br />
allowlist = true<br />
listenaddr = 127.713705<br />
port = 10809<br />
<br />
[wrap]<br />
exportname = $dir/wrapper.img<br />
multifile = true<br />
EOF<br />
<br />
nbd-server \<br />
-C wrapper.conf \<br />
-p wrapper.pid \<br />
"$@"<br />
<br />
The {{ic|.0}} and {{ic|.1}} suffixes are essential; the rest can be changed. After running the above script (which you may need to do as root to make sure nbd-server is able to access the partition), you can launch QEMU with:<br />
<br />
qemu-system-x86_64 -drive file=nbd:127.713705:10809:exportname=wrap ''[...]''<br />
<br />
== Networking ==<br />
<br />
{{Style|Network topologies (sections [[#Host-only networking]], [[#Internal networking]] and info spread out across other sections) should not be described alongside the various virtual interfaces implementations, such as [[#User-mode networking]], [[#Tap networking with QEMU]], [[#Networking with VDE2]].}}<br />
<br />
The performance of virtual networking should be better with tap devices and bridges than with user-mode networking or vde because tap devices and bridges are implemented in-kernel.<br />
<br />
In addition, networking performance can be improved by assigning virtual machines a [http://wiki.libvirt.org/page/Virtio virtio] network device rather than the default emulation of an e1000 NIC. See [[#Installing virtio drivers]] for more information.<br />
<br />
=== Link-level address caveat ===<br />
<br />
By giving the {{ic|-net nic}} argument to QEMU, it will, by default, assign a virtual machine a network interface with the link-level address {{ic|52:54:00:12:34:56}}. However, when using bridged networking with multiple virtual machines, it is essential that each virtual machine has a unique link-level (MAC) address on the virtual machine side of the tap device. Otherwise, the bridge will not work correctly, because it will receive packets from multiple sources that have the same link-level address. This problem occurs even if the tap devices themselves have unique link-level addresses because the source link-level address is not rewritten as packets pass through the tap device.<br />
<br />
Make sure that each virtual machine has a unique link-level address, but it should always start with {{ic|52:54:}}. Use the following option, replace ''X'' with arbitrary hexadecimal digit:<br />
<br />
$ qemu-system-x86_64 -net nic,macaddr=52:54:''XX:XX:XX:XX'' -net vde ''disk_image''<br />
<br />
Generating unique link-level addresses can be done in several ways:<br />
<br />
* Manually specify unique link-level address for each NIC. The benefit is that the DHCP server will assign the same IP address each time the virtual machine is run, but it is unusable for large number of virtual machines.<br />
* Generate random link-level address each time the virtual machine is run. Practically zero probability of collisions, but the downside is that the DHCP server will assign a different IP address each time. You can use the following command in a script to generate random link-level address in a {{ic|macaddr}} variable:<br />
<br />
{{bc|1=<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
qemu-system-x86_64 -net nic,macaddr="$macaddr" -net vde ''disk_image''<br />
}}<br />
<br />
* Use the following script {{ic|qemu-mac-hasher.py}} to generate the link-level address from the virtual machine name using a hashing function. Given that the names of virtual machines are unique, this method combines the benefits of the aforementioned methods: it generates the same link-level address each time the script is run, yet it preserves the practically zero probability of collisions.<br />
<br />
{{hc|qemu-mac-hasher.py|<nowiki><br />
#!/usr/bin/env python<br />
<br />
import sys<br />
import zlib<br />
<br />
if len(sys.argv) != 2:<br />
print("usage: %s <VM Name>" % sys.argv[0])<br />
sys.exit(1)<br />
<br />
crc = zlib.crc32(sys.argv[1].encode("utf-8")) & 0xffffffff<br />
crc = str(hex(crc))[2:]<br />
print("52:54:%s%s:%s%s:%s%s:%s%s" % tuple(crc))<br />
</nowiki>}}<br />
<br />
In a script, you can use for example:<br />
<br />
vm_name="''VM Name''"<br />
qemu-system-x86_64 -name "$vm_name" -net nic,macaddr=$(qemu-mac-hasher.py "$vm_name") -net vde ''disk_image''<br />
<br />
=== User-mode networking ===<br />
<br />
By default, without any {{ic|-netdev}} arguments, QEMU will use user-mode networking with a built-in DHCP server. Your virtual machines will be assigned an IP address when they run their DHCP client, and they will be able to access the physical host's network through IP masquerading done by QEMU.<br />
<br />
{{warning|This only works with the TCP and UDP protocols, so ICMP, including {{ic|ping}}, will not work. Do not use {{ic|ping}} to test network connectivity. To make ping work in the guest see [[Sysctl#Allow unprivileged users to create IPPROTO_ICMP sockets]].}}<br />
<br />
This default configuration allows your virtual machines to easily access the Internet, provided that the host is connected to it, but the virtual machines will not be directly visible on the external network, nor will virtual machines be able to talk to each other if you start up more than one concurrently.<br />
<br />
QEMU's user-mode networking can offer more capabilities such as built-in TFTP or SMB servers, redirecting host ports to the guest (for example to allow SSH connections to the guest) or attaching guests to VLANs so that they can talk to each other. See the QEMU documentation on the {{ic|-net user}} flag for more details.<br />
<br />
However, user-mode networking has limitations in both utility and performance. More advanced network configurations require the use of tap devices or other methods.<br />
<br />
{{Note|If the host system uses [[systemd-networkd]], make sure to symlink the {{ic|/etc/resolv.conf}} file as described in [[systemd-networkd#Required services and setup]], otherwise the DNS lookup in the guest system will not work.}}<br />
<br />
=== Tap networking with QEMU ===<br />
<br />
[[wikipedia:TUN/TAP|Tap devices]] are a Linux kernel feature that allows you to create virtual network interfaces that appear as real network interfaces. Packets sent to a tap interface are delivered to a userspace program, such as QEMU, that has bound itself to the interface.<br />
<br />
QEMU can use tap networking for a virtual machine so that packets sent to the tap interface will be sent to the virtual machine and appear as coming from a network interface (usually an Ethernet interface) in the virtual machine. Conversely, everything that the virtual machine sends through its network interface will appear on the tap interface.<br />
<br />
Tap devices are supported by the Linux bridge drivers, so it is possible to bridge together tap devices with each other and possibly with other host interfaces such as {{ic|eth0}}. This is desirable if you want your virtual machines to be able to talk to each other, or if you want other machines on your LAN to be able to talk to the virtual machines.<br />
<br />
{{Warning|If you bridge together tap device and some host interface, such as {{ic|eth0}}, your virtual machines will appear directly on the external network, which will expose them to possible attack. Depending on what resources your virtual machines have access to, you may need to take all the [[Firewalls|precautions]] you normally would take in securing a computer to secure your virtual machines. If the risk is too great, virtual machines have little resources or you set up multiple virtual machines, a better solution might be to use [[#Host-only networking|host-only networking]] and set up NAT. In this case you only need one firewall on the host instead of multiple firewalls for each guest.}}<br />
<br />
As indicated in the user-mode networking section, tap devices offer higher networking performance than user-mode. If the guest OS supports virtio network driver, then the networking performance will be increased considerably as well. Supposing the use of the tap0 device, that the virtio driver is used on the guest, and that no scripts are used to help start/stop networking, next is part of the qemu command one should see:<br />
<br />
-device virtio-net,netdev=network0 -netdev tap,id=network0,ifname=tap0,script=no,downscript=no<br />
<br />
But if already using a tap device with virtio networking driver, one can even boost the networking performance by enabling vhost, like:<br />
<br />
-device virtio-net,netdev=network0 -netdev tap,id=network0,ifname=tap0,script=no,downscript=no,vhost=on<br />
<br />
See [https://web.archive.org/web/20160222161955/http://www.linux-kvm.com:80/content/how-maximize-virtio-net-performance-vhost-net] for more information.<br />
<br />
==== Host-only networking ====<br />
<br />
If the bridge is given an IP address and traffic destined for it is allowed, but no real interface (e.g. {{ic|eth0}}) is connected to the bridge, then the virtual machines will be able to talk to each other and the host system. However, they will not be able to talk to anything on the external network, provided that you do not set up IP masquerading on the physical host. This configuration is called ''host-only networking'' by other virtualization software such as [[VirtualBox]].<br />
<br />
{{Tip|<br />
* If you want to set up IP masquerading, e.g. NAT for virtual machines, see the [[Internet sharing#Enable NAT]] page.<br />
* See [[Network bridge]] for information on creating bridge.<br />
* You may want to have a DHCP server running on the bridge interface to service the virtual network. For example, to use the {{ic|172.20.0.1/16}} subnet with [[dnsmasq]] as the DHCP server:<br />
<br />
{{bc|1=<br />
# ip addr add 172.20.0.1/16 dev br0<br />
# ip link set br0 up<br />
# dnsmasq --interface=br0 --bind-interfaces --dhcp-range=172.20.0.2,172.20.255.254<br />
}}<br />
}}<br />
<br />
==== Internal networking ====<br />
<br />
If you do not give the bridge an IP address and add an [[iptables]] rule to drop all traffic to the bridge in the INPUT chain, then the virtual machines will be able to talk to each other, but not to the physical host or to the outside network. This configuration is called ''internal networking'' by other virtualization software such as [[VirtualBox]]. You will need to either assign static IP addresses to the virtual machines or run a DHCP server on one of them.<br />
<br />
By default iptables would drop packets in the bridge network. You may need to use such iptables rule to allow packets in a bridged network:<br />
<br />
# iptables -I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Bridged networking using qemu-bridge-helper ====<br />
<br />
{{Note|This method is available since QEMU 1.1, see http://wiki.qemu.org/Features/HelperNetworking.}}<br />
<br />
This method does not require a start-up script and readily accommodates multiple taps and multiple bridges. It uses {{ic|/usr/lib/qemu/qemu-bridge-helper}} binary, which allows creating tap devices on an existing bridge.<br />
<br />
{{Tip|See [[Network bridge]] for information on creating bridge.}}<br />
<br />
First, create a configuration file containing the names of all bridges to be used by QEMU:<br />
<br />
{{hc|/etc/qemu/bridge.conf|<br />
allow ''bridge0''<br />
allow ''bridge1''<br />
...}}<br />
<br />
Now start the VM. The most basic usage would be:<br />
<br />
$ qemu-system-x86_64 -net nic -net bridge,br=''bridge0'' ''[...]''<br />
<br />
With multiple taps, the most basic usage requires specifying the VLAN for all additional NICs:<br />
<br />
$ qemu-system-x86_64 -net nic -net bridge,br=''bridge0'' -net nic,vlan=1 -net bridge,vlan=1,br=''bridge1'' ''[...]''<br />
<br />
==== Creating bridge manually ====<br />
<br />
{{Style|This section needs serious cleanup and may contain out-of-date information.}}<br />
<br />
{{Tip|Since QEMU 1.1, the [http://wiki.qemu.org/Features/HelperNetworking network bridge helper] can set tun/tap up for you without the need for additional scripting. See [[#Bridged networking using qemu-bridge-helper]].}}<br />
<br />
The following describes how to bridge a virtual machine to a host interface such as {{ic|eth0}}, which is probably the most common configuration. This configuration makes it appear that the virtual machine is located directly on the external network, on the same Ethernet segment as the physical host machine.<br />
<br />
We will replace the normal Ethernet adapter with a bridge adapter and bind the normal Ethernet adapter to it.<br />
<br />
* Install {{Pkg|bridge-utils}}, which provides {{ic|brctl}} to manipulate bridges.<br />
<br />
* Enable IPv4 forwarding:<br />
# sysctl -w net.ipv4.ip_forward=1<br />
<br />
To make the change permanent, change {{ic|1=net.ipv4.ip_forward = 0}} to {{ic|1=net.ipv4.ip_forward = 1}} in {{ic|/etc/sysctl.d/99-sysctl.conf}}.<br />
<br />
* Load the {{ic|tun}} module and configure it to be loaded on boot. See [[Kernel modules]] for details.<br />
<br />
* Now create the bridge. See [[Bridge with netctl]] for details. Remember to name your bridge as {{ic|br0}}, or change the scripts below to your bridge's name.<br />
<br />
* Create the script that QEMU uses to bring up the tap adapter with {{ic|root:kvm}} 750 permissions:<br />
<br />
{{hc|/etc/qemu-ifup|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifup"<br />
echo "Bringing up $1 for bridged mode..."<br />
sudo /usr/bin/ip link set $1 up promisc on<br />
echo "Adding $1 to br0..."<br />
sudo /usr/bin/brctl addif br0 $1<br />
sleep 2<br />
</nowiki>}}<br />
<br />
* Create the script that QEMU uses to bring down the tap adapter in {{ic|/etc/qemu-ifdown}} with {{ic|root:kvm}} 750 permissions:<br />
{{hc|/etc/qemu-ifdown|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifdown"<br />
sudo /usr/bin/ip link set $1 down<br />
sudo /usr/bin/brctl delif br0 $1<br />
sudo /usr/bin/ip link delete dev $1<br />
</nowiki>}}<br />
<br />
* Use {{ic|visudo}} to add the following to your {{ic|sudoers}} file:<br />
<br />
{{bc|<nowiki><br />
Cmnd_Alias QEMU=/usr/bin/ip,/usr/bin/modprobe,/usr/bin/brctl<br />
%kvm ALL=NOPASSWD: QEMU<br />
</nowiki>}}<br />
<br />
* You launch QEMU using the following {{ic|run-qemu}} script:<br />
<br />
{{hc|run-qemu|<nowiki><br />
#!/bin/bash<br />
USERID=$(whoami)<br />
<br />
# Get name of newly created TAP device; see https://bbs.archlinux.org/viewtopic.php?pid=1285079#p1285079<br />
precreationg=$(/usr/bin/ip tuntap list | /usr/bin/cut -d: -f1 | /usr/bin/sort)<br />
sudo /usr/bin/ip tuntap add user $USERID mode tap<br />
postcreation=$(/usr/bin/ip tuntap list | /usr/bin/cut -d: -f1 | /usr/bin/sort)<br />
IFACE=$(comm -13 <(echo "$precreationg") <(echo "$postcreation"))<br />
<br />
# This line creates a random MAC address. The downside is the DHCP server will assign a different IP address each time<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
# Instead, uncomment and edit this line to set a static MAC address. The benefit is that the DHCP server will assign the same IP address.<br />
# macaddr='52:54:be:36:42:a9'<br />
<br />
qemu-system-x86_64 -net nic,macaddr=$macaddr -net tap,ifname="$IFACE" $*<br />
<br />
sudo ip link set dev $IFACE down &> /dev/null<br />
sudo ip tuntap del $IFACE mode tap &> /dev/null<br />
</nowiki>}}<br />
<br />
Then to launch a VM, do something like this<br />
<br />
$ run-qemu -hda ''myvm.img'' -m 512<br />
<br />
* It is recommended for performance and security reasons to disable the [http://ebtables.netfilter.org/documentation/bridge-nf.html firewall on the bridge]:<br />
<br />
{{hc|/etc/sysctl.d/10-disable-firewall-on-bridge.conf|<nowiki><br />
net.bridge.bridge-nf-call-ip6tables = 0<br />
net.bridge.bridge-nf-call-iptables = 0<br />
net.bridge.bridge-nf-call-arptables = 0<br />
</nowiki>}}<br />
<br />
Run {{ic|sysctl -p /etc/sysctl.d/10-disable-firewall-on-bridge.conf}} to apply the changes immediately.<br />
<br />
See the [http://wiki.libvirt.org/page/Networking#Creating_network_initscripts libvirt wiki] and [https://bugzilla.redhat.com/show_bug.cgi?id=512206 Fedora bug 512206]. If you get errors by sysctl during boot about non-existing files, make the {{ic|bridge}} module load at boot. See [[Kernel modules#Automatic module loading with systemd]].<br />
<br />
Alternatively, you can configure [[iptables]] to allow all traffic to be forwarded across the bridge by adding a rule like this:<br />
<br />
-I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Network sharing between physical device and a Tap device through iptables ====<br />
<br />
{{Merge|Internet_sharing|Duplication, not specific to QEMU.}}<br />
<br />
Bridged networking works fine between a wired interface (Eg. eth0), and it is easy to setup. However if the host gets connected to the network through a wireless device, then bridging is not possible.<br />
<br />
See [[Network bridge#Wireless interface on a bridge]] as a reference.<br />
<br />
One way to overcome that is to setup a tap device with a static IP, making linux automatically handle the routing for it, and then forward traffic between the tap interface and the device connected to the network through iptables rules.<br />
<br />
See [[Internet sharing]] as a reference.<br />
<br />
There you can find what is needed to share the network between devices, included tap and tun ones. The following just hints further on some of the host configurations required. As indicated in the reference above, the client needs to be configured for a static IP, using the IP assigned to the tap interface as the gateway. The caveat is that the DNS servers on the client might need to be manually edited if they change when changing from one host device connected to the network to another.<br />
<br />
To allow IP forwarding on every boot, one need to add the following lines to sysctl configuration file inside {{ic|/etc/sysctl.d}}:<br />
<br />
net.ipv4.ip_forward = 1<br />
net.ipv6.conf.default.forwarding = 1<br />
net.ipv6.conf.all.forwarding = 1<br />
<br />
The iptables rules can look like:<br />
<br />
# Forwarding from/to outside<br />
iptables -A FORWARD -i ${INT} -o ${EXT_0} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_1} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_2} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_0} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_1} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_2} -o ${INT} -j ACCEPT<br />
# NAT/Masquerade (network address translation)<br />
iptables -t nat -A POSTROUTING -o ${EXT_0} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_1} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_2} -j MASQUERADE<br />
<br />
The prior supposes there are 3 devices connected to the network sharing traffic with one internal device, where for example:<br />
<br />
INT=tap0<br />
EXT_0=eth0<br />
EXT_1=wlan0<br />
EXT_2=tun0<br />
<br />
The prior shows a forwarding that would allow sharing wired and wireless connections with the tap device.<br />
<br />
The forwarding rules shown are stateless, and for pure forwarding. One could think of restricting specific traffic, putting a firewall in place to protect the guest and others. However those would decrease the networking performance, while a simple bridge does not include any of that.<br />
<br />
Bonus: Whether the connection is wired or wireless, if one gets connected through VPN to a remote site with a tun device, supposing the tun device opened for that connection is tun0, and the prior iptables rules are applied, then the remote connection gets also shared with the guest. This avoids the need for the guest to also open a VPN connection. Again, as the guest networking needs to be static, then if connecting the host remotely this way, one most probably will need to edit the DNS servers on the guest.<br />
<br />
=== Networking with VDE2 ===<br />
<br />
{{Style|This section needs serious cleanup and may contain out-of-date information.}}<br />
<br />
==== What is VDE? ====<br />
<br />
VDE stands for Virtual Distributed Ethernet. It started as an enhancement of [[User-mode Linux|uml]]_switch. It is a toolbox to manage virtual networks.<br />
<br />
The idea is to create virtual switches, which are basically sockets, and to "plug" both physical and virtual machines in them. The configuration we show here is quite simple; However, VDE is much more powerful than this, it can plug virtual switches together, run them on different hosts and monitor the traffic in the switches. You are invited to read [https://wiki.virtualsquare.org/ the documentation of the project].<br />
<br />
The advantage of this method is you do not have to add sudo privileges to your users. Regular users should not be allowed to run modprobe.<br />
<br />
==== Basics ====<br />
<br />
VDE support can be [[pacman|installed]] via the {{Pkg|vde2}} package.<br />
<br />
In our config, we use tun/tap to create a virtual interface on my host. Load the {{ic|tun}} module (see [[Kernel modules]] for details):<br />
<br />
# modprobe tun<br />
<br />
Now create the virtual switch:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
<br />
This line creates the switch, creates {{ic|tap0}}, "plugs" it, and allows the users of the group {{ic|users}} to use it.<br />
<br />
The interface is plugged in but not configured yet. To configure it, run this command:<br />
<br />
# ip addr add 192.168.100.254/24 dev tap0<br />
<br />
Now, you just have to run KVM with these {{ic|-net}} options as a normal user:<br />
<br />
$ qemu-system-x86_64 -net nic -net vde -hda ''[...]''<br />
<br />
Configure networking for your guest as you would do in a physical network.<br />
<br />
{{Tip|You might want to set up NAT on tap device to access the internet from the virtual machine. See [[Internet sharing#Enable NAT]] for more information.}}<br />
<br />
==== Startup scripts ====<br />
<br />
Example of main script starting VDE:<br />
<br />
{{hc|/etc/systemd/scripts/qemu-network-env|<nowiki><br />
#!/bin/sh<br />
# QEMU/VDE network environment preparation script<br />
<br />
# The IP configuration for the tap device that will be used for<br />
# the virtual machine network:<br />
<br />
TAP_DEV=tap0<br />
TAP_IP=192.168.100.254<br />
TAP_MASK=24<br />
TAP_NETWORK=192.168.100.0<br />
<br />
# Host interface<br />
NIC=eth0<br />
<br />
case "$1" in<br />
start)<br />
echo -n "Starting VDE network for QEMU: "<br />
<br />
# If you want tun kernel module to be loaded by script uncomment here<br />
#modprobe tun 2>/dev/null<br />
## Wait for the module to be loaded<br />
#while ! lsmod | grep -q "^tun"; do echo "Waiting for tun device"; sleep 1; done<br />
<br />
# Start tap switch<br />
vde_switch -tap "$TAP_DEV" -daemon -mod 660 -group users<br />
<br />
# Bring tap interface up<br />
ip address add "$TAP_IP"/"$TAP_MASK" dev "$TAP_DEV"<br />
ip link set "$TAP_DEV" up<br />
<br />
# Start IP Forwarding<br />
echo "1" > /proc/sys/net/ipv4/ip_forward<br />
iptables -t nat -A POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
;;<br />
stop)<br />
echo -n "Stopping VDE network for QEMU: "<br />
# Delete the NAT rules<br />
iptables -t nat -D POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
<br />
# Bring tap interface down<br />
ip link set "$TAP_DEV" down<br />
<br />
# Kill VDE switch<br />
pgrep vde_switch | xargs kill -TERM<br />
;;<br />
restart|reload)<br />
$0 stop<br />
sleep 1<br />
$0 start<br />
;;<br />
*)<br />
echo "Usage: $0 {start|stop|restart|reload}"<br />
exit 1<br />
esac<br />
exit 0<br />
</nowiki>}}<br />
<br />
Example of systemd service using the above script:<br />
<br />
{{hc|/etc/systemd/system/qemu-network-env.service|<nowiki><br />
[Unit]<br />
Description=Manage VDE Switch<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/etc/systemd/scripts/qemu-network-env start<br />
ExecStop=/etc/systemd/scripts/qemu-network-env stop<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
Change permissions for {{ic|qemu-network-env}} to be executable<br />
<br />
# chmod u+x /etc/systemd/scripts/qemu-network-env<br />
<br />
You can [[start]] {{ic|qemu-network-env.service}} as usual.<br />
<br />
====Alternative method====<br />
<br />
If the above method does not work or you do not want to mess with kernel configs, TUN, dnsmasq, and iptables you can do the following for the same result.<br />
<br />
# vde_switch -daemon -mod 660 -group users<br />
# slirpvde --dhcp --daemon<br />
<br />
Then, to start the VM with a connection to the network of the host:<br />
<br />
$ qemu-system-x86_64 -net nic,macaddr=52:54:00:00:EE:03 -net vde ''disk_image''<br />
<br />
=== VDE2 Bridge ===<br />
<br />
Based on [https://selamatpagicikgu.wordpress.com/2011/06/08/quickhowto-qemu-networking-using-vde-tuntap-and-bridge/ quickhowto: qemu networking using vde, tun/tap, and bridge] graphic. Any virtual machine connected to vde is externally exposed. For example, each virtual machine can receive DHCP configuration directly from your ADSL router.<br />
<br />
==== Basics ====<br />
<br />
Remember that you need {{ic|tun}} module and {{Pkg|bridge-utils}} package.<br />
<br />
Create the vde2/tap device:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
# ip link set tap0 up<br />
<br />
Create bridge:<br />
<br />
# brctl addbr br0<br />
<br />
Add devices:<br />
<br />
# brctl addif br0 eth0<br />
# brctl addif br0 tap0<br />
<br />
And configure bridge interface:<br />
<br />
# dhcpcd br0<br />
<br />
==== Startup scripts ====<br />
<br />
All devices must be set up. And only the bridge needs an IP address. For physical devices on the bridge (e.g. {{ic|eth0}}), this can be done with [[netctl]] using a custom Ethernet profile with:<br />
<br />
{{hc|/etc/netctl/ethernet-noip|2=<br />
Description='A more versatile static Ethernet connection'<br />
Interface=eth0<br />
Connection=ethernet<br />
IP=no<br />
}}<br />
<br />
The following custom systemd service can be used to create and activate a VDE2 tap interface for use in the {{ic|users}} user group.<br />
<br />
{{hc|/etc/systemd/system/vde2@.service|2=<br />
[Unit]<br />
Description=Network Connectivity for %i<br />
Wants=network.target<br />
Before=network.target<br />
<br />
[Service]<br />
Type=oneshot<br />
RemainAfterExit=yes<br />
ExecStart=/usr/bin/vde_switch -tap %i -daemon -mod 660 -group users<br />
ExecStart=/usr/bin/ip link set dev %i up<br />
ExecStop=/usr/bin/ip addr flush dev %i<br />
ExecStop=/usr/bin/ip link set dev %i down<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
}}<br />
<br />
And finally, you can create the [[Bridge with netctl|bridge interface with netctl]].<br />
<br />
=== Shorthand configuration ===<br />
<br />
If you are using QEMU with various networking options a lot, you probably have created a lot of {{ic|-netdev}} and {{ic|-device}} argument pairs, which gets quite repetitive. You can instead use the {{ic|-nic}} argument to combine {{ic|-netdev}} and {{ic|-device}} together, so that, for example, these arguments:<br />
<br />
-netdev tap,id=network0,ifname=tap0,script=no,downscript=no,vhost=on -device virtio-net-pci,netdev=network0<br />
<br />
become:<br />
<br />
-nic tap,script=no,downscript=no,vhost=on,model=virtio-net-pci<br />
<br />
Notice the lack of network IDs, and that the device was created with {{ic|1=model=}}. The first half of the {{ic|-nic}} parameters are {{ic|-netdev}} parameters, whereas the second half (after {{ic|1=model=}}) are related with the device. The same parameters (for example, {{ic|1=smb=}}) are used. To completely disable the networking use {{ic|-nic none}}.<br />
<br />
See [https://qemu.weilnetz.de/doc/qemu-doc.html#Network-options QEMU networking documentation] for more information on parameters you can use.<br />
<br />
== Graphic card ==<br />
<br />
QEMU can emulate a standard graphic card text mode using {{ic|-curses}} command line option. This allows to type text and see text output directly inside a text terminal.<br />
<br />
QEMU can emulate several types of VGA card. The card type is passed in the {{ic|-vga ''type''}} command line option and can be {{ic|std}}, {{ic|qxl}}, {{ic|vmware}}, {{ic|virtio}}, {{ic|cirrus}} or {{ic|none}}.<br />
<br />
=== std ===<br />
<br />
With {{ic|-vga std}} you can get a resolution of up to 2560 x 1600 pixels without requiring guest drivers. This is the default since QEMU 2.2.<br />
<br />
=== qxl ===<br />
<br />
QXL is a paravirtual graphics driver with 2D support. To use it, pass the {{ic|-vga qxl}} option and install drivers in the guest. You may want to use [[#SPICE]] for improved graphical performance when using QXL.<br />
<br />
On Linux guests, the {{ic|qxl}} and {{ic|bochs_drm}} kernel modules must be loaded in order to gain a decent performance.<br />
<br />
Default VGA memory size for QXL devices is 16M which is sufficient to drive resolutions approximately up to QHD (2560x1440). To enable higher resolutions, [[#Multi-monitor support|increase vga_memmb]].<br />
<br />
=== vmware ===<br />
<br />
Although it is a bit buggy, it performs better than std and cirrus. Install the VMware drivers {{Pkg|xf86-video-vmware}} and {{Pkg|xf86-input-vmmouse}} for Arch Linux guests.<br />
<br />
=== virtio ===<br />
<br />
{{ic|virtio-vga}} / {{ic|virtio-gpu}} is a paravirtual 3D graphics driver based on [https://virgil3d.github.io/ virgl]. Currently a work in progress, supporting only very recent (>= 4.4) Linux guests with {{Pkg|mesa}} (>=11.2) compiled with the option {{ic|1=gallium-drivers=virgl}}.<br />
<br />
To enable 3D acceleration on the guest system select this vga with {{ic|-vga virtio}} and enable the opengl context in the display device with {{ic|1=-display sdl,gl=on}} or {{ic|1=-display gtk,gl=on}} for the sdl and gtk display output respectively. Successful configuration can be confirmed looking at the kernel log in the guest:<br />
<br />
{{hc|$ dmesg {{!}} grep drm |<br />
[drm] pci: virtio-vga detected<br />
[drm] virgl 3d acceleration enabled<br />
}}<br />
<br />
=== cirrus ===<br />
<br />
The cirrus graphical adapter was the default [http://wiki.qemu.org/ChangeLog/2.2#VGA before 2.2]. It [https://www.kraxel.org/blog/2014/10/qemu-using-cirrus-considered-harmful/ should not] be used on modern systems.<br />
<br />
=== none ===<br />
<br />
This is like a PC that has no VGA card at all. You would not even be able to access it with the {{ic|-vnc}} option. Also, this is different from the {{ic|-nographic}} option which lets QEMU emulate a VGA card, but disables the SDL display.<br />
<br />
== SPICE ==<br />
The [http://spice-space.org/ SPICE project] aims to provide a complete open source solution for remote access to virtual machines in a seamless way.<br />
=== Enabling SPICE support on the host ===<br />
The following is an example of booting with SPICE as the remote desktop protocol, including the support for copy and paste from host:<br />
<br />
$ qemu-system-x86_64 -vga qxl -device virtio-serial-pci -spice port=5930,disable-ticketing -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
The parameters have the following meaning:<br />
<br />
# {{ic|-device virtio-serial-pci}} adds a virtio-serial device<br />
# {{ic|1=-spice port=5930,disable-ticketing}} set TCP port {{ic|5930}} for spice channels listening and allow client to connect without authentication{{Tip|Using [[wikipedia:Unix_socket|Unix sockets]] instead of TCP ports does not involve using network stack on the host system. It does not imply that packets are encapsulated and decapsulated to use the network and the related protocol. The sockets are identified solely by the inodes on the hard drive. It is therefore considered better for performance. Use instead {{ic|1=-spice unix,addr=/tmp/vm_spice.socket,disable-ticketing}}.}}<br />
# {{ic|1=-device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0}} opens a port for spice vdagent in the virtio-serial device,<br />
# {{ic|1=-chardev spicevmc,id=spicechannel0,name=vdagent}} adds a spicevmc chardev for that port. It is important that the {{ic|1=chardev=}} option of the {{ic|virtserialport}} device matches the {{ic|1=id=}} option given to the {{ic|chardev}} option ({{ic|spicechannel0}} in this example). It is also important that the port name is {{ic|com.redhat.spice.0}}, because that is the namespace where vdagent is looking for in the guest. And finally, specify {{ic|1=name=vdagent}} so that spice knows what this channel is for.<br />
<br />
=== Connecting to the guest with a SPICE client ===<br />
<br />
A SPICE client is necessary to connect to the guest. In Arch, the following clients are available:<br />
<br />
{{App|virt-viewer|SPICE client recommended by the protocol developers, a subset of the virt-manager project.|https://virt-manager.org/|{{Pkg|virt-viewer}}}}<br />
<br />
{{App|spice-gtk|SPICE GTK client, a subset of the SPICE project. Embedded into other applications as a widget.|https://www.spice-space.org/|{{Pkg|spice-gtk}}}}<br />
<br />
For clients that run on smartphone or on other platforms, refer to the ''Other clients'' section in [http://www.spice-space.org/download.html spice-space download].<br />
<br />
==== Manually running a SPICE client ====<br />
<br />
One way of connecting to a guest listening on Unix socket {{ic|/tmp/vm_spice.socket}} is to manually run the SPICE client using {{ic|$ remote-viewer spice+unix:///tmp/vm_spice.socket}} or {{ic|1=$ spicy --uri="spice+unix:///tmp/vm_spice.socket"}}, depending on the desired client. Since QEMU in SPICE mode acts similarly to a remote desktop server, it may be more convenient to run QEMU in daemon mode with the {{ic|-daemonize}} parameter.<br />
<br />
{{Tip|To connect to the guest through SSH tunelling, the following type of command can be used: {{bc|$ ssh -fL 5999:localhost:5930 ''my.domain.org'' sleep 10; spicy -h 127.0.0.1 -p 5999}}<br />
This example connects ''spicy'' to the local port {{ic|5999}} which is forwarded through SSH to the guest's SPICE server located at the address ''my.domain.org'', port {{ic|5930}}.<br />
Note the {{ic|-f}} option that requests ssh to execute the command {{ic|sleep 10}} in the background. This way, the ssh session runs while the client is active and auto-closes once the client ends.<br />
}}<br />
<br />
==== Running a SPICE client with QEMU ====<br />
<br />
QEMU can automatically start a SPICE client with an appropriate socket, if the display is set to SPICE with the {{ic|-display spice-app}} parameter. This will use the system's default SPICE client as the viewer, determined by your [[XDG_MIME_Applications#mimeapps.list|mimeapps.list]] files.<br />
<br />
=== Enabling SPICE support on the guest ===<br />
<br />
For '''Arch Linux guests''', for improved support for multiple monitors or clipboard sharing, the following packages should be installed:<br />
* {{Pkg|spice-vdagent}}: Spice agent xorg client that enables copy and paste between client and X-session and more.<br />
* {{Pkg|xf86-video-qxl}}: Xorg X11 qxl video driver<br />
For guests under '''other operating systems''', refer to the ''Guest'' section in [http://www.spice-space.org/download.html spice-space download].<br />
<br />
=== Password authentication with SPICE ===<br />
<br />
If you want to enable password authentication with SPICE you need to remove {{ic|disable-ticketing}} from the {{ic|-spice}} argument and instead add {{ic|1=password=''yourpassword''}}. For example:<br />
<br />
$ qemu-system-x86_64 -vga qxl -spice port=5900,password=''yourpassword'' -device virtio-serial-pci -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
Your SPICE client should now ask for the password to be able to connect to the SPICE server.<br />
<br />
=== TLS encrypted communication with SPICE ===<br />
<br />
You can also configure TLS encryption for communicating with the SPICE server. First, you need to have a directory which contains the following files (the names must be exactly as indicated):<br />
<br />
* {{ic|ca-cert.pem}}: the CA master certificate.<br />
* {{ic|server-cert.pem}}: the server certificate signed with {{ic|ca-cert.pem}}.<br />
* {{ic|server-key.pem}}: the server private key.<br />
<br />
An example of generation of self-signed certificates with your own generated CA for your server is shown in the [https://www.spice-space.org/spice-user-manual.html#_generating_self_signed_certificates Spice User Manual].<br />
<br />
Afterwards, you can run QEMU with SPICE as explained above but using the following {{ic|-spice}} argument: {{ic|1=-spice tls-port=5901,password=''yourpassword'',x509-dir=''/path/to/pki_certs''}}, where {{ic|''/path/to/pki_certs''}} is the directory path that contains the three needed files shown earlier.<br />
<br />
It is now possible to connect to the server using {{pkg|virt-viewer}}:<br />
<br />
$ remote-viewer spice://''hostname''?tls-port=5901 --spice-ca-file=''/path/to/ca-cert.pem'' --spice-host-subject="C=''XX'',L=''city'',O=''organization'',CN=''hostname''" --spice-secure-channels=all<br />
<br />
Keep in mind that the {{ic|--spice-host-subject}} parameter needs to be set according to your {{ic|server-cert.pem}} subject. You also need to copy {{ic|ca-cert.pem}} to every client to verify the server certificate.<br />
<br />
{{Tip|You can get the subject line of the server certificate in the correct format for {{ic|--spice-host-subject}} (with entries separated by commas) using the following command: {{bc|<nowiki>$ openssl x509 -noout -subject -in server-cert.pem | cut -d' ' -f2- | sed 's/\///' | sed 's/\//,/g'</nowiki>}}<br />
}}<br />
<br />
The equivalent {{Pkg|spice-gtk}} command is:<br />
<br />
$ spicy -h ''hostname'' -s 5901 --spice-ca-file=ca-cert.pem --spice-host-subject="C=''XX'',L=''city'',O=''organization'',CN=''hostname''" --spice-secure-channels=all<br />
<br />
== VNC ==<br />
<br />
One can add the {{ic|-vnc :''X''}} option to have QEMU redirect the VGA display to the VNC session. Substitute {{ic|''X''}} for the number of the display (0 will then listen on 5900, 1 on 5901...).<br />
<br />
$ qemu-system-x86_64 -vnc :0<br />
<br />
An example is also provided in the [[#Starting QEMU virtual machines on boot]] section.<br />
{{Warning|The default VNC server setup does not use any form of authentication. Any user can connect from any host.}}<br />
<br />
=== Basic password authentication ===<br />
<br />
An access password can be setup easily by using the {{ic|password}} option. The password must be indicated in the QEMU monitor and connection is only possible once the password is provided.<br />
<br />
$ qemu-system-x86_64 -vnc :0,password -monitor stdio<br />
<br />
In the QEMU monitor, password is set using the command {{ic|change vnc password}} and then indicating the password.<br />
<br />
The following command line directly runs vnc with a password:<br />
<br />
$ printf "change vnc password\n%s\n" MYPASSWORD | qemu-system-x86_64 -vnc :0,password -monitor stdio<br />
<br />
{{Note|The password is limited to 8 characters and can be guessed through brute force attack. More elaborated protection is strongly recommended for public network.}}<br />
<br />
== Audio ==<br />
<br />
=== Host ===<br />
<br />
The {{ic|-audiodev}} flag sets the audio backend driver and its options. The list of available audio backend drivers and their optional settings is detailed in the {{man|1|qemu}}. man page.<br />
<br />
At the bare minimum, you need to choose a driver and set an id.<br />
<br />
-audiodev pa,id=snd0<br />
<br />
=== Guest ===<br />
<br />
==== With audiodev ====<br />
<br />
===== Intel HD Audio =====<br />
<br />
For Intel HD Audio emulation add both controller and codec devices. To list the available Intel HDA Audio devices:<br />
<br />
$ qemu-system-x86_64 -device help | grep hda<br />
<br />
Add the audio controller<br />
<br />
-device ich9-intel-hda<br />
<br />
Add the audio codec and map it to a host audio backend id<br />
<br />
-device hda-output,audiodev=snd0<br />
<br />
===== Intel 82801AA AC97 =====<br />
<br />
For AC97 emulation just add the audio card device and map it to a host audio backend id<br />
<br />
-device AC97,audiodev=snd0<br />
<br />
==== Without audiodev ====<br />
<br />
To get list of the supported emulation audio drivers:<br />
$ qemu-system-x86_64 -soundhw help<br />
<br />
To use e.g. {{ic|hda}} driver for the guest use the {{ic|-soundhw hda}} command with QEMU.<br />
<br />
{{Note|Video graphic card emulated drivers for the guest machine may also cause a problem with the sound quality. Test one by one to make it work. You can list possible options with {{ic|<nowiki>qemu-system-x86_64 -h | grep vga</nowiki>}}.}}<br />
<br />
== Installing virtio drivers ==<br />
<br />
QEMU offers guests the ability to use paravirtualized block and network devices using the [http://wiki.libvirt.org/page/Virtio virtio] drivers, which provide better performance and lower overhead.<br />
<br />
* A virtio block device requires the option {{Ic|-drive}} for passing a disk image, with parameter {{Ic|1=if=virtio}}:<br />
$ qemu-system-x86_64 -boot order=c -drive file=''disk_image'',if=virtio<br />
<br />
* Almost the same goes for the network:<br />
$ qemu-system-x86_64 -nic user,model=virtio-net-pci<br />
<br />
{{Note|This will only work if the guest machine has drivers for virtio devices. Linux does, and the required drivers are included in Arch Linux, but there is no guarantee that virtio devices will work with other operating systems.}}<br />
<br />
=== Preparing an (Arch) Linux guest ===<br />
<br />
To use virtio devices after an Arch Linux guest has been installed, the following modules must be loaded in the guest: {{Ic|virtio}}, {{Ic|virtio_pci}}, {{Ic|virtio_blk}}, {{Ic|virtio_net}}, and {{Ic|virtio_ring}}. For 32-bit guests, the specific "virtio" module is not necessary.<br />
<br />
If you want to boot from a virtio disk, the initial ramdisk must contain the necessary modules. By default, this is handled by [[mkinitcpio]]'s {{ic|autodetect}} hook. Otherwise use the {{ic|MODULES}} array in {{ic|/etc/mkinitcpio.conf}} to include the necessary modules and rebuild the initial ramdisk.<br />
<br />
{{hc|/etc/mkinitcpio.conf|2=<br />
MODULES=(virtio virtio_blk virtio_pci virtio_net)}}<br />
<br />
Virtio disks are recognized with the prefix {{ic|'''v'''}} (e.g. {{ic|'''v'''da}}, {{ic|'''v'''db}}, etc.); therefore, changes must be made in at least {{ic|/etc/fstab}} and {{ic|/boot/grub/grub.cfg}} when booting from a virtio disk.<br />
<br />
{{Tip|When referencing disks by [[UUID]] in both {{ic|/etc/fstab}} and bootloader, nothing has to be done.}}<br />
<br />
Further information on paravirtualization with KVM can be found [http://www.linux-kvm.org/page/Boot_from_virtio_block_device here].<br />
<br />
You might also want to install {{Pkg|qemu-guest-agent}} to implement support for QMP commands that will enhance the hypervisor management capabilities. After installing the package you can enable and start the {{ic|qemu-ga.service}}.<br />
<br />
=== Preparing a Windows guest ===<br />
<br />
==== Block device drivers ====<br />
<br />
===== New Install of Windows =====<br />
<br />
Windows does not come with the virtio drivers. Therefore, you will need to load them during installation. There are basically two ways to do this: via Floppy Disk or via ISO files. Both images can be downloaded from the [https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/stable-virtio/virtio-win.iso Fedora repository].<br />
<br />
The floppy disk option is difficult because you will need to press F6 (Shift-F6 on newer Windows) at the very beginning of powering on the QEMU. This is difficult since you need time to connect your VNC console window. You can attempt to add a delay to the boot sequence. See {{man|1|qemu}} for more details about applying a delay at boot.<br />
<br />
The ISO option to load drivers is the preferred way, but it is available only on Windows Vista and Windows Server 2008 and later. The procedure is to load the image with virtio drivers in an additional cdrom device along with the primary disk device and Windows installer:<br />
<br />
$ qemu-system-x86_64 ... \<br />
-drive file=''windows_disk_image'',index=0,media=disk,if=virtio \<br />
-drive file=''windows.iso'',index=2,media=cdrom \<br />
-drive file=''virtio.iso'',index=3,media=cdrom \<br />
...<br />
<br />
During the installation, at some stage, the Windows installer will ask "Where do you want to install Windows?", it will give a warning that no disks are found. Follow the example instructions below (based on Windows Server 2012 R2 with Update).<br />
<br />
* Select the option ''Load Drivers''.<br />
* Uncheck the box for ''Hide drivers that aren't compatible with this computer's hardware''.<br />
* Click the browse button and open the CDROM for the virtio iso, usually named "virtio-win-XX".<br />
* Now browse to {{ic|E:\viostor\[your-os]\amd64}}, select it, and confirm.<br />
<br />
You should now see your virtio disk(s) listed here, ready to be selected, formatted and installed to.<br />
<br />
===== Change Existing Windows VM to use virtio =====<br />
<br />
Modifying an existing Windows guest for booting from virtio disk requires that the virtio driver is available in the guest and that it is loaded at boot time.<br />
<br />
One can find the virtio disk driver in the [https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/stable-virtio/virtio-win.iso Fedora repository].<br />
<br />
Now, create a new disk image that will be used to search for the virtio driver:<br />
<br />
$ qemu-img create -f qcow2 ''fake.qcow2'' 1G<br />
<br />
Run the original Windows guest (with the boot disk still in IDE mode) with the fake disk (in virtio mode) and a CD-ROM with the driver.<br />
<br />
$ qemu-system-x86_64 -m 512 -drive file=''windows_disk_image'',if=ide -drive file=''fake.qcow2'',if=virtio -cdrom virtio-win-0.1-81.iso<br />
<br />
Windows will detect the fake disk and look for a suitable driver. If it fails, go to ''Device Manager'', locate the SCSI drive with an exclamation mark icon (should be open), click ''Update driver'' and select the virtual CD-ROM. Do not navigate to the driver folder within the CD-ROM, simply select the CD-ROM drive and Windows will find the appropriate driver automatically (tested for Windows 7 SP1).<br />
<br />
Request Windows to boot in safe mode next time it starts up. This can be done using the ''msconfig.exe'' tool in Windows. In safe mode all the drivers will be loaded at boot time including the new virtio driver. Once Windows knows that the virtio driver is required at boot it will memorize it for future boot.<br />
<br />
Once instructed to boot in safe mode, you can turn off the virtual machine and launch it again, now with the boot disk attached in virtio mode:<br />
<br />
$ qemu-system-x86_64 -m 512 -drive file=''windows_disk_image'',if=virtio<br />
<br />
You should boot in safe mode with virtio driver loaded, you can now return to ''msconfig.exe'' disable safe mode boot and restart Windows.<br />
<br />
{{Note|If you encounter the blue screen of death using the {{ic|1=if=virtio}} parameter, it probably means the virtio disk driver is not installed or not loaded at boot time, reboot in safe mode and check your driver configuration.}}<br />
<br />
==== Network drivers ====<br />
<br />
Installing virtio network drivers is a bit easier, simply add the {{ic|-nic}} argument.<br />
<br />
$ qemu-system-x86_64 -m 512 -drive file=''windows_disk_image'',if=virtio -nic user,model=virtio-net-pci -cdrom virtio-win-0.1-74.iso<br />
<br />
Windows will detect the network adapter and try to find a driver for it. If it fails, go to the ''Device Manager'', locate the network adapter with an exclamation mark icon (should be open), click ''Update driver'' and select the virtual CD-ROM. Do not forget to select the checkbox which says to search for directories recursively.<br />
<br />
==== Balloon driver ====<br />
<br />
If you want to track you guest memory state (for example via {{ic|virsh}} command {{ic|dommemstat}}) or change guest's memory size in runtime (you still will not be able to change memory size, but can limit memory usage via inflating balloon driver) you will need to install guest balloon driver.<br />
<br />
For this you will need to go to ''Device Manager'', locate ''PCI standard RAM Controller'' in ''System devices'' (or unrecognized PCI controller from ''Other devices'') and choose ''Update driver''. In opened window you will need to choose ''Browse my computer...'' and select the CD-ROM (and do not forget the ''Include subdirectories'' checkbox). Reboot after installation. This will install the driver and you will be able to inflate the balloon (for example via hmp command {{ic|balloon ''memory_size''}}, which will cause balloon to take as much memory as possible in order to shrink the guest's available memory size to ''memory_size''). However, you still will not be able to track guest memory state. In order to do this you will need to install ''Balloon'' service properly. For that open command line as administrator, go to the CD-ROM, ''Balloon'' directory and deeper, depending on your system and architecture. Once you are in ''amd64'' (''x86'') directory, run {{ic|blnsrv.exe -i}} which will do the installation. After that {{ic|virsh}} command {{ic|dommemstat}} should be outputting all supported values.<br />
<br />
=== Preparing a FreeBSD guest ===<br />
<br />
Install the {{ic|emulators/virtio-kmod}} port if you are using FreeBSD 8.3 or later up until 10.0-CURRENT where they are included into the kernel. After installation, add the following to your {{ic|/boot/loader.conf}} file:<br />
<br />
{{bc|1=<br />
virtio_load="YES"<br />
virtio_pci_load="YES"<br />
virtio_blk_load="YES"<br />
if_vtnet_load="YES"<br />
virtio_balloon_load="YES"<br />
}}<br />
<br />
Then modify your {{ic|/etc/fstab}} by doing the following:<br />
<br />
# sed -ibak "s/ada/vtbd/g" /etc/fstab<br />
<br />
And verify that {{ic|/etc/fstab}} is consistent. If anything goes wrong, just boot into a rescue CD and copy {{ic|/etc/fstab.bak}} back to {{ic|/etc/fstab}}.<br />
<br />
== QEMU monitor ==<br />
<br />
While QEMU is running, a monitor console is provided in order to provide several ways to interact with the virtual machine running. The QEMU monitor offers interesting capabilities such as obtaining information about the current virtual machine, hotplugging devices, creating snapshots of the current state of the virtual machine, etc. To see the list of all commands, run {{ic|help}} or {{ic|?}} in the QEMU monitor console or review the relevant section of the [https://qemu.weilnetz.de/doc/qemu-doc.html#pcsys_005fmonitor official QEMU documentation].<br />
<br />
=== Accessing the monitor console ===<br />
<br />
==== Graphical view ====<br />
<br />
When using the {{ic|std}} default graphics option, one can access the QEMU monitor by pressing {{ic|Ctrl+Alt+2}} or by clicking ''View > compatmonitor0'' in the QEMU window. To return to the virtual machine graphical view either press {{ic|Ctrl+Alt+1}} or click ''View > VGA''.<br />
<br />
However, the standard method of accessing the monitor is not always convenient and does not work in all graphic outputs QEMU supports.<br />
<br />
==== Telnet ====<br />
<br />
To enable [[telnet]], run QEMU with the {{ic|-monitor telnet:127.0.0.1:''port'',server,nowait}} parameter. When the virtual machine is started you will be able to access the monitor via telnet:<br />
<br />
$ telnet 127.0.0.1 ''port''<br />
<br />
{{Note|If {{ic|127.0.0.1}} is specified as the IP to listen it will be only possible to connect to the monitor from the same host QEMU is running on. If connecting from remote hosts is desired, QEMU must be told to listen {{ic|0.0.0.0}} as follows: {{ic|-monitor telnet:0.0.0.0:''port'',server,nowait}}. Keep in mind that it is recommended to have a [[firewall]] configured in this case or make sure your local network is completely trustworthy since this connection is completely unauthenticated and unencrypted.}}<br />
<br />
==== UNIX socket ====<br />
<br />
Run QEMU with the {{ic|-monitor unix:''socketfile'',server,nowait}} parameter. Then you can connect with either {{pkg|socat}} or {{pkg|openbsd-netcat}}.<br />
<br />
For example, if QEMU is run via:<br />
<br />
$ qemu-system-x86_64 ''[...]'' -monitor unix:/tmp/monitor.sock,server,nowait ''[...]''<br />
<br />
It is possible to connect to the monitor with:<br />
<br />
$ socat - UNIX-CONNECT:/tmp/monitor.sock<br />
<br />
Or with:<br />
<br />
$ nc -U /tmp/monitor.sock<br />
<br />
==== TCP ====<br />
<br />
You can expose the monitor over TCP with the argument {{ic|-monitor tcp:127.0.0.1:''port'',server,nowait}}. Then connect with netcat, either {{pkg|openbsd-netcat}} or {{pkg|gnu-netcat}} by running:<br />
<br />
$ nc 127.0.0.1 ''port''<br />
<br />
{{Note|In order to be able to connect to the tcp socket from other devices other than the same host QEMU is being run on you need to listen to {{ic|0.0.0.0}} like explained in the telnet case. The same security warnings apply in this case as well.}}<br />
<br />
==== Standard I/O ====<br />
<br />
It is possible to access the monitor automatically from the same terminal QEMU is being run by running it with the argument {{ic|-monitor stdio}}.<br />
<br />
=== Sending keyboard presses to the virtual machine using the monitor console ===<br />
<br />
Some combinations of keys may be difficult to perform on virtual machines due to the host intercepting them instead in some configurations (a notable example is the {{ic|Ctrl+Alt+F*}} key combinations, which change the active tty). To avoid this problem, the problematic combination of keys may be sent via the monitor console instead. Switch to the monitor and use the {{ic|sendkey}} command to forward the necessary keypresses to the virtual machine. For example:<br />
<br />
(qemu) sendkey ctrl-alt-f2<br />
<br />
=== Creating and managing snapshots via the monitor console ===<br />
<br />
{{Note|This feature will '''only''' work when the virtual machine disk image is in ''qcow2'' format. It will not work with ''raw'' images.}}<br />
<br />
It is sometimes desirable to save the current state of a virtual machine and having the possibility of reverting the state of the virtual machine to that of a previously saved snapshot at any time. The QEMU monitor console provides the user with the necessary utilities to create snapshots, manage them, and revert the machine state to a saved snapshot.<br />
<br />
* Use {{ic|savevm ''name''}} in order to create a snapshot with the tag ''name''.<br />
* Use {{ic|loadvm ''name''}} to revert the virtual machine to the state of the snapshot ''name''.<br />
* Use {{ic|delvm ''name''}} to delete the snapshot tagged as ''name''.<br />
* Use {{ic|info snapshots}} to see a list of saved snapshots. Snapshots are identified by both an auto-incremented ID number and a text tag (set by the user on snapshot creation).<br />
<br />
=== Running the virtual machine in immutable mode ===<br />
<br />
It is possible to run a virtual machine in a frozen state so that all changes will be discarded when the virtual machine is powered off just by running QEMU with the {{ic|-snapshot}} parameter. When the disk image is written by the guest, changes will be saved in a temporary file in {{ic|/tmp}} and will be discarded when QEMU halts.<br />
<br />
However, if a machine is running in frozen mode it is still possible to save the changes to the disk image if it is afterwards desired by using the monitor console and running the following command:<br />
<br />
(qemu) commit all<br />
<br />
If snapshots are created when running in frozen mode they will be discarded as soon as QEMU is exited unless changes are explicitly commited to disk, as well.<br />
<br />
=== Pause and power options via the monitor console ===<br />
<br />
Some operations of a physical machine can be emulated by QEMU using some monitor commands:<br />
<br />
* {{ic|system_powerdown}} will send an ACPI shutdown request to the virtual machine. This effect is similar to the power button in a physical machine.<br />
* {{ic|system_reset}} will reset the virtual machine similarly to a reset button in a physical machine. This operation can cause data loss and file system corruption since the virtual machine is not cleanly restarted.<br />
* {{ic|stop}} will pause the virtual machine.<br />
* {{ic|cont}} will resume a virtual machine previously paused.<br />
<br />
=== Taking screenshots of the virtual machine ===<br />
<br />
Screenshots of the virtual machine graphic display can be obtained in the PPM format by running the following command in the monitor console:<br />
<br />
(qemu) screendump ''file.ppm''<br />
<br />
== QEMU machine protocol ==<br />
<br />
The QEMU machine protocol (QMP) is a JSON-based protocol which allows applications to control a QEMU instance. Similarly to the [[#QEMU monitor]] it offers ways to interact with a running machine and the JSON protocol allows to do it programmatically. The description of all the QMP commands can be found in [https://raw.githubusercontent.com/coreos/qemu/master/qmp-commands.hx qmp-commands].<br />
<br />
=== Start QMP ===<br />
<br />
The usual way to control the guest using the QMP protocol, is to open a TCP socket when launching the machine using the {{ic|-qmp}} option. Here it is using for example the TCP port 4444:<br />
<br />
$ qemu-system-x86_64 ''[...]'' -qmp tcp:localhost:4444,server,nowait<br />
<br />
Then one way to communicate with the QMP agent is to use [[netcat]]:<br />
<br />
{{hc|nc localhost 4444|{"QMP": {"version": {"qemu": {"micro": 0, "minor": 1, "major": 3}, "package": ""}, "capabilities": []} } }}<br />
<br />
At this stage, the only command that can be recognized is {{ic|qmp_capabilities}}, so that QMP enters into command mode. Type:<br />
<br />
{"execute": "qmp_capabilities"}<br />
<br />
Now, QMP is ready to receive commands, to retrieve the list of recognized commands, use:<br />
<br />
{"execute": "query-commands"}<br />
<br />
=== Live merging of child image into parent image ===<br />
<br />
It is possible to merge a running snapshot into its parent by issuing a {{ic|block-commit}} command. In its simplest form the following line will commit the child into its parent:<br />
<br />
{"execute": "block-commit", "arguments": {"device": "''devicename''"}}<br />
<br />
Upon reception of this command, the handler looks for the base image and converts it from read only to read write mode and then runs the commit job.<br />
<br />
Once the ''block-commit'' operation has completed, the event {{ic|BLOCK_JOB_READY}} will be emitted, signalling that the synchronization has finished. The job can then be gracefully completed by issuing the command {{ic|block-job-complete}}:<br />
<br />
{"execute": "block-job-complete", "arguments": {"device": "''devicename''"}}<br />
<br />
Until such a command is issued, the ''commit'' operation remains active.<br />
After successful completion, the base image remains in read write mode and becomes the new active layer. On the other hand, the child image becomes invalid and it is the responsibility of the user to clean it up.<br />
<br />
{{Tip|The list of device and their names can be retrieved by executing the command {{ic|query-block}} and parsing the results. The device name is in the {{ic|device}} field, for example {{ic|ide0-hd0}} for the hard disk in this example: {{hc|{"execute": "query-block"}|{"return": [{"io-status": "ok", "device": "'''ide0-hd0'''", "locked": false, "removable": false, "inserted": {"iops_rd": 0, "detect_zeroes": "off", "image": {"backing-image": {"virtual-size": 27074281472, "filename": "parent.qcow2", ... } }} }}<br />
<br />
=== Live creation of a new snapshot ===<br />
<br />
To create a new snapshot out of a running image, run the command:<br />
<br />
{"execute": "blockdev-snapshot-sync", "arguments": {"device": "''devicename''","snapshot-file": "''new_snapshot_name''.qcow2"}}<br />
<br />
This creates an overlay file named {{ic|''new_snapshot_name''.qcow2}} which then becomes the new active layer.<br />
<br />
== Tips and tricks ==<br />
=== Improve virtual machine performance ===<br />
<br />
There are a number of techniques that you can use to improve the performance of the virtual machine. For example:<br />
<br />
* Apply [[#Enabling KVM]]: add {{ic|-enable-kvm}} to the QEMU start command you use.<br />
* Use the {{ic|-cpu host}} option to make QEMU emulate the host's exact CPU. If you do not do this, it may be trying to emulate a more generic CPU.<br />
* Especially for Windows guests, enable [http://blog.wikichoon.com/2014/07/enabling-hyper-v-enlightenments-with-kvm.html Hyper-V enlightenments]: {{ic|1=-cpu host,hv_relaxed,hv_spinlocks=0x1fff,hv_vapic,hv_time}}.<br />
* If the host machine has multiple cores, assign the guest more cores using the {{ic|-smp}} option.<br />
* Make sure you have assigned the virtual machine enough memory. By default, QEMU only assigns 128 MiB of memory to each virtual machine. Use the {{ic|-m}} option to assign more memory. For example, {{ic|-m 1024}} runs a virtual machine with 1024 MiB of memory.<br />
* If supported by drivers in the guest operating system, use [http://wiki.libvirt.org/page/Virtio virtio] for network and/or block devices. For example:<br />
$ qemu-system-x86_64 -net nic,model=virtio -net tap,if=tap0,script=no -drive file=''disk_image'',media=disk,if=virtio<br />
* Use TAP devices instead of user-mode networking. See [[#Tap networking with QEMU]].<br />
* If the guest OS is doing heavy writing to its disk, you may benefit from certain mount options on the host's file system. For example, you can mount an [[Ext4|ext4 file system]] with the option {{ic|1=barrier=0}}. You should read the documentation for any options that you change because sometimes performance-enhancing options for file systems come at the cost of data integrity.<br />
* If you have a raw disk image, you may want to disable the cache:<br />
$ qemu-system-x86_64 -drive file=''disk_image'',if=virtio,'''cache=none'''<br />
* Use the native Linux AIO:<br />
$ qemu-system-x86_64 -drive file=''disk_image'',if=virtio''',aio=native,cache.direct=on'''<br />
* If you are running multiple virtual machines concurrently that all have the same operating system installed, you can save memory by enabling [[wikipedia:Kernel_SamePage_Merging_(KSM)|kernel same-page merging]]. See [[#Enabling KSM]].<br />
* In some cases, memory can be reclaimed from running virtual machines by running a memory ballooning driver in the guest operating system and launching QEMU using {{ic|-device virtio-balloon}}.<br />
* It is possible to use a emulation layer for an ICH-9 AHCI controller (although it may be unstable). The AHCI emulation supports [[Wikipedia:Native_Command_Queuing|NCQ]], so multiple read or write requests can be outstanding at the same time:<br />
$ qemu-system-x86_64 -drive id=disk,file=''disk_image'',if=none -device ich9-ahci,id=ahci -device ide-drive,drive=disk,bus=ahci.0<br />
<br />
See http://www.linux-kvm.org/page/Tuning_KVM for more information.<br />
<br />
=== Starting QEMU virtual machines on boot ===<br />
<br />
==== With libvirt ====<br />
<br />
If a virtual machine is set up with [[libvirt]], it can be configured with {{ic|virsh autostart}} or through the ''virt-manager'' GUI to start at host boot by going to the Boot Options for the virtual machine and selecting "Start virtual machine on host boot up".<br />
<br />
==== With systemd service ====<br />
<br />
To run QEMU VMs on boot, you can use following systemd unit and config.<br />
<br />
{{hc|/etc/systemd/system/qemu@.service|2=<br />
[Unit]<br />
Description=QEMU virtual machine<br />
<br />
[Service]<br />
Environment="haltcmd=kill -INT $MAINPID"<br />
EnvironmentFile=/etc/conf.d/qemu.d/%i<br />
ExecStart=/usr/bin/qemu-system-x86_64 -name %i -enable-kvm -m 512 -nographic $args<br />
ExecStop=/usr/bin/bash -c ${haltcmd}<br />
ExecStop=/usr/bin/bash -c 'while nc localhost 7100; do sleep 1; done'<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
}}<br />
<br />
{{Note|This service will wait for the console port to be released, which means that the VM has been shutdown, to graciously end.}}<br />
<br />
Then create per-VM configuration files, named {{ic|/etc/conf.d/qemu.d/''vm_name''}}, with the variables {{ic|args}} and {{ic|haltcmd}} set. Example configs:<br />
<br />
{{hc|/etc/conf.d/qemu.d/one|2=<br />
args="-hda /dev/vg0/vm1 -serial telnet:localhost:7000,server,nowait,nodelay \<br />
-monitor telnet:localhost:7100,server,nowait,nodelay -vnc :0"<br />
<br />
haltcmd="echo 'system_powerdown' {{!}} nc localhost 7100" # or netcat/ncat}}<br />
<br />
{{hc|/etc/conf.d/qemu.d/two|2=<br />
args="-hda /srv/kvm/vm2 -serial telnet:localhost:7001,server,nowait,nodelay -vnc :1"<br />
<br />
haltcmd="ssh powermanager@vm2 sudo poweroff"}}<br />
<br />
The description of the variables is the following:<br />
<br />
* {{ic|args}} - QEMU command line arguments to be used.<br />
* {{ic|haltcmd}} - Command to shut down a VM safely. In the first example, the QEMU monitor is exposed via telnet using {{ic|-monitor telnet:..}} and the VMs are powered off via ACPI by sending {{ic|system_powerdown}} to monitor with the {{ic|nc}} command. In the other example, SSH is used.<br />
<br />
To set which virtual machines will start on boot-up, [[enable]] the {{ic|qemu@''vm_name''.service}} systemd unit.<br />
<br />
=== Mouse integration ===<br />
<br />
To prevent the mouse from being grabbed when clicking on the guest operating system's window, add the options {{ic|-usb -device usb-tablet}}. This means QEMU is able to report the mouse position without having to grab the mouse. This also overrides PS/2 mouse emulation when activated. For example:<br />
<br />
$ qemu-system-x86_64 -hda ''disk_image'' -m 512 -usb -device usb-tablet<br />
<br />
If that does not work, try using {{ic|-vga qxl}} parameter, also look at the instructions [[#Mouse cursor is jittery or erratic]].<br />
<br />
=== Pass-through host USB device ===<br />
<br />
It is possible to access the physical device connected to a USB port of the host from the guest. The first step is to identify where the device is connected, this can be found running the {{ic|lsusb}} command. For example:<br />
<br />
{{hc|$ lsusb|<br />
...<br />
Bus '''003''' Device '''007''': ID '''0781''':'''5406''' SanDisk Corp. Cruzer Micro U3<br />
}}<br />
<br />
The outputs in bold above will be useful to identify respectively the ''host_bus'' and ''host_addr'' or the ''vendor_id'' and ''product_id''.<br />
<br />
In qemu, the idea is to emulate an EHCI (USB 2) or XHCI (USB 3) controller with the option {{ic|1=-device usb-ehci,id=ehci}} or {{ic|1=-device qemu-xhci,id=xhci}} respectively and then attach the physical device to it with the option {{ic|1=-device usb-host,..}}. We will consider that ''controller_id'' is either {{ic|ehci}} or {{ic|xhci}} for the rest of this section.<br />
<br />
Then, there are two ways to connect to the USB of the host with qemu:<br />
<br />
# Identify the device and connect to it on any bus and address it is attached to on the host, the generic syntax is: {{bc|1=-device usb-host,bus=''controller_id''.0,vendorid=0x''vendor_id'',productid=0x''product_id''}}Applied to the device used in the example above, it becomes:{{bc|1=-device usb-ehci,id=ehci -device usb-host,bus=ehci.0,vendorid=0x'''0781''',productid=0x'''5406'''}}One can also add the {{ic|1=...,port=''port_number''}} setting to the previous option to specify in which physical port of the virtual controller the device should be attached, useful in the case one wants to add multiple usb devices to the VM.<br />
# Starting from QEMU 5.1.0, the {{ic|usb-host}} {{ic|hostdevice}} property can also be used: {{bc|1=-device qemu-xhci,id=xhci -device usb-host,bus=xhci.0,hostdevice=/dev/bus/usb/$bus/$dev}}<br />
# Attach whatever is connected to a given USB bus and address, the syntax is:{{bc|1=-device usb-host,bus=''controller_id''.0,hostbus=''host_bus'',host_addr=''host_addr''}}Applied to the bus and the address in the example above, it becomes:{{bc|1=-device usb-ehci,id=ehci -device usb-host,bus=ehci.0,hostbus='''3''',hostaddr='''7'''}}<br />
<br />
{{Note|If you encounter permission errors when running QEMU, see [[udev#About udev rules]] for information on how to set permissions of the device.}}<br />
<br />
=== USB redirection with SPICE ===<br />
<br />
When using [[#SPICE]] it is possible to redirect USB devices from the client to the virtual machine without needing to specify them in the QEMU command. It is possible to configure the number of USB slots available for redirected devices (the number of slots will determine the maximum number of devices which can be redirected simultaneously). The main advantages of using SPICE for redirection compared to the previously-mentioned {{ic|-usbdevice}} method is the possibility of hot-swapping USB devices after the virtual machine has started, without needing to halt it in order to remove USB devices from the redirection or adding new ones. This method of USB redirection also allows us to redirect USB devices over the network, from the client to the server. In summary, it is the most flexible method of using USB devices in a QEMU virtual machine.<br />
<br />
We need to add one EHCI/UHCI controller per available USB redirection slot desired as well as one SPICE redirection channel per slot. For example, adding the following arguments to the QEMU command you use for starting the virtual machine in SPICE mode will start the virtual machine with three available USB slots for redirection:<br />
<br />
{{bc|1=-device ich9-usb-ehci1,id=usb \<br />
-device ich9-usb-uhci1,masterbus=usb.0,firstport=0,multifunction=on \<br />
-device ich9-usb-uhci2,masterbus=usb.0,firstport=2 \<br />
-device ich9-usb-uhci3,masterbus=usb.0,firstport=4 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev1 -device usb-redir,chardev=usbredirchardev1,id=usbredirdev1 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev2 -device usb-redir,chardev=usbredirchardev2,id=usbredirdev2 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev3 -device usb-redir,chardev=usbredirchardev3,id=usbredirdev3}}<br />
See [https://www.spice-space.org/usbredir.html SPICE/usbredir] for more information.<br />
<br />
Both {{ic|spicy}} from {{Pkg|spice-gtk}} (''Input > Select USB Devices for redirection'') and {{ic|remote-viewer}} from {{pkg|virt-viewer}} (''File > USB device selection'') support this feature. Please make sure that you have installed the necessary SPICE Guest Tools on the virtual machine for this functionality to work as expected (see the [[#SPICE]] section for more information).<br />
<br />
{{Warning|Keep in mind that when a USB device is redirected from the client, it will not be usable from the client operating system itself until the redirection is stopped. It is specially important to never redirect the input devices (namely mouse and keyboard), since it will be then difficult to access the SPICE client menus to revert the situation, because the client will not respond to the input devices after being redirected to the virtual machine.}}<br />
<br />
=== Enabling KSM ===<br />
<br />
Kernel Samepage Merging (KSM) is a feature of the Linux kernel that allows for an application to register with the kernel to have its pages merged with other processes that also register to have their pages merged. The KSM mechanism allows for guest virtual machines to share pages with each other. In an environment where many of the guest operating systems are similar, this can result in significant memory savings.<br />
<br />
{{Note|Although KSM may reduce memory usage, it may increase CPU usage. Also note some security issues may occur, see [[Wikipedia:Kernel same-page merging]].}}<br />
<br />
To enable KSM:<br />
<br />
# echo 1 > /sys/kernel/mm/ksm/run<br />
<br />
To make it permanent, use [[systemd#systemd-tmpfiles - temporary files|systemd's temporary files]]:<br />
<br />
{{hc|/etc/tmpfiles.d/ksm.conf|<br />
w /sys/kernel/mm/ksm/run - - - - 1<br />
}}<br />
<br />
If KSM is running, and there are pages to be merged (i.e. at least two similar VMs are running), then {{ic|/sys/kernel/mm/ksm/pages_shared}} should be non-zero. See https://www.kernel.org/doc/html/latest/admin-guide/mm/ksm.html for more information.<br />
<br />
{{Tip|An easy way to see how well KSM is performing is to simply print the contents of all the files in that directory: {{bc|$ grep . /sys/kernel/mm/ksm/*}}}}<br />
<br />
=== Multi-monitor support ===<br />
<br />
The Linux QXL driver supports four heads (virtual screens) by default. This can be changed via the {{ic|1=qxl.heads=N}} kernel parameter.<br />
<br />
The default VGA memory size for QXL devices is 16M (VRAM size is 64M). This is not sufficient if you would like to enable two 1920x1200 monitors since that requires 2 × 1920 × 4 (color depth) × 1200 = 17.6 MiB VGA memory. This can be changed by replacing {{ic|-vga qxl}} by {{ic|<nowiki>-vga none -device qxl-vga,vgamem_mb=32</nowiki>}}. If you ever increase vgamem_mb beyond 64M, then you also have to increase the {{ic|vram_size_mb}} option.<br />
<br />
=== Copy and paste ===<br />
<br />
One way to share the clipboard between the host and the guest is to enable the SPICE remote desktop protocol and access the client with a SPICE client.<br />
One needs to follow the steps described in [[#SPICE]]. A guest run this way will support copy paste with the host.<br />
<br />
=== Windows-specific notes ===<br />
<br />
QEMU can run any version of Windows from Windows 95 through Windows 10.<br />
<br />
It is possible to run [[Windows PE]] in QEMU.<br />
<br />
==== Fast startup ====<br />
<br />
{{Note|An administrator account is required to change power settings.}}<br />
<br />
For Windows 8 (or later) guests it is better to disable "Turn on fast startup (recommended)" from the Power Options of the Control Panel as explained in the following [https://www.tenforums.com/tutorials/4189-turn-off-fast-startup-windows-10-a.html forum page], as it causes the guest to hang during every other boot.<br />
<br />
Fast Startup may also need to be disabled for changes to the {{ic|-smp}} option to be properly applied.<br />
<br />
==== Remote Desktop Protocol ====<br />
<br />
If you use a MS Windows guest, you might want to use RDP to connect to your guest VM. If you are using a VLAN or are not in the same network as the guest, use:<br />
<br />
$ qemu-system-x86_64 -nographic -net user,hostfwd=tcp::5555-:3389<br />
<br />
Then connect with either {{Pkg|rdesktop}} or {{Pkg|freerdp}} to the guest. For example:<br />
<br />
$ xfreerdp -g 2048x1152 localhost:5555 -z -x lan<br />
<br />
=== Clone Linux system installed on physical equipment ===<br />
<br />
Linux system installed on physical equipment can be cloned for running on QEMU vm. See [https://coffeebirthday.wordpress.com/2018/09/14/clone-linux-system-for-qemu-virtual-machine/ Clone Linux system from hardware for QEMU virtual machine]<br />
<br />
=== Chrooting into arm/arm64 environment from x86_64 ===<br />
<br />
Sometimes it is easier to work directly on a disk image instead of the real ARM based device. This can be achieved by mounting an SD card/storage containing the ''root'' partition and chrooting into it.<br />
<br />
Another use case for an ARM chroot is building ARM packages on an x86_64 machine - {{AUR|armutils-git}} can be used for that. Here, the chroot environment can be created from an image tarball from [https://archlinuxarm.org Arch Linux ARM] - see [https://nerdstuff.org/posts/2020/2020-003_simplest_way_to_create_an_arm_chroot/] for a detailed description of this approach.<br />
<br />
Either way, from the chroot it should be possible to run ''pacman'' and install more packages, compile large libraries etc. Since the executables are for the ARM architecture, the translation to x86 needs to be performed by [[QEMU]].<br />
<br />
Install {{AUR|binfmt-qemu-static}} and {{AUR|qemu-user-static}} from the [[AUR]] on the x86_64 machine/host. ''binfmt-qemu-static'' will take care of registering the qemu binaries to binfmt service.<br />
<br />
[[Restart]] {{ic|systemd-binfmt.service}}<br />
<br />
{{AUR|qemu-user-static}} is needed to allow the execution of compiled programs from other architectures. This is similar to what is provided by {{Pkg|qemu-arch-extra}}, but the "static" variant is required for chroot. Examples:<br />
<br />
qemu-arm-static path_to_sdcard/usr/bin/ls<br />
qemu-aarch64-static path_to_sdcard/usr/bin/ls<br />
<br />
These two lines execute the {{ic|ls}} command compiled for 32-bit ARM and 64-bit ARM respectively. Note that this will not work without chrooting, because it will look for libraries not present in the host system.<br />
<br />
{{AUR|qemu-user-static}} allows automatically prefixing the ARM exectuable with {{ic|qemu-arm-static}} or {{ic|qemu-aarch64-static}}.<br />
<br />
Make sure that the ARM executable support is active:<br />
<br />
{{hc|$ ls /proc/sys/fs/binfmt_misc|<br />
qemu-aarch64 qemu-arm qemu-cris qemu-microblaze qemu-mipsel qemu-ppc64 qemu-riscv64 qemu-sh4 qemu-sparc qemu-sparc64 status<br />
qemu-alpha qemu-armeb qemu-m68k qemu-mips qemu-ppc qemu-ppc64abi32 qemu-s390x qemu-sh4eb qemu-sparc32plus register<br />
}}<br />
<br />
Each executable must be listed.<br />
<br />
If it is not active, reinstall ''binfmt-qemu-static'' and restart ''systemd-binfmt''.<br />
<br />
Mount the SD card to {{ic|/mnt/scdard}} (the device name may be different).<br />
<br />
# mkdir -p /mnt/sdcard<br />
# mount /dev/mmcblk0p2 /mnt/sdcard<br />
<br />
Mount boot partition if needed (again, use the suitable device name):<br />
<br />
# mount /dev/mmcblk0p1 /mnt/sdcard/boot<br />
<br />
Finally ''chroot'' into the SD card root as described in [[Change root#Using chroot]]:<br />
<br />
# chroot /mnt/sdcard /bin/bash<br />
<br />
Alternatively, you can use ''arch-chroot'' from {{Pkg|arch-install-scripts}}, as it will provide an easier way to get network support:<br />
# arch-chroot /mnt/sdcard /bin/bash<br />
<br />
You can also use ''systemd-nspawn'' to chroot into the ARM environment:<br />
# systemd-nspawn -D /mnt/sdcard -M myARMMachine --bind-ro=/etc/resolv.conf<br />
<br />
{{ic|1=--bind-ro=/etc/resolv.conf}} is optional and gives a working network DNS inside the chroot<br />
<br />
== Troubleshooting ==<br />
<br />
=== Mouse cursor is jittery or erratic ===<br />
<br />
If the cursor jumps around the screen uncontrollably, entering this on the terminal before starting QEMU might help:<br />
<br />
$ export SDL_VIDEO_X11_DGAMOUSE=0<br />
<br />
If this helps, you can add this to your {{ic|~/.bashrc}} file.<br />
<br />
=== No visible Cursor ===<br />
<br />
Add {{ic|-show-cursor}} to QEMU's options to see a mouse cursor.<br />
<br />
If that still does not work, make sure you have set your display device appropriately, for example: {{ic|-vga qxl}}.<br />
<br />
Another option to try is {{ic|-usb -device usb-tablet}} as mentioned in [[#Mouse integration]]. This overrides the default PS/2 mouse emulation and synchronizes pointer location between host and guest as an added bonus.<br />
<br />
=== Two different mouse cursors are visible ===<br />
<br />
Apply the tip [[#Mouse integration]].<br />
<br />
=== Keyboard issues when using VNC ===<br />
<br />
When using VNC, you might experience keyboard problems described (in gory details) [https://www.berrange.com/posts/2010/07/04/more-than-you-or-i-ever-wanted-to-know-about-virtual-keyboard-handling/ here]. The solution is ''not'' to use the {{ic|-k}} option on QEMU, and to use {{ic|gvncviewer}} from {{Pkg|gtk-vnc}}. See also [http://www.mail-archive.com/libvir-list@redhat.com/msg13340.html this] message posted on libvirt's mailing list.<br />
<br />
=== Keyboard seems broken or the arrow keys do not work ===<br />
<br />
Should you find that some of your keys do not work or "press" the wrong key (in particular, the arrow keys), you likely need to specify your keyboard layout as an option. The keyboard layouts can be found in {{ic|/usr/share/qemu/keymaps}}.<br />
<br />
$ qemu-system-x86_64 -k ''keymap'' ''disk_image''<br />
<br />
=== Guest display stretches on window resize ===<br />
<br />
To restore default window size, press {{ic|Ctrl+Alt+u}}.<br />
<br />
=== ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy ===<br />
<br />
If an error message like this is printed when starting QEMU with {{ic|-enable-kvm}} option:<br />
<br />
ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy<br />
failed to initialize KVM: Device or resource busy<br />
<br />
that means another [[hypervisor]] is currently running. It is not recommended or possible to run several hypervisors in parallel.<br />
<br />
=== libgfapi error message ===<br />
<br />
The error message displayed at startup:<br />
<br />
Failed to open module: libgfapi.so.0: cannot open shared object file: No such file or directory<br />
<br />
[[Install]] {{pkg|glusterfs}} or ignore the error message as GlusterFS is a optional dependency.<br />
<br />
=== Kernel panic on LIVE-environments===<br />
<br />
If you start a live-environment (or better: booting a system) you may encounter this:<br />
<br />
[ end Kernel panic - not syncing: VFS: Unable to mount root fs on unknown block(0,0)<br />
<br />
or some other boot hindering process (e.g. cannot unpack initramfs, cant start service foo).<br />
Try starting the VM with the {{ic|-m VALUE}} switch and an appropriate amount of RAM, if the ram is to low you will probably encounter similar issues as above/without the memory-switch.<br />
<br />
=== Windows 7 guest suffers low-quality sound ===<br />
<br />
Using the {{ic|hda}} audio driver for Windows 7 guest may result in low-quality sound. Changing the audio driver to {{ic|ac97}} by passing the {{ic|-soundhw ac97}} arguments to QEMU and installing the AC97 driver from [https://www.realtek.com/en/component/zoo/category/pc-audio-codecs-ac-97-audio-codecs-software Realtek AC'97 Audio Codecs] in the guest may solve the problem. See [https://bugzilla.redhat.com/show_bug.cgi?id=1176761#c16 Red Hat Bugzilla – Bug 1176761] for more information.<br />
<br />
=== Could not access KVM kernel module: Permission denied ===<br />
<br />
If you encounter the following error:<br />
<br />
libvirtError: internal error: process exited while connecting to monitor: Could not access KVM kernel module: Permission denied failed to initialize KVM: Permission denied<br />
<br />
Systemd 234 assigns a dynamic ID for the {{ic|kvm}} group (see {{Bug|54943}}). To avoid this error, you need edit the file {{ic|/etc/libvirt/qemu.conf}} and change the line with {{ic|1=group = "78"}} to {{ic|1=group = "kvm"}}.<br />
<br />
=== "System Thread Exception Not Handled" when booting a Windows VM ===<br />
<br />
Windows 8 or Windows 10 guests may raise a generic compatibility exception at boot, namely "System Thread Exception Not Handled", which tends to be caused by legacy drivers acting strangely on real machines. On KVM machines this issue can generally be solved by setting the CPU model to {{ic|core2duo}}.<br />
<br />
=== Certain Windows games/applications crashing/causing a bluescreen ===<br />
<br />
Occasionally, applications running in the VM may crash unexpectedly, whereas they would run normally on a physical machine. If, while running {{ic|dmesg -wH}}, you encounter an error mentioning {{ic|MSR}}, the reason for those crashes is that KVM injects a [[wikipedia:General protection fault|General protection fault]] (GPF) when the guest tries to access unsupported [[wikipedia:Model-specific register|Model-specific registers]] (MSRs) - this often results in guest applications/OS crashing. A number of those issues can be solved by passing the {{ic|1=ignore_msrs=1}} option to the KVM module, which will ignore unimplemented MSRs.<br />
<br />
{{hc|/etc/modprobe.d/kvm.conf|2=<br />
...<br />
options kvm ignore_msrs=1<br />
...<br />
}}<br />
<br />
Cases where adding this option might help:<br />
<br />
* GeForce Experience complaining about an unsupported CPU being present.<br />
* StarCraft 2 and L.A. Noire reliably blue-screening Windows 10 with {{ic|KMODE_EXCEPTION_NOT_HANDLED}}. The blue screen information does not identify a driver file in these cases.<br />
<br />
{{Warning|While this is normally safe and some applications might not work without this, silently ignoring unknown MSR accesses could potentially break other software within the VM or other VMs.}}<br />
<br />
=== Applications in the VM experience long delays or take a long time to start ===<br />
<br />
This may be caused by insufficient available entropy in the VM. Consider allowing the guest to access the hosts's entropy pool by adding a [https://wiki.qemu.org/Features/VirtIORNG VirtIO RNG device] to the VM, or by installing an entropy generating daemon such as [[Haveged]].<br />
<br />
Anecdotally, OpenSSH takes a while to start accepting connections under insufficient entropy, without the logs revealing why.<br />
<br />
=== High interrupt latency and microstuttering ===<br />
<br />
This problem manifests itself as small pauses (stutters) and is particularly noticeable in graphics-intensive applications, such as games.<br />
<br />
* One of the causes is CPU power saving features, which are controlled by [[CPU frequency scaling]]. Change this to {{ic|performance}} for all processor cores. <br />
* Another possible cause is PS/2 inputs. Switch from PS/2 to Virtio inputs, see [[PCI passthrough via OVMF#Passing keyboard/mouse via Evdev]].<br />
<br />
=== QXL video causes low resolution ===<br />
<br />
QEMU 4.1.0 introduced a regression where QXL video can fall back to low resolutions, when being displayed through spice. [https://bugs.launchpad.net/qemu/+bug/1843151] For example, when KMS starts, text resolution may become as low as 4x10 characters. When trying to increase GUI resolution, it may go to the lowest supported resolution.<br />
<br />
As a workaround, create your device in this form:<br />
<br />
-device qxl-vga,max_outputs=1...<br />
<br />
=== Hang during VM initramfs ===<br />
<br />
Linux 5.2.11 introduced a KVM regression where under some circumstances a VM may permanently hang during the early boot phase, when the initramfs is being loaded or ran. [https://www.spinics.net/lists/kvm/msg195171.html] Linux 5.3 fixed the regression. The host shows qemu using 100% CPU * number of virtual CPUs. Reported case is with a host using hyperthreading, and a VM being given more than host's {{ic|nproc}}/2 virtual CPUs. It is unknown what exact circumstances trigger one of the threads to delete a memory region to cause this. The workarounds are:<br />
<br />
* Upgrade to Linux 5.3.<br />
* Downgrade to Linux 5.2.10<br />
* Until fixed, try giving the VM no more than the host's {{ic|nproc}}/2 virtual CPUs<br />
* Custom compile linux, reverting commit 2ad350fb4c (note this re-introduces a regression triggered when removing a memslot)<br />
<br />
=== VM does not boot when using a Secure Boot enabled OVMF ===<br />
<br />
{{ic|/usr/share/edk2-ovmf/x64/OVMF_CODE.secboot.fd}} from {{Pkg|edk2-ovmf}} is built with [[Wikipedia:System Management Mode|SMM]] support. If S3 support is not disabled in the VM, then the VM might not boot at all.<br />
<br />
Add the {{ic|1=-global ICH9-LPC.disable_s3=1}} option to the ''qemu'' command.<br />
<br />
See {{Bug|59465}} and https://github.com/tianocore/edk2/blob/master/OvmfPkg/README for more details and the required options to use Secure Boot in QEMU.<br />
<br />
=== Guest CPU interrupts are not firing ===<br />
<br />
If you are writing your own operating system by following the [https://wiki.osdev.org/ OSDev wiki], or are simply getting stepping through the guest architecture assembly code using QEMU's {{ic|gdb}} interface using the {{ic|-s}} flag, it's useful to know that many emulators, QEMU included, usually implement some CPU interrupts leaving many hardware interrupts unimplemented. One way to know if your code if firing an interrupt, is by using:<br />
<br />
-d int<br />
<br />
to enable showing interrupts/exceptions on stdout.<br />
<br />
To see what other guest debugging features QEMU has to offer, see:<br />
<br />
qemu-system-x86_64 -d help<br />
<br />
or replace {{ic|x86_64}} for your chosen guest architecture.<br />
<br />
== See also ==<br />
<br />
* [http://qemu.org Official QEMU website]<br />
* [http://www.linux-kvm.org Official KVM website]<br />
* [http://qemu.weilnetz.de/qemu-doc.html QEMU Emulator User Documentation]<br />
* [[Wikibooks:QEMU|QEMU Wikibook]]<br />
* [http://alien.slackbook.org/dokuwiki/doku.php?id=slackware:qemu Hardware virtualization with QEMU] by AlienBOB (last updated in 2008)<br />
* [http://blog.falconindy.com/articles/build-a-virtual-army.html Building a Virtual Army] by Falconindy<br />
* [http://git.qemu.org/?p=qemu.git;a=tree;f=docs Lastest docs]<br />
* [http://qemu.weilnetz.de/ QEMU on Windows]<br />
* [[wikipedia:Qemu|Wikipedia]]<br />
* [[debian:QEMU|Debian Wiki - QEMU]]<br />
* [https://people.gnome.org/~markmc/qemu-networking.html QEMU Networking on gnome.org]<br />
* [http://bsdwiki.reedmedia.net/wiki/networking_qemu_virtual_bsd_systems.html Networking QEMU Virtual BSD Systems]<br />
* [https://www.gnu.org/software/hurd/hurd/running/qemu.html QEMU on gnu.org]<br />
* [https://wiki.freebsd.org/qemu QEMU on FreeBSD as host]<br />
* [https://wiki.mikejung.biz/KVM_/_Xen KVM/QEMU Virtio Tuning and SSD VM Optimization Guide]<br />
* [https://doc.opensuse.org/documentation/leap/virtualization/html/book-virt/part-virt-qemu.html Managing Virtual Machines with QEMU - openSUSE documentation]<br />
* [https://www.ibm.com/support/knowledgecenter/en/linuxonibm/liaat/liaatkvm.htm KVM on IBM Knowledge Center]</div>Malcontenthttps://wiki.archlinux.org/index.php?title=QEMU&diff=634637QEMU2020-09-08T07:00:10Z<p>Malcontent: Add example for "usb: add hostdevice property to usb-host" https://git.qemu.org/?p=qemu.git;a=commitdiff;h=9f815e83e983d247a3cd67579d2d9c1765adc644</p>
<hr />
<div>[[Category:Emulation]]<br />
[[Category:Hypervisors]]<br />
[[de:Qemu]]<br />
[[es:QEMU]]<br />
[[fr:Qemu]]<br />
[[ja:QEMU]]<br />
[[zh-hans:QEMU]]<br />
[[zh-hant:QEMU]]<br />
{{Related articles start}}<br />
{{Related|:Category:Hypervisors}}<br />
{{Related|Libvirt}}<br />
{{Related|QEMU/Guest graphics acceleration}}<br />
{{Related|PCI passthrough via OVMF}}<br />
{{Related articles end}}<br />
<br />
According to the [http://wiki.qemu.org/Main_Page QEMU about page], "QEMU is a generic and open source machine emulator and virtualizer."<br />
<br />
When used as a machine emulator, QEMU can run OSes and programs made for one machine (e.g. an ARM board) on a different machine (e.g. your x86 PC). By using dynamic translation, it achieves very good performance.<br />
<br />
QEMU can use other hypervisors like [[Xen]] or [[KVM]] to use CPU extensions ([[Wikipedia:Hardware-assisted virtualization|HVM]]) for virtualization. When used as a virtualizer, QEMU achieves near native performances by executing the guest code directly on the host CPU.<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|qemu}} package (or {{Pkg|qemu-headless}} for the version without GUI) and below optional packages for your needs:<br />
<br />
* {{Pkg|qemu-arch-extra}} - extra architectures support<br />
* {{Pkg|qemu-block-gluster}} - [[Glusterfs]] block support<br />
* {{Pkg|qemu-block-iscsi}} - [[iSCSI]] block support<br />
* {{Pkg|qemu-block-rbd}} - RBD block support <br />
* {{Pkg|samba}} - [[Samba|SMB/CIFS]] server support<br />
<br />
Alternatively, {{AUR|qemu-user-static}} exists as a usermode and static variant.<br />
<br />
=== QEMU variants ===<br />
<br />
QEMU is offered in several variants suited for different use cases.<br />
<br />
As a first classification, QEMU is offered in full-system and usermode emulation modes:<br />
<br />
; Full-system emulation<br />
: In this mode, QEMU emulates a full system, including one or several processors and various peripherals. It is more accurate but slower, and does not require the emulated OS to be Linux.<br />
: QEMU commands for full-system emulation are named {{ic|qemu-system-''target_architecture''}}, e.g. {{ic|qemu-system-x86_64}} for emulating intel 64-bit CPUs, {{ic|qemu-system-i386}} for intel 32 bits CPUs, {{ic|qemu-system-arm}} for ARM (32 bits), {{ic|qemu-system-aarch64}} for ARM64, etc.<br />
: If the target architecture matches the host CPU, this mode may still benefit from a significant speedup by using a hypervisor like [[#Enabling KVM|KVM]] or Xen.<br />
; [https://www.qemu.org/docs/master/user/main.html Usermode emulation]: In this mode, QEMU is able to invoke a Linux executable compiled for a (potentially) different architecture by leveraging the host system resources. There may be compatibility issues, e.g. some features may not be implemented, dynamically linked executables will not work out of the box (see [[#Chrooting into arm/arm64 environment from x86_64|the section below]] to address this) and only Linux is supported (although [https://wiki.winehq.org/Emulation Wine may be used] for running Windows executables).<br />
: QEMU commands for usermode emulation are named {{ic|qemu-''target_architecture''}}, e.g. {{ic|qemu-x86_64}} for emulating intel 64-bit CPUs.<br />
<br />
QEMU is offered in dynamically-linked and statically-linked variants:<br />
<br />
; Dynamically-linked (default): {{ic|qemu-*}} commands depend on the host OS libraries, so executables are smaller.<br />
; Statically-linked: {{ic|qemu-*}} commands can be copied to any Linux system with the same architecture.<br />
<br />
In the case of Arch Linux, full-system emulation is offered as:<br />
<br />
; Non-headless (default): This variant enables GUI features that require additional dependencies (like SDL or GTK).<br />
; Headless: This is a slimmer variant that does not require GUI (this is suitable e.g. for servers).<br />
<br />
Note that headless and non-headless versions install commands with the same name (e.g. {{ic|qemu-system-x86_64}}) and thus cannot be both installed at the same time.<br />
<br />
=== Details on packages offered in Arch Linux ===<br />
<br />
* The {{Pkg|qemu}} package provides the {{ic|x86_64}} architecture emulators for full-system emulation ({{ic|qemu-system-x86_64}}). The {{Pkg|qemu-arch-extra}} package provides the {{ic|x86_64}} usermode variant ({{ic|qemu-x86_64}}) and also for the rest of supported architectures it includes both full-system and usermode variants (e.g. {{ic|qemu-system-arm}} and {{ic|qemu-arm}}).<br />
* The headless versions of these packages (only applicable to full-system emulation) are {{Pkg|qemu-headless}} ({{ic|x86_64}}-only) and {{Pkg|qemu-headless-arch-extra}} (rest of architectures).<br />
* Full-system emulation can be expanded with some QEMU modules present in separate packages: {{Pkg|qemu-block-gluster}}, {{Pkg|qemu-block-iscsi}}, {{Pkg|qemu-block-rbd}} and {{Pkg|qemu-guest-agent}}.<br />
* The unofficial AUR package {{AUR|qemu-user-static}} provides a usermode and static variant for all target architectures supported by QEMU. A precompiled version of this package exists: {{AUR|qemu-user-static-bin}}. The installed QEMU commands are named {{ic|qemu-''target_architecture''-static}}, for example, {{ic|qemu-x86_64-static}} for intel 64-bit CPUs.<br />
<br />
{{Note|At present, Arch does not offer a full-system mode and statically linked variant (neither officially nor via AUR), as this is usually not needed.}}<br />
<br />
== Graphical front-ends for QEMU ==<br />
<br />
Unlike other virtualization programs such as [[VirtualBox]] and [[VMware]], QEMU does not provide a GUI to manage virtual machines (other than the window that appears when running a virtual machine), nor does it provide a way to create persistent virtual machines with saved settings. All parameters to run a virtual machine must be specified on the command line at every launch, unless you have created a custom script to start your virtual machine(s).<br />
<br />
[[Libvirt]] provides a convenient way to manage QEMU virtual machines. See [[Libvirt#Client|list of libvirt clients]] for available front-ends.<br />
<br />
Other GUI front-ends for QEMU:<br />
<br />
* {{App|AQEMU|QEMU GUI written in Qt5.|https://github.com/tobimensch/aqemu|{{AUR|aqemu}}}}<br />
<br />
== Creating new virtualized system ==<br />
<br />
=== Creating a hard disk image ===<br />
<br />
{{Accuracy|If I get the man page right the raw format only allocates the full size if the filesystem does not support "holes" or it is <br />
explicitly told to preallocate. See man qemu-img in section Notes.}} <br />
<br />
{{Tip|See [[Wikibooks:QEMU/Images]] for more information on QEMU images.}}<br />
<br />
To run QEMU you will need a hard disk image, unless you are booting a live system from CD-ROM or the network (and not doing so to install an operating system to a hard disk image). A hard disk image is a file which stores the contents of the emulated hard disk.<br />
<br />
A hard disk image can be ''raw'', so that it is literally byte-by-byte the same as what the guest sees, and will always use the full capacity of the guest hard drive on the host. This method provides the least I/O overhead, but can waste a lot of space, as not-used space on the guest cannot be used on the host.<br />
<br />
Alternatively, the hard disk image can be in a format such as ''qcow2'' which only allocates space to the image file when the guest operating system actually writes to those sectors on its virtual hard disk. The image appears as the full size to the guest operating system, even though it may take up only a very small amount of space on the host system. This image format also supports QEMU snapshotting functionality (see [[#Creating and managing snapshots via the monitor console]] for details). However, using this format instead of ''raw'' will likely affect performance.<br />
<br />
QEMU provides the {{ic|qemu-img}} command to create hard disk images. For example to create a 4 GB image in the ''raw'' format:<br />
<br />
$ qemu-img create -f raw ''image_file'' 4G<br />
<br />
You may use {{ic|-f qcow2}} to create a ''qcow2'' disk instead.<br />
<br />
{{Note|You can also simply create a ''raw'' image by creating a file of the needed size using {{ic|dd}} or {{ic|fallocate}}.}}<br />
<br />
{{Warning|If you store the hard disk images on a [[Btrfs]] file system, you should consider disabling [[Btrfs#Copy-on-Write (CoW)|Copy-on-Write]] for the directory before creating any images.}}<br />
<br />
==== Overlay storage images ====<br />
<br />
You can create a storage image once (the 'backing' image) and have QEMU keep mutations to this image in an overlay image. This allows you to revert to a previous state of this storage image. You could revert by creating a new overlay image at the time you wish to revert, based on the original backing image.<br />
<br />
To create an overlay image, issue a command like:<br />
<br />
$ qemu-img create -o backing_file=''img1.raw'',backing_fmt=''raw'' -f ''qcow2'' ''img1.cow''<br />
<br />
After that you can run your QEMU VM as usual (see [[#Running virtualized system]]):<br />
<br />
$ qemu-system-x86_64 ''img1.cow''<br />
<br />
The backing image will then be left intact and mutations to this storage will be recorded in the overlay image file.<br />
<br />
When the path to the backing image changes, repair is required.<br />
<br />
{{Warning|The backing image's absolute filesystem path is stored in the (binary) overlay image file. Changing the backing image's path requires some effort.}}<br />
<br />
Make sure that the original backing image's path still leads to this image. If necessary, make a symbolic link at the original path to the new path. Then issue a command like:<br />
<br />
$ qemu-img rebase -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
At your discretion, you may alternatively perform an 'unsafe' rebase where the old path to the backing image is not checked:<br />
<br />
$ qemu-img rebase -u -b ''/new/img1.raw'' ''/new/img1.cow''<br />
<br />
==== Resizing an image ====<br />
<br />
{{Warning|Resizing an image containing an NTFS boot file system could make the operating system installed on it unbootable. It is recommended to create a backup first.}}<br />
<br />
The {{ic|qemu-img}} executable has the {{ic|resize}} option, which enables easy resizing of a hard drive image. It works for both ''raw'' and ''qcow2''. For example, to increase image space by 10 GB, run:<br />
<br />
$ qemu-img resize ''disk_image'' +10G<br />
<br />
After enlarging the disk image, you must use file system and partitioning tools inside the virtual machine to actually begin using the new space. When shrinking a disk image, you must '''first reduce the allocated file systems and partition sizes''' using the file system and partitioning tools inside the virtual machine and then shrink the disk image accordingly, otherwise shrinking the disk image will result in data loss! For a Windows guest, open the "create and format hard disk partitions" control panel.<br />
<br />
==== Converting an image ====<br />
<br />
You can convert an image to other formats using {{ic|qemu-img convert}}. This example shows how to convert a ''raw'' image to ''qcow2'':<br />
<br />
$ qemu-img convert -f raw -O qcow2 ''input''.img ''output''.qcow2<br />
<br />
This will not remove the original input file.<br />
<br />
=== Preparing the installation media ===<br />
<br />
To install an operating system into your disk image, you need the installation medium (e.g. optical disk, USB-drive, or ISO image) for the operating system. The installation medium should not be mounted because QEMU accesses the media directly.<br />
<br />
{{Tip|If using an optical disk, it is a good idea to first dump the media to a file because this both improves performance and does not require you to have direct access to the devices (that is, you can run QEMU as a regular user without having to change access permissions on the media's device file). For example, if the CD-ROM device node is named {{ic|/dev/cdrom}}, you can dump it to a file with the command: {{bc|1=$ dd if=/dev/cdrom of=''cd_image.iso'' bs=4k}}}}<br />
<br />
=== Installing the operating system ===<br />
<br />
This is the first time you will need to start the emulator. To install the operating system on the disk image, you must attach both the disk image and the installation media to the virtual machine, and have it boot from the installation media.<br />
<br />
For example on i386 guests, to install from a bootable ISO file as CD-ROM and a raw disk image:<br />
<br />
$ qemu-system-x86_64 -cdrom ''iso_image'' -boot order=d -drive file=''disk_image'',format=raw<br />
<br />
See {{man|1|qemu}} for more information about loading other media types (such as floppy, disk images or physical drives) and [[#Running virtualized system]] for other useful options.<br />
<br />
After the operating system has finished installing, the QEMU image can be booted directly (see [[#Running virtualized system]]).<br />
<br />
{{Note|By default only 128 MB of memory is assigned to the machine. The amount of memory can be adjusted with the {{ic|-m}} switch, for example {{ic|-m 512M}} or {{ic|-m 2G}}.}}<br />
<br />
{{Tip|<br />
* Instead of specifying {{ic|1=-boot order=x}}, some users may feel more comfortable using a boot menu: {{ic|1=-boot menu=on}}, at least during configuration and experimentation.<br />
* When running QEMU in headless mode, it starts a local VNC server on port 5900 per default. You can use [[TigerVNC]] to connect to the guest OS: {{ic|vncviewer :5900}}<br />
* If you need to replace floppies or CDs as part of the installation process, you can use the QEMU machine monitor (press {{ic|Ctrl+Alt+2}} in the virtual machine's window) to remove and attach storage devices to a virtual machine. Type {{ic|info block}} to see the block devices, and use the {{ic|change}} command to swap out a device. Press {{ic|Ctrl+Alt+1}} to go back to the virtual machine.<br />
}}<br />
<br />
== Running virtualized system ==<br />
<br />
{{ic|qemu-system-*}} binaries (for example {{ic|qemu-system-i386}} or {{ic|qemu-system-x86_64}}, depending on guest's architecture) are used to run the virtualized guest. The usage is:<br />
<br />
$ qemu-system-x86_64 ''options'' ''disk_image''<br />
<br />
Options are the same for all {{ic|qemu-system-*}} binaries, see {{man|1|qemu}} for documentation of all options.<br />
<br />
By default, QEMU will show the virtual machine's video output in a window. One thing to keep in mind: when you click inside the QEMU window, the mouse pointer is grabbed. To release it, press {{ic|Ctrl+Alt+g}}.<br />
<br />
{{Warning|QEMU should never be run as root. If you must launch it in a script as root, you should use the {{ic|-runas}} option to make QEMU drop root privileges.}}<br />
<br />
=== Enabling KVM ===<br />
<br />
KVM (''Kernel-based Virtual Machine'') full virtualization must be supported by your Linux kernel and your hardware, and necessary [[kernel modules]] must be loaded. See [[KVM]] for more information.<br />
<br />
To start QEMU in KVM mode, append {{ic|-enable-kvm}} to the additional start options. To check if KVM is enabled for a running VM, enter the [[#QEMU monitor]] and type {{ic|info kvm}}.<br />
<br />
{{Note|<br />
* The argument {{ic|1=accel=kvm}} of the {{ic|-machine}} option is equivalent to the {{ic|-enable-kvm}} or the {{ic|-accel kvm}} option.<br />
* CPU model {{ic|host}} requires KVM<br />
* If you start your VM with a GUI tool and experience very bad performance, you should check for proper KVM support, as QEMU may be falling back to software emulation.<br />
* KVM needs to be enabled in order to start Windows 7 and Windows 8 properly without a ''blue screen''.<br />
}}<br />
<br />
=== Enabling IOMMU (Intel VT-d/AMD-Vi) support ===<br />
<br />
First enable IOMMU, see [[PCI passthrough via OVMF#Setting up IOMMU]].<br />
<br />
Add {{ic|-device intel-iommu}} to create the IOMMU device:<br />
<br />
$ qemu-system-x86_64 '''-enable-kvm -machine q35 -device intel-iommu''' -cpu host ..<br />
<br />
{{Note|<br />
On Intel CPU based systems creating an IOMMU device in a QEMU guest with {{ic|-device intel-iommu}} will disable PCI passthrough with an error like: {{bc|Device at bus pcie.0 addr 09.0 requires iommu notifier which is currently not supported by intel-iommu emulation}} While adding the kernel parameter {{ic|1=intel_iommu=on}} is still needed for remapping IO (e.g. [[PCI passthrough via OVMF#Isolating the GPU|PCI passthrough with vfio-pci]]), {{ic|-device intel-iommu}} should not be set if PCI PCI passthrough is required.<br />
}}<br />
<br />
== Sharing data between host and guest ==<br />
<br />
=== Network ===<br />
<br />
Data can be shared between the host and guest OS using any network protocol that can transfer files, such as [[NFS]], [[SMB]], [[Wikipedia:Network block device|NBD]], HTTP, [[Very Secure FTP Daemon|FTP]], or [[SSH]], provided that you have set up the network appropriately and enabled the appropriate services.<br />
<br />
The default user-mode networking allows the guest to access the host OS at the IP address 10.0.2.2. Any servers that you are running on your host OS, such as a SSH server or SMB server, will be accessible at this IP address. So on the guests, you can mount directories exported on the host via [[SMB]] or [[NFS]], or you can access the host's HTTP server, etc.<br />
It will not be possible for the host OS to access servers running on the guest OS, but this can be done with other network configurations (see [[#Tap networking with QEMU]]).<br />
<br />
=== QEMU's port forwarding ===<br />
<br />
QEMU can forward ports from the host to the guest to enable e.g. connecting from the host to an SSH server running on the guest.<br />
<br />
For example, to bind port 10022 on the host with port 22 (SSH) on the guest, start QEMU with a command like:<br />
<br />
$ qemu-system-x86_64 ''disk_image'' -nic user,hostfwd=tcp::10022-:22<br />
<br />
Make sure the sshd is running on the guest and connect with:<br />
<br />
$ ssh ''guest-user''@localhost -p 10022<br />
<br />
You can use [[SSHFS]] to mount the guest's file system at the host for shared read and write access.<br />
<br />
=== QEMU's built-in SMB server ===<br />
<br />
QEMU's documentation says it has a "built-in" SMB server, but actually it just starts up [[Samba]] on the host with an automatically generated {{ic|smb.conf}} file located in {{ic|/tmp/qemu-smb.''random_string''}} and makes it accessible to the guest at a different IP address (10.0.2.4 by default). This only works for user networking, and is useful when you do not want to start the normal [[Samba]] service on the host, which the guest can also access if you have set up shares on it.<br />
<br />
Only a single directory can be set as shared with the option {{ic|1=smb=}}, but adding more directories (even while the virtual machine is running) could be as easy as creating symbolic links in the shared directory if QEMU configured SMB to follow symbolic links. It does not do so, but the configuration of the running SMB server can be changed as described below.<br />
<br />
''Samba'' must be installed on the host. To enable this feature, start QEMU with a command like:<br />
<br />
$ qemu-system-x86_64 ''disk_image'' -net nic -net user,smb=''shared_dir_path''<br />
<br />
where {{ic|''shared_dir_path''}} is a directory that you want to share between the guest and host.<br />
<br />
Then, in the guest, you will be able to access the shared directory on the host 10.0.2.4 with the share name "qemu". For example, in Windows Explorer you would go to {{ic|\\10.0.2.4\qemu}}.<br />
<br />
{{Note|<br />
* If you are using sharing options multiple times like {{ic|1=-net user,smb=''shared_dir_path1'' -net user,smb=''shared_dir_path2''}} or {{ic|1=-net user,smb=''shared_dir_path1'',smb=''shared_dir_path2''}} then it will share only the last defined one.<br />
* If you cannot access the shared folder and the guest system is Windows, check that the [http://ecross.mvps.org/howto/enable-netbios-over-tcp-ip-with-windows.htm NetBIOS protocol is enabled] and that a firewall does not block [https://technet.microsoft.com/en-us/library/cc940063.aspx ports] used by the NetBIOS protocol.<br />
* If you cannot access the shared folder and the guest system is Windows 10 Enterprise or Education or Windows Server 2016, [https://support.microsoft.com/en-us/help/4046019 enable guest access].<br />
}}<br />
<br />
One way to share multiple directories and to add or remove them while the virtual machine is running, is to share an empty directory and create/remove symbolic links to the directories in the shared directory. For this to work, the configuration of the running SMB server can be changed with the following script, which also allows the execution of files on the guest that are not set executable on the host:<br />
<br />
#!/bin/bash<br />
eval $(ps h -C smbd -o pid,args | grep /tmp/qemu-smb | gawk '{print "pid="$1";conf="$6}')<br />
echo "[global]<br />
allow insecure wide links = yes<br />
[qemu]<br />
follow symlinks = yes<br />
wide links = yes<br />
acl allow execute always = yes" >> $conf<br />
# in case the change is not detected automatically:<br />
smbcontrol --configfile=$conf $pid reload-config<br />
<br />
This can be applied to the running server started by qemu only after the guest has connected to the network drive the first time. An alternative to this method is to add additional shares to the configuration file like so:<br />
<br />
echo "[''myshare'']<br />
path=''another_path''<br />
read only=no<br />
guest ok=yes<br />
force user=''username''" >> $conf<br />
<br />
This share will be available on the guest as {{ic|\\10.0.2.4\''myshare''}}.<br />
<br />
=== Using filesystem passthrough and VirtFS ===<br />
<br />
See the [https://wiki.qemu.org/Documentation/9psetup QEMU documentation].<br />
<br />
=== Mounting a partition of the guest on the host ===<br />
<br />
It can be useful to mount a drive image under the host system, it can be a way to transfer files in and out of the guest. This should be done when the virtual machine is not running.<br />
<br />
The procedure to mount the drive on the host depends on the type of qemu image, ''raw'' or ''qcow2''. We detail thereafter the steps to mount a drive in the two formats in [[#Mounting a partition from a raw image]] and [[#Mounting a partition from a qcow2 image]]. For the full documentation see [[Wikibooks:QEMU/Images#Mounting an image on the host]].<br />
<br />
{{Warning|You must make sure to unmount the partitions before running the virtual machine again. Otherwise, data corruption is very likely to occur.}}<br />
<br />
==== Mounting a partition from a raw image ====<br />
<br />
It is possible to mount partitions that are inside a raw disk image file by setting them up as loopback devices.<br />
<br />
===== With manually specifying byte offset =====<br />
<br />
One way to mount a disk image partition is to mount the disk image at a certain offset using a command like the following:<br />
<br />
# mount -o loop,offset=32256 ''disk_image'' ''mountpoint''<br />
<br />
The {{ic|1=offset=32256}} option is actually passed to the {{ic|losetup}} program to set up a loopback device that starts at byte offset 32256 of the file and continues to the end. This loopback device is then mounted. You may also use the {{ic|sizelimit}} option to specify the exact size of the partition, but this is usually unnecessary.<br />
<br />
Depending on your disk image, the needed partition may not start at offset 32256. Run {{ic|fdisk -l ''disk_image''}} to see the partitions in the image. fdisk gives the start and end offsets in 512-byte sectors, so multiply by 512 to get the correct offset to pass to {{ic|mount}}.<br />
<br />
===== With loop module autodetecting partitions =====<br />
<br />
The Linux loop driver actually supports partitions in loopback devices, but it is disabled by default. To enable it, do the following:<br />
<br />
* Get rid of all your loopback devices (unmount all mounted images, etc.).<br />
* [[Kernel_modules#Manual_module_handling|Unload]] the {{ic|loop}} kernel module, and load it with the {{ic|1=max_part=15}} parameter set. Additionally, the maximum number of loop devices can be controlled with the {{ic|max_loop}} parameter.<br />
<br />
{{Tip|You can put an entry in {{ic|/etc/modprobe.d}} to load the loop module with {{ic|1=max_part=15}} every time, or you can put {{ic|1=loop.max_part=15}} on the kernel command-line, depending on whether you have the {{ic|loop.ko}} module built into your kernel or not.}}<br />
<br />
Set up your image as a loopback device:<br />
<br />
# losetup -f -P ''disk_image''<br />
<br />
Then, if the device created was {{ic|/dev/loop0}}, additional devices {{ic|/dev/loop0pX}} will have been automatically created, where X is the number of the partition. These partition loopback devices can be mounted directly. For example:<br />
<br />
# mount /dev/loop0p1 ''mountpoint''<br />
<br />
To mount the disk image with ''udisksctl'', see [[Udisks#Mount loop devices]].<br />
<br />
===== With kpartx =====<br />
<br />
'''kpartx''' from the {{Pkg|multipath-tools}} package can read a partition table on a device and create a new device for each partition. For example:<br />
<br />
# kpartx -a ''disk_image''<br />
<br />
This will setup the loopback device and create the necessary partition(s) device(s) in {{ic|/dev/mapper/}}.<br />
<br />
==== Mounting a partition from a qcow2 image ====<br />
<br />
We will use {{ic|qemu-nbd}}, which lets use the NBD (''network block device'') protocol to share the disk image.<br />
<br />
First, we need the ''nbd'' module loaded:<br />
<br />
# modprobe nbd max_part=16<br />
<br />
Then, we can share the disk and create the device entries:<br />
<br />
# qemu-nbd -c /dev/nbd0 ''/path/to/image.qcow2''<br />
<br />
Discover the partitions:<br />
<br />
# partprobe /dev/nbd0<br />
<br />
''fdisk'' can be used to get information regarding the different partitions in {{{ic|''nbd0''}}:<br />
<br />
{{hc|# fdisk -l /dev/nbd0|2=<br />
Disk /dev/nbd0: 25.2 GiB, 27074281472 bytes, 52879456 sectors<br />
Units: sectors of 1 * 512 = 512 bytes<br />
Sector size (logical/physical): 512 bytes / 512 bytes<br />
I/O size (minimum/optimal): 512 bytes / 512 bytes<br />
Disklabel type: dos<br />
Disk identifier: 0xa6a4d542<br />
<br />
Device Boot Start End Sectors Size Id Type<br />
/dev/nbd0p1 * 2048 1026047 1024000 500M 7 HPFS/NTFS/exFAT<br />
/dev/nbd0p2 1026048 52877311 51851264 24.7G 7 HPFS/NTFS/exFAT}}<br />
<br />
Then mount any partition of the drive image, for example the partition 2:<br />
<br />
# mount /dev/nbd0'''p2''' ''mountpoint''<br />
<br />
After the usage, it is important to unmount the image and reverse previous steps, i.e. unmount the partition and disconnect the nbd device:<br />
<br />
# umount ''mountpoint''<br />
# qemu-nbd -d /dev/nbd0<br />
<br />
=== Using any real partition as the single primary partition of a hard disk image ===<br />
<br />
Sometimes, you may wish to use one of your system partitions from within QEMU. Using a raw partition for a virtual machine will improve performance, as the read and write operations do not go through the file system layer on the physical host. Such a partition also provides a way to share data between the host and guest.<br />
<br />
In Arch Linux, device files for raw partitions are, by default, owned by ''root'' and the ''disk'' group. If you would like to have a non-root user be able to read and write to a raw partition, you must either change the owner of the partition's device file to that user, add that user to the ''disk'' group, or use [[ACL]] for more fine-grained access control.<br />
<br />
{{Warning|<br />
* Although it is possible, it is not recommended to allow virtual machines to alter critical data on the host system, such as the root partition.<br />
* You must not mount a file system on a partition read-write on both the host and the guest at the same time. Otherwise, data corruption will result.<br />
}}<br />
<br />
After doing so, you can attach the partition to a QEMU virtual machine as a virtual disk.<br />
<br />
However, things are a little more complicated if you want to have the ''entire'' virtual machine contained in a partition. In that case, there would be no disk image file to actually boot the virtual machine since you cannot install a bootloader to a partition that is itself formatted as a file system and not as a partitioned device with an MBR. Such a virtual machine can be booted either by specifying the [[kernel]] and [[initrd]] manually, or by simulating a disk with an MBR by using the [https://www.kernel.org/doc/html/latest/admin-guide/device-mapper/index.html Device-mapper], linear [[RAID]], or a [https://www.kernel.org/doc/html/latest/admin-guide/blockdev/nbd.html Linux Network Block Device].<br />
<br />
==== By specifying kernel and initrd manually ====<br />
<br />
QEMU supports loading [[Kernels|Linux kernels]] and [[initramfs|init ramdisks]] directly, thereby circumventing bootloaders such as [[GRUB]]. It then can be launched with the physical partition containing the root file system as the virtual disk, which will not appear to be partitioned. This is done by issuing a command similar to the following:<br />
<br />
{{Note|In this example, it is the '''host's''' images that are being used, not the guest's. If you wish to use the guest's images, either mount {{ic|/dev/sda3}} read-only (to protect the file system from the host) and specify the {{ic|/full/path/to/images}} or use some kexec hackery in the guest to reload the guest's kernel (extends boot time). }}<br />
<br />
$ qemu-system-x86_64 -kernel /boot/vmlinuz-linux -initrd /boot/initramfs-linux.img -append root=/dev/sda /dev/sda3<br />
<br />
In the above example, the physical partition being used for the guest's root file system is {{ic|/dev/sda3}} on the host, but it shows up as {{ic|/dev/sda}} on the guest.<br />
<br />
You may, of course, specify any kernel and initrd that you want, and not just the ones that come with Arch Linux.<br />
<br />
When there are multiple [[kernel parameters]] to be passed to the {{ic|-append}} option, they need to be quoted using single or double quotes. For example:<br />
<br />
... -append 'root=/dev/sda1 console=ttyS0'<br />
<br />
==== Simulate a virtual disk with MBR ====<br />
<br />
A more complicated way to have a virtual machine use a physical partition, while keeping that partition formatted as a file system and not just having the guest partition the partition as if it were a disk, is to simulate an MBR for it so that it can boot using a bootloader such as GRUB.<br />
<br />
For the following, suppose you have a plain, unmounted {{ic|/dev/hda''N''}} partition with some file system on it you wish to make part of a QEMU disk image. The trick is to dynamically prepend a master boot record (MBR) to the real partition you wish to embed in a QEMU raw disk image. More generally, the partition can be any part of a larger simulated disk, in particular a block device that simulates the original physical disk but only exposes {{ic|/dev/hda''N''}} to the virtual machine.<br />
<br />
A virtual disk of this type can be represented by a VMDK file that contains references to (a copy of) the MBR and the partition, but QEMU does not support this VMDK format. For instance, a virtual disk [https://www.virtualbox.org/manual/ch09.html#rawdisk created by]<br />
<br />
$ VBoxManage internalcommands createrawvmdk -filename ''/path/to/file.vmdk'' -rawdisk /dev/hda<br />
<br />
will be rejected by QEMU with the error message<br />
<br />
Unsupported image type 'partitionedDevice'<br />
<br />
Note that {{ic|VBoxManage}} creates two files, {{ic|''file.vmdk''}} and {{ic|''file-pt.vmdk''}}, the latter being a copy of the MBR, to which the text file {{ic|file.vmdk}} points. Read operations outside the target partition or the MBR would give zeros, while written data would be discarded.<br />
<br />
===== Device Mapper =====<br />
<br />
A method that is similar to the use of a VMDK descriptor file uses the device mapper to prepend a loop device attached to the MBR file to the target partition. In case we do not need our virtual disk to have the same size as the original, we first create a file to hold the MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=2048<br />
<br />
Here, a 1 MB (2048 * 512 bytes) file is created in accordance with partition alignment policies used by modern disk partitioning tools. For compatibility with older partitioning software, 63 sectors instead of 2048 might be required. The MBR only needs a single 512 bytes block, the additional free space can be used for a BIOS boot partition and, in the case of a hybrid partitioning scheme, for a GUID Partition Table. Then, we attach a loop device to the MBR file:<br />
<br />
# losetup --show -f ''/path/to/mbr''<br />
/dev/loop0<br />
<br />
In this example, the resulting device is {{ic|/dev/loop0}}. The device mapper is now used to join the MBR and the partition:<br />
<br />
# echo "0 2048 linear /dev/loop0 0<br />
2048 `blockdev --getsz /dev/hda''N''` linear /dev/hda''N'' 0" | dmsetup create qemu<br />
<br />
The resulting {{ic|/dev/mapper/qemu}} is what we will use as a QEMU raw disk image. Additional steps are required to create a partition table (see the section that describes the use of a linear RAID for an example) and boot loader code on the virtual disk (which will be stored in {{ic|''/path/to/mbr''}}).<br />
<br />
The following setup is an example where the position of {{ic|/dev/hda''N''}} on the virtual disk is to be the same as on the physical disk and the rest of the disk is hidden, except for the MBR, which is provided as a copy:<br />
<br />
# dd if=/dev/hda count=1 of=''/path/to/mbr''<br />
# loop=`losetup --show -f ''/path/to/mbr''`<br />
# start=`blockdev --report /dev/hda''N'' | tail -1 | awk '{print $5}'`<br />
# size=`blockdev --getsz /dev/hda''N''`<br />
# disksize=`blockdev --getsz /dev/hda`<br />
# echo "0 1 linear $loop 0<br />
1 $((start-1)) zero<br />
$start $size linear /dev/hda''N'' 0<br />
$((start+size)) $((disksize-start-size)) zero" | dmsetup create qemu<br />
<br />
The table provided as standard input to {{ic|dmsetup}} has a similar format as the table in a VDMK descriptor file produced by {{ic|VBoxManage}} and can alternatively be loaded from a file with {{ic|dmsetup create qemu --table ''table_file''}}. To the virtual machine, only {{ic|/dev/hda''N''}} is accessible, while the rest of the hard disk reads as zeros and discards written data, except for the first sector. We can print the table for {{ic|/dev/mapper/qemu}} with {{ic|dmsetup table qemu}} (use {{ic|udevadm info -rq name /sys/dev/block/''major'':''minor''}} to translate {{ic|''major'':''minor''}} to the corresponding {{ic|/dev/''blockdevice''}} name). Use {{ic|dmsetup remove qemu}} and {{ic|losetup -d $loop}} to delete the created devices.<br />
<br />
A situation where this example would be useful is an existing Windows XP installation in a multi-boot configuration and maybe a hybrid partitioning scheme (on the physical hardware, Windows XP could be the only operating system that uses the MBR partition table, while more modern operating systems installed on the same computer could use the GUID Partition Table). Windows XP supports hardware profiles, so that that the same installation can be used with different hardware configurations alternatingly (in this case bare metal vs. virtual) with Windows needing to install drivers for newly detected hardware only once for every profile. Note that in this example the boot loader code in the copied MBR needs to be updated to directly load Windows XP from {{ic|/dev/hda''N''}} instead of trying to start the multi-boot capable boot loader (like GRUB) present in the original system. Alternatively, a copy of the boot partition containing the boot loader installation can be included in the virtual disk the same way as the MBR.<br />
<br />
===== Linear RAID =====<br />
<br />
You can also do this using software [[RAID]] in linear mode (you need the {{ic|linear.ko}} kernel driver) and a loopback device: <br />
<br />
First, you create some small file to hold the MBR:<br />
<br />
$ dd if=/dev/zero of=''/path/to/mbr'' count=32<br />
<br />
Here, a 16 KB (32 * 512 bytes) file is created. It is important not to make it too small (even if the MBR only needs a single 512 bytes block), since the smaller it will be, the smaller the chunk size of the software RAID device will have to be, which could have an impact on performance. Then, you setup a loopback device to the MBR file:<br />
<br />
# losetup -f ''/path/to/mbr''<br />
<br />
Let us assume the resulting device is {{ic|/dev/loop0}}, because we would not already have been using other loopbacks. Next step is to create the "merged" MBR + {{ic|/dev/hda''N''}} disk image using software RAID:<br />
<br />
# modprobe linear<br />
# mdadm --build --verbose /dev/md0 --chunk=16 --level=linear --raid-devices=2 /dev/loop0 /dev/hda''N''<br />
<br />
The resulting {{ic|/dev/md0}} is what you will use as a QEMU raw disk image (do not forget to set the permissions so that the emulator can access it). The last (and somewhat tricky) step is to set the disk configuration (disk geometry and partitions table) so that the primary partition start point in the MBR matches the one of {{ic|/dev/hda''N''}} inside {{ic|/dev/md0}} (an offset of exactly 16 * 512 = 16384 bytes in this example). Do this using {{ic|fdisk}} on the host machine, not in the emulator: the default raw disc detection routine from QEMU often results in non-kilobyte-roundable offsets (such as 31.5 KB, as in the previous section) that cannot be managed by the software RAID code. Hence, from the the host:<br />
<br />
# fdisk /dev/md0<br />
<br />
Press {{ic|X}} to enter the expert menu. Set number of 's'ectors per track so that the size of one cylinder matches the size of your MBR file. For two heads and a sector size of 512, the number of sectors per track should be 16, so we get cylinders of size 2x16x512=16k.<br />
<br />
Now, press {{ic|R}} to return to the main menu.<br />
<br />
Press {{ic|P}} and check that the cylinder size is now 16k.<br />
<br />
Now, create a single primary partition corresponding to {{ic|/dev/hda''N''}}. It should start at cylinder 2 and end at the end of the disk (note that the number of cylinders now differs from what it was when you entered fdisk.<br />
<br />
Finally, 'w'rite the result to the file: you are done. You now have a partition you can mount directly from your host, as well as part of a QEMU disk image:<br />
<br />
$ qemu-system-x86_64 -hdc /dev/md0 ''[...]''<br />
<br />
You can, of course, safely set any bootloader on this disk image using QEMU, provided the original {{ic|/dev/hda''N''}} partition contains the necessary tools.<br />
<br />
===== Network Block Device =====<br />
<br />
Instead of the methods decribed above, you may use {{ic|nbd-server}} (from the {{pkg|nbd}} package) to create an MBR wrapper for QEMU.<br />
<br />
Assuming you have already set up your MBR wrapper file like above, rename it to {{ic|wrapper.img.0}}. Then create a symbolic link named {{ic|wrapper.img.1}} in the same directory, pointing to your partition. Then put the following script in the same directory:<br />
<br />
#!/bin/sh<br />
dir="$(realpath "$(dirname "$0")")"<br />
cat >wrapper.conf <<EOF<br />
[generic]<br />
allowlist = true<br />
listenaddr = 127.713705<br />
port = 10809<br />
<br />
[wrap]<br />
exportname = $dir/wrapper.img<br />
multifile = true<br />
EOF<br />
<br />
nbd-server \<br />
-C wrapper.conf \<br />
-p wrapper.pid \<br />
"$@"<br />
<br />
The {{ic|.0}} and {{ic|.1}} suffixes are essential; the rest can be changed. After running the above script (which you may need to do as root to make sure nbd-server is able to access the partition), you can launch QEMU with:<br />
<br />
qemu-system-x86_64 -drive file=nbd:127.713705:10809:exportname=wrap ''[...]''<br />
<br />
== Networking ==<br />
<br />
{{Style|Network topologies (sections [[#Host-only networking]], [[#Internal networking]] and info spread out across other sections) should not be described alongside the various virtual interfaces implementations, such as [[#User-mode networking]], [[#Tap networking with QEMU]], [[#Networking with VDE2]].}}<br />
<br />
The performance of virtual networking should be better with tap devices and bridges than with user-mode networking or vde because tap devices and bridges are implemented in-kernel.<br />
<br />
In addition, networking performance can be improved by assigning virtual machines a [http://wiki.libvirt.org/page/Virtio virtio] network device rather than the default emulation of an e1000 NIC. See [[#Installing virtio drivers]] for more information.<br />
<br />
=== Link-level address caveat ===<br />
<br />
By giving the {{ic|-net nic}} argument to QEMU, it will, by default, assign a virtual machine a network interface with the link-level address {{ic|52:54:00:12:34:56}}. However, when using bridged networking with multiple virtual machines, it is essential that each virtual machine has a unique link-level (MAC) address on the virtual machine side of the tap device. Otherwise, the bridge will not work correctly, because it will receive packets from multiple sources that have the same link-level address. This problem occurs even if the tap devices themselves have unique link-level addresses because the source link-level address is not rewritten as packets pass through the tap device.<br />
<br />
Make sure that each virtual machine has a unique link-level address, but it should always start with {{ic|52:54:}}. Use the following option, replace ''X'' with arbitrary hexadecimal digit:<br />
<br />
$ qemu-system-x86_64 -net nic,macaddr=52:54:''XX:XX:XX:XX'' -net vde ''disk_image''<br />
<br />
Generating unique link-level addresses can be done in several ways:<br />
<br />
* Manually specify unique link-level address for each NIC. The benefit is that the DHCP server will assign the same IP address each time the virtual machine is run, but it is unusable for large number of virtual machines.<br />
* Generate random link-level address each time the virtual machine is run. Practically zero probability of collisions, but the downside is that the DHCP server will assign a different IP address each time. You can use the following command in a script to generate random link-level address in a {{ic|macaddr}} variable:<br />
<br />
{{bc|1=<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
qemu-system-x86_64 -net nic,macaddr="$macaddr" -net vde ''disk_image''<br />
}}<br />
<br />
* Use the following script {{ic|qemu-mac-hasher.py}} to generate the link-level address from the virtual machine name using a hashing function. Given that the names of virtual machines are unique, this method combines the benefits of the aforementioned methods: it generates the same link-level address each time the script is run, yet it preserves the practically zero probability of collisions.<br />
<br />
{{hc|qemu-mac-hasher.py|<nowiki><br />
#!/usr/bin/env python<br />
<br />
import sys<br />
import zlib<br />
<br />
if len(sys.argv) != 2:<br />
print("usage: %s <VM Name>" % sys.argv[0])<br />
sys.exit(1)<br />
<br />
crc = zlib.crc32(sys.argv[1].encode("utf-8")) & 0xffffffff<br />
crc = str(hex(crc))[2:]<br />
print("52:54:%s%s:%s%s:%s%s:%s%s" % tuple(crc))<br />
</nowiki>}}<br />
<br />
In a script, you can use for example:<br />
<br />
vm_name="''VM Name''"<br />
qemu-system-x86_64 -name "$vm_name" -net nic,macaddr=$(qemu-mac-hasher.py "$vm_name") -net vde ''disk_image''<br />
<br />
=== User-mode networking ===<br />
<br />
By default, without any {{ic|-netdev}} arguments, QEMU will use user-mode networking with a built-in DHCP server. Your virtual machines will be assigned an IP address when they run their DHCP client, and they will be able to access the physical host's network through IP masquerading done by QEMU.<br />
<br />
{{warning|This only works with the TCP and UDP protocols, so ICMP, including {{ic|ping}}, will not work. Do not use {{ic|ping}} to test network connectivity. To make ping work in the guest see [[Sysctl#Allow unprivileged users to create IPPROTO_ICMP sockets]].}}<br />
<br />
This default configuration allows your virtual machines to easily access the Internet, provided that the host is connected to it, but the virtual machines will not be directly visible on the external network, nor will virtual machines be able to talk to each other if you start up more than one concurrently.<br />
<br />
QEMU's user-mode networking can offer more capabilities such as built-in TFTP or SMB servers, redirecting host ports to the guest (for example to allow SSH connections to the guest) or attaching guests to VLANs so that they can talk to each other. See the QEMU documentation on the {{ic|-net user}} flag for more details.<br />
<br />
However, user-mode networking has limitations in both utility and performance. More advanced network configurations require the use of tap devices or other methods.<br />
<br />
{{Note|If the host system uses [[systemd-networkd]], make sure to symlink the {{ic|/etc/resolv.conf}} file as described in [[systemd-networkd#Required services and setup]], otherwise the DNS lookup in the guest system will not work.}}<br />
<br />
=== Tap networking with QEMU ===<br />
<br />
[[wikipedia:TUN/TAP|Tap devices]] are a Linux kernel feature that allows you to create virtual network interfaces that appear as real network interfaces. Packets sent to a tap interface are delivered to a userspace program, such as QEMU, that has bound itself to the interface.<br />
<br />
QEMU can use tap networking for a virtual machine so that packets sent to the tap interface will be sent to the virtual machine and appear as coming from a network interface (usually an Ethernet interface) in the virtual machine. Conversely, everything that the virtual machine sends through its network interface will appear on the tap interface.<br />
<br />
Tap devices are supported by the Linux bridge drivers, so it is possible to bridge together tap devices with each other and possibly with other host interfaces such as {{ic|eth0}}. This is desirable if you want your virtual machines to be able to talk to each other, or if you want other machines on your LAN to be able to talk to the virtual machines.<br />
<br />
{{Warning|If you bridge together tap device and some host interface, such as {{ic|eth0}}, your virtual machines will appear directly on the external network, which will expose them to possible attack. Depending on what resources your virtual machines have access to, you may need to take all the [[Firewalls|precautions]] you normally would take in securing a computer to secure your virtual machines. If the risk is too great, virtual machines have little resources or you set up multiple virtual machines, a better solution might be to use [[#Host-only networking|host-only networking]] and set up NAT. In this case you only need one firewall on the host instead of multiple firewalls for each guest.}}<br />
<br />
As indicated in the user-mode networking section, tap devices offer higher networking performance than user-mode. If the guest OS supports virtio network driver, then the networking performance will be increased considerably as well. Supposing the use of the tap0 device, that the virtio driver is used on the guest, and that no scripts are used to help start/stop networking, next is part of the qemu command one should see:<br />
<br />
-device virtio-net,netdev=network0 -netdev tap,id=network0,ifname=tap0,script=no,downscript=no<br />
<br />
But if already using a tap device with virtio networking driver, one can even boost the networking performance by enabling vhost, like:<br />
<br />
-device virtio-net,netdev=network0 -netdev tap,id=network0,ifname=tap0,script=no,downscript=no,vhost=on<br />
<br />
See [https://web.archive.org/web/20160222161955/http://www.linux-kvm.com:80/content/how-maximize-virtio-net-performance-vhost-net] for more information.<br />
<br />
==== Host-only networking ====<br />
<br />
If the bridge is given an IP address and traffic destined for it is allowed, but no real interface (e.g. {{ic|eth0}}) is connected to the bridge, then the virtual machines will be able to talk to each other and the host system. However, they will not be able to talk to anything on the external network, provided that you do not set up IP masquerading on the physical host. This configuration is called ''host-only networking'' by other virtualization software such as [[VirtualBox]].<br />
<br />
{{Tip|<br />
* If you want to set up IP masquerading, e.g. NAT for virtual machines, see the [[Internet sharing#Enable NAT]] page.<br />
* See [[Network bridge]] for information on creating bridge.<br />
* You may want to have a DHCP server running on the bridge interface to service the virtual network. For example, to use the {{ic|172.20.0.1/16}} subnet with [[dnsmasq]] as the DHCP server:<br />
<br />
{{bc|1=<br />
# ip addr add 172.20.0.1/16 dev br0<br />
# ip link set br0 up<br />
# dnsmasq --interface=br0 --bind-interfaces --dhcp-range=172.20.0.2,172.20.255.254<br />
}}<br />
}}<br />
<br />
==== Internal networking ====<br />
<br />
If you do not give the bridge an IP address and add an [[iptables]] rule to drop all traffic to the bridge in the INPUT chain, then the virtual machines will be able to talk to each other, but not to the physical host or to the outside network. This configuration is called ''internal networking'' by other virtualization software such as [[VirtualBox]]. You will need to either assign static IP addresses to the virtual machines or run a DHCP server on one of them.<br />
<br />
By default iptables would drop packets in the bridge network. You may need to use such iptables rule to allow packets in a bridged network:<br />
<br />
# iptables -I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Bridged networking using qemu-bridge-helper ====<br />
<br />
{{Note|This method is available since QEMU 1.1, see http://wiki.qemu.org/Features/HelperNetworking.}}<br />
<br />
This method does not require a start-up script and readily accommodates multiple taps and multiple bridges. It uses {{ic|/usr/lib/qemu/qemu-bridge-helper}} binary, which allows creating tap devices on an existing bridge.<br />
<br />
{{Tip|See [[Network bridge]] for information on creating bridge.}}<br />
<br />
First, create a configuration file containing the names of all bridges to be used by QEMU:<br />
<br />
{{hc|/etc/qemu/bridge.conf|<br />
allow ''bridge0''<br />
allow ''bridge1''<br />
...}}<br />
<br />
Now start the VM. The most basic usage would be:<br />
<br />
$ qemu-system-x86_64 -net nic -net bridge,br=''bridge0'' ''[...]''<br />
<br />
With multiple taps, the most basic usage requires specifying the VLAN for all additional NICs:<br />
<br />
$ qemu-system-x86_64 -net nic -net bridge,br=''bridge0'' -net nic,vlan=1 -net bridge,vlan=1,br=''bridge1'' ''[...]''<br />
<br />
==== Creating bridge manually ====<br />
<br />
{{Style|This section needs serious cleanup and may contain out-of-date information.}}<br />
<br />
{{Tip|Since QEMU 1.1, the [http://wiki.qemu.org/Features/HelperNetworking network bridge helper] can set tun/tap up for you without the need for additional scripting. See [[#Bridged networking using qemu-bridge-helper]].}}<br />
<br />
The following describes how to bridge a virtual machine to a host interface such as {{ic|eth0}}, which is probably the most common configuration. This configuration makes it appear that the virtual machine is located directly on the external network, on the same Ethernet segment as the physical host machine.<br />
<br />
We will replace the normal Ethernet adapter with a bridge adapter and bind the normal Ethernet adapter to it.<br />
<br />
* Install {{Pkg|bridge-utils}}, which provides {{ic|brctl}} to manipulate bridges.<br />
<br />
* Enable IPv4 forwarding:<br />
# sysctl -w net.ipv4.ip_forward=1<br />
<br />
To make the change permanent, change {{ic|1=net.ipv4.ip_forward = 0}} to {{ic|1=net.ipv4.ip_forward = 1}} in {{ic|/etc/sysctl.d/99-sysctl.conf}}.<br />
<br />
* Load the {{ic|tun}} module and configure it to be loaded on boot. See [[Kernel modules]] for details.<br />
<br />
* Now create the bridge. See [[Bridge with netctl]] for details. Remember to name your bridge as {{ic|br0}}, or change the scripts below to your bridge's name.<br />
<br />
* Create the script that QEMU uses to bring up the tap adapter with {{ic|root:kvm}} 750 permissions:<br />
<br />
{{hc|/etc/qemu-ifup|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifup"<br />
echo "Bringing up $1 for bridged mode..."<br />
sudo /usr/bin/ip link set $1 up promisc on<br />
echo "Adding $1 to br0..."<br />
sudo /usr/bin/brctl addif br0 $1<br />
sleep 2<br />
</nowiki>}}<br />
<br />
* Create the script that QEMU uses to bring down the tap adapter in {{ic|/etc/qemu-ifdown}} with {{ic|root:kvm}} 750 permissions:<br />
{{hc|/etc/qemu-ifdown|<nowiki><br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifdown"<br />
sudo /usr/bin/ip link set $1 down<br />
sudo /usr/bin/brctl delif br0 $1<br />
sudo /usr/bin/ip link delete dev $1<br />
</nowiki>}}<br />
<br />
* Use {{ic|visudo}} to add the following to your {{ic|sudoers}} file:<br />
<br />
{{bc|<nowiki><br />
Cmnd_Alias QEMU=/usr/bin/ip,/usr/bin/modprobe,/usr/bin/brctl<br />
%kvm ALL=NOPASSWD: QEMU<br />
</nowiki>}}<br />
<br />
* You launch QEMU using the following {{ic|run-qemu}} script:<br />
<br />
{{hc|run-qemu|<nowiki><br />
#!/bin/bash<br />
USERID=$(whoami)<br />
<br />
# Get name of newly created TAP device; see https://bbs.archlinux.org/viewtopic.php?pid=1285079#p1285079<br />
precreationg=$(/usr/bin/ip tuntap list | /usr/bin/cut -d: -f1 | /usr/bin/sort)<br />
sudo /usr/bin/ip tuntap add user $USERID mode tap<br />
postcreation=$(/usr/bin/ip tuntap list | /usr/bin/cut -d: -f1 | /usr/bin/sort)<br />
IFACE=$(comm -13 <(echo "$precreationg") <(echo "$postcreation"))<br />
<br />
# This line creates a random MAC address. The downside is the DHCP server will assign a different IP address each time<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
# Instead, uncomment and edit this line to set a static MAC address. The benefit is that the DHCP server will assign the same IP address.<br />
# macaddr='52:54:be:36:42:a9'<br />
<br />
qemu-system-x86_64 -net nic,macaddr=$macaddr -net tap,ifname="$IFACE" $*<br />
<br />
sudo ip link set dev $IFACE down &> /dev/null<br />
sudo ip tuntap del $IFACE mode tap &> /dev/null<br />
</nowiki>}}<br />
<br />
Then to launch a VM, do something like this<br />
<br />
$ run-qemu -hda ''myvm.img'' -m 512<br />
<br />
* It is recommended for performance and security reasons to disable the [http://ebtables.netfilter.org/documentation/bridge-nf.html firewall on the bridge]:<br />
<br />
{{hc|/etc/sysctl.d/10-disable-firewall-on-bridge.conf|<nowiki><br />
net.bridge.bridge-nf-call-ip6tables = 0<br />
net.bridge.bridge-nf-call-iptables = 0<br />
net.bridge.bridge-nf-call-arptables = 0<br />
</nowiki>}}<br />
<br />
Run {{ic|sysctl -p /etc/sysctl.d/10-disable-firewall-on-bridge.conf}} to apply the changes immediately.<br />
<br />
See the [http://wiki.libvirt.org/page/Networking#Creating_network_initscripts libvirt wiki] and [https://bugzilla.redhat.com/show_bug.cgi?id=512206 Fedora bug 512206]. If you get errors by sysctl during boot about non-existing files, make the {{ic|bridge}} module load at boot. See [[Kernel modules#Automatic module loading with systemd]].<br />
<br />
Alternatively, you can configure [[iptables]] to allow all traffic to be forwarded across the bridge by adding a rule like this:<br />
<br />
-I FORWARD -m physdev --physdev-is-bridged -j ACCEPT<br />
<br />
==== Network sharing between physical device and a Tap device through iptables ====<br />
<br />
{{Merge|Internet_sharing|Duplication, not specific to QEMU.}}<br />
<br />
Bridged networking works fine between a wired interface (Eg. eth0), and it is easy to setup. However if the host gets connected to the network through a wireless device, then bridging is not possible.<br />
<br />
See [[Network bridge#Wireless interface on a bridge]] as a reference.<br />
<br />
One way to overcome that is to setup a tap device with a static IP, making linux automatically handle the routing for it, and then forward traffic between the tap interface and the device connected to the network through iptables rules.<br />
<br />
See [[Internet sharing]] as a reference.<br />
<br />
There you can find what is needed to share the network between devices, included tap and tun ones. The following just hints further on some of the host configurations required. As indicated in the reference above, the client needs to be configured for a static IP, using the IP assigned to the tap interface as the gateway. The caveat is that the DNS servers on the client might need to be manually edited if they change when changing from one host device connected to the network to another.<br />
<br />
To allow IP forwarding on every boot, one need to add the following lines to sysctl configuration file inside {{ic|/etc/sysctl.d}}:<br />
<br />
net.ipv4.ip_forward = 1<br />
net.ipv6.conf.default.forwarding = 1<br />
net.ipv6.conf.all.forwarding = 1<br />
<br />
The iptables rules can look like:<br />
<br />
# Forwarding from/to outside<br />
iptables -A FORWARD -i ${INT} -o ${EXT_0} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_1} -j ACCEPT<br />
iptables -A FORWARD -i ${INT} -o ${EXT_2} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_0} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_1} -o ${INT} -j ACCEPT<br />
iptables -A FORWARD -i ${EXT_2} -o ${INT} -j ACCEPT<br />
# NAT/Masquerade (network address translation)<br />
iptables -t nat -A POSTROUTING -o ${EXT_0} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_1} -j MASQUERADE<br />
iptables -t nat -A POSTROUTING -o ${EXT_2} -j MASQUERADE<br />
<br />
The prior supposes there are 3 devices connected to the network sharing traffic with one internal device, where for example:<br />
<br />
INT=tap0<br />
EXT_0=eth0<br />
EXT_1=wlan0<br />
EXT_2=tun0<br />
<br />
The prior shows a forwarding that would allow sharing wired and wireless connections with the tap device.<br />
<br />
The forwarding rules shown are stateless, and for pure forwarding. One could think of restricting specific traffic, putting a firewall in place to protect the guest and others. However those would decrease the networking performance, while a simple bridge does not include any of that.<br />
<br />
Bonus: Whether the connection is wired or wireless, if one gets connected through VPN to a remote site with a tun device, supposing the tun device opened for that connection is tun0, and the prior iptables rules are applied, then the remote connection gets also shared with the guest. This avoids the need for the guest to also open a VPN connection. Again, as the guest networking needs to be static, then if connecting the host remotely this way, one most probably will need to edit the DNS servers on the guest.<br />
<br />
=== Networking with VDE2 ===<br />
<br />
{{Style|This section needs serious cleanup and may contain out-of-date information.}}<br />
<br />
==== What is VDE? ====<br />
<br />
VDE stands for Virtual Distributed Ethernet. It started as an enhancement of [[User-mode Linux|uml]]_switch. It is a toolbox to manage virtual networks.<br />
<br />
The idea is to create virtual switches, which are basically sockets, and to "plug" both physical and virtual machines in them. The configuration we show here is quite simple; However, VDE is much more powerful than this, it can plug virtual switches together, run them on different hosts and monitor the traffic in the switches. You are invited to read [https://wiki.virtualsquare.org/ the documentation of the project].<br />
<br />
The advantage of this method is you do not have to add sudo privileges to your users. Regular users should not be allowed to run modprobe.<br />
<br />
==== Basics ====<br />
<br />
VDE support can be [[pacman|installed]] via the {{Pkg|vde2}} package.<br />
<br />
In our config, we use tun/tap to create a virtual interface on my host. Load the {{ic|tun}} module (see [[Kernel modules]] for details):<br />
<br />
# modprobe tun<br />
<br />
Now create the virtual switch:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
<br />
This line creates the switch, creates {{ic|tap0}}, "plugs" it, and allows the users of the group {{ic|users}} to use it.<br />
<br />
The interface is plugged in but not configured yet. To configure it, run this command:<br />
<br />
# ip addr add 192.168.100.254/24 dev tap0<br />
<br />
Now, you just have to run KVM with these {{ic|-net}} options as a normal user:<br />
<br />
$ qemu-system-x86_64 -net nic -net vde -hda ''[...]''<br />
<br />
Configure networking for your guest as you would do in a physical network.<br />
<br />
{{Tip|You might want to set up NAT on tap device to access the internet from the virtual machine. See [[Internet sharing#Enable NAT]] for more information.}}<br />
<br />
==== Startup scripts ====<br />
<br />
Example of main script starting VDE:<br />
<br />
{{hc|/etc/systemd/scripts/qemu-network-env|<nowiki><br />
#!/bin/sh<br />
# QEMU/VDE network environment preparation script<br />
<br />
# The IP configuration for the tap device that will be used for<br />
# the virtual machine network:<br />
<br />
TAP_DEV=tap0<br />
TAP_IP=192.168.100.254<br />
TAP_MASK=24<br />
TAP_NETWORK=192.168.100.0<br />
<br />
# Host interface<br />
NIC=eth0<br />
<br />
case "$1" in<br />
start)<br />
echo -n "Starting VDE network for QEMU: "<br />
<br />
# If you want tun kernel module to be loaded by script uncomment here<br />
#modprobe tun 2>/dev/null<br />
## Wait for the module to be loaded<br />
#while ! lsmod | grep -q "^tun"; do echo "Waiting for tun device"; sleep 1; done<br />
<br />
# Start tap switch<br />
vde_switch -tap "$TAP_DEV" -daemon -mod 660 -group users<br />
<br />
# Bring tap interface up<br />
ip address add "$TAP_IP"/"$TAP_MASK" dev "$TAP_DEV"<br />
ip link set "$TAP_DEV" up<br />
<br />
# Start IP Forwarding<br />
echo "1" > /proc/sys/net/ipv4/ip_forward<br />
iptables -t nat -A POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
;;<br />
stop)<br />
echo -n "Stopping VDE network for QEMU: "<br />
# Delete the NAT rules<br />
iptables -t nat -D POSTROUTING -s "$TAP_NETWORK"/"$TAP_MASK" -o "$NIC" -j MASQUERADE<br />
<br />
# Bring tap interface down<br />
ip link set "$TAP_DEV" down<br />
<br />
# Kill VDE switch<br />
pgrep vde_switch | xargs kill -TERM<br />
;;<br />
restart|reload)<br />
$0 stop<br />
sleep 1<br />
$0 start<br />
;;<br />
*)<br />
echo "Usage: $0 {start|stop|restart|reload}"<br />
exit 1<br />
esac<br />
exit 0<br />
</nowiki>}}<br />
<br />
Example of systemd service using the above script:<br />
<br />
{{hc|/etc/systemd/system/qemu-network-env.service|<nowiki><br />
[Unit]<br />
Description=Manage VDE Switch<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/etc/systemd/scripts/qemu-network-env start<br />
ExecStop=/etc/systemd/scripts/qemu-network-env stop<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
Change permissions for {{ic|qemu-network-env}} to be executable<br />
<br />
# chmod u+x /etc/systemd/scripts/qemu-network-env<br />
<br />
You can [[start]] {{ic|qemu-network-env.service}} as usual.<br />
<br />
====Alternative method====<br />
<br />
If the above method does not work or you do not want to mess with kernel configs, TUN, dnsmasq, and iptables you can do the following for the same result.<br />
<br />
# vde_switch -daemon -mod 660 -group users<br />
# slirpvde --dhcp --daemon<br />
<br />
Then, to start the VM with a connection to the network of the host:<br />
<br />
$ qemu-system-x86_64 -net nic,macaddr=52:54:00:00:EE:03 -net vde ''disk_image''<br />
<br />
=== VDE2 Bridge ===<br />
<br />
Based on [https://selamatpagicikgu.wordpress.com/2011/06/08/quickhowto-qemu-networking-using-vde-tuntap-and-bridge/ quickhowto: qemu networking using vde, tun/tap, and bridge] graphic. Any virtual machine connected to vde is externally exposed. For example, each virtual machine can receive DHCP configuration directly from your ADSL router.<br />
<br />
==== Basics ====<br />
<br />
Remember that you need {{ic|tun}} module and {{Pkg|bridge-utils}} package.<br />
<br />
Create the vde2/tap device:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group users<br />
# ip link set tap0 up<br />
<br />
Create bridge:<br />
<br />
# brctl addbr br0<br />
<br />
Add devices:<br />
<br />
# brctl addif br0 eth0<br />
# brctl addif br0 tap0<br />
<br />
And configure bridge interface:<br />
<br />
# dhcpcd br0<br />
<br />
==== Startup scripts ====<br />
<br />
All devices must be set up. And only the bridge needs an IP address. For physical devices on the bridge (e.g. {{ic|eth0}}), this can be done with [[netctl]] using a custom Ethernet profile with:<br />
<br />
{{hc|/etc/netctl/ethernet-noip|2=<br />
Description='A more versatile static Ethernet connection'<br />
Interface=eth0<br />
Connection=ethernet<br />
IP=no<br />
}}<br />
<br />
The following custom systemd service can be used to create and activate a VDE2 tap interface for use in the {{ic|users}} user group.<br />
<br />
{{hc|/etc/systemd/system/vde2@.service|2=<br />
[Unit]<br />
Description=Network Connectivity for %i<br />
Wants=network.target<br />
Before=network.target<br />
<br />
[Service]<br />
Type=oneshot<br />
RemainAfterExit=yes<br />
ExecStart=/usr/bin/vde_switch -tap %i -daemon -mod 660 -group users<br />
ExecStart=/usr/bin/ip link set dev %i up<br />
ExecStop=/usr/bin/ip addr flush dev %i<br />
ExecStop=/usr/bin/ip link set dev %i down<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
}}<br />
<br />
And finally, you can create the [[Bridge with netctl|bridge interface with netctl]].<br />
<br />
=== Shorthand configuration ===<br />
<br />
If you are using QEMU with various networking options a lot, you probably have created a lot of {{ic|-netdev}} and {{ic|-device}} argument pairs, which gets quite repetitive. You can instead use the {{ic|-nic}} argument to combine {{ic|-netdev}} and {{ic|-device}} together, so that, for example, these arguments:<br />
<br />
-netdev tap,id=network0,ifname=tap0,script=no,downscript=no,vhost=on -device virtio-net-pci,netdev=network0<br />
<br />
become:<br />
<br />
-nic tap,script=no,downscript=no,vhost=on,model=virtio-net-pci<br />
<br />
Notice the lack of network IDs, and that the device was created with {{ic|1=model=}}. The first half of the {{ic|-nic}} parameters are {{ic|-netdev}} parameters, whereas the second half (after {{ic|1=model=}}) are related with the device. The same parameters (for example, {{ic|1=smb=}}) are used. To completely disable the networking use {{ic|-nic none}}.<br />
<br />
See [https://qemu.weilnetz.de/doc/qemu-doc.html#Network-options QEMU networking documentation] for more information on parameters you can use.<br />
<br />
== Graphic card ==<br />
<br />
QEMU can emulate a standard graphic card text mode using {{ic|-curses}} command line option. This allows to type text and see text output directly inside a text terminal.<br />
<br />
QEMU can emulate several types of VGA card. The card type is passed in the {{ic|-vga ''type''}} command line option and can be {{ic|std}}, {{ic|qxl}}, {{ic|vmware}}, {{ic|virtio}}, {{ic|cirrus}} or {{ic|none}}.<br />
<br />
=== std ===<br />
<br />
With {{ic|-vga std}} you can get a resolution of up to 2560 x 1600 pixels without requiring guest drivers. This is the default since QEMU 2.2.<br />
<br />
=== qxl ===<br />
<br />
QXL is a paravirtual graphics driver with 2D support. To use it, pass the {{ic|-vga qxl}} option and install drivers in the guest. You may want to use [[#SPICE]] for improved graphical performance when using QXL.<br />
<br />
On Linux guests, the {{ic|qxl}} and {{ic|bochs_drm}} kernel modules must be loaded in order to gain a decent performance.<br />
<br />
Default VGA memory size for QXL devices is 16M which is sufficient to drive resolutions approximately up to QHD (2560x1440). To enable higher resolutions, [[#Multi-monitor support|increase vga_memmb]].<br />
<br />
=== vmware ===<br />
<br />
Although it is a bit buggy, it performs better than std and cirrus. Install the VMware drivers {{Pkg|xf86-video-vmware}} and {{Pkg|xf86-input-vmmouse}} for Arch Linux guests.<br />
<br />
=== virtio ===<br />
<br />
{{ic|virtio-vga}} / {{ic|virtio-gpu}} is a paravirtual 3D graphics driver based on [https://virgil3d.github.io/ virgl]. Currently a work in progress, supporting only very recent (>= 4.4) Linux guests with {{Pkg|mesa}} (>=11.2) compiled with the option {{ic|1=gallium-drivers=virgl}}.<br />
<br />
To enable 3D acceleration on the guest system select this vga with {{ic|-vga virtio}} and enable the opengl context in the display device with {{ic|1=-display sdl,gl=on}} or {{ic|1=-display gtk,gl=on}} for the sdl and gtk display output respectively. Successful configuration can be confirmed looking at the kernel log in the guest:<br />
<br />
{{hc|$ dmesg {{!}} grep drm |<br />
[drm] pci: virtio-vga detected<br />
[drm] virgl 3d acceleration enabled<br />
}}<br />
<br />
=== cirrus ===<br />
<br />
The cirrus graphical adapter was the default [http://wiki.qemu.org/ChangeLog/2.2#VGA before 2.2]. It [https://www.kraxel.org/blog/2014/10/qemu-using-cirrus-considered-harmful/ should not] be used on modern systems.<br />
<br />
=== none ===<br />
<br />
This is like a PC that has no VGA card at all. You would not even be able to access it with the {{ic|-vnc}} option. Also, this is different from the {{ic|-nographic}} option which lets QEMU emulate a VGA card, but disables the SDL display.<br />
<br />
== SPICE ==<br />
The [http://spice-space.org/ SPICE project] aims to provide a complete open source solution for remote access to virtual machines in a seamless way.<br />
=== Enabling SPICE support on the host ===<br />
The following is an example of booting with SPICE as the remote desktop protocol, including the support for copy and paste from host:<br />
<br />
$ qemu-system-x86_64 -vga qxl -device virtio-serial-pci -spice port=5930,disable-ticketing -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
The parameters have the following meaning:<br />
<br />
# {{ic|-device virtio-serial-pci}} adds a virtio-serial device<br />
# {{ic|1=-spice port=5930,disable-ticketing}} set TCP port {{ic|5930}} for spice channels listening and allow client to connect without authentication{{Tip|Using [[wikipedia:Unix_socket|Unix sockets]] instead of TCP ports does not involve using network stack on the host system. It does not imply that packets are encapsulated and decapsulated to use the network and the related protocol. The sockets are identified solely by the inodes on the hard drive. It is therefore considered better for performance. Use instead {{ic|1=-spice unix,addr=/tmp/vm_spice.socket,disable-ticketing}}.}}<br />
# {{ic|1=-device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0}} opens a port for spice vdagent in the virtio-serial device,<br />
# {{ic|1=-chardev spicevmc,id=spicechannel0,name=vdagent}} adds a spicevmc chardev for that port. It is important that the {{ic|1=chardev=}} option of the {{ic|virtserialport}} device matches the {{ic|1=id=}} option given to the {{ic|chardev}} option ({{ic|spicechannel0}} in this example). It is also important that the port name is {{ic|com.redhat.spice.0}}, because that is the namespace where vdagent is looking for in the guest. And finally, specify {{ic|1=name=vdagent}} so that spice knows what this channel is for.<br />
<br />
=== Connecting to the guest with a SPICE client ===<br />
<br />
A SPICE client is necessary to connect to the guest. In Arch, the following clients are available:<br />
<br />
{{App|virt-viewer|SPICE client recommended by the protocol developers, a subset of the virt-manager project.|https://virt-manager.org/|{{Pkg|virt-viewer}}}}<br />
<br />
{{App|spice-gtk|SPICE GTK client, a subset of the SPICE project. Embedded into other applications as a widget.|https://www.spice-space.org/|{{Pkg|spice-gtk}}}}<br />
<br />
For clients that run on smartphone or on other platforms, refer to the ''Other clients'' section in [http://www.spice-space.org/download.html spice-space download].<br />
<br />
==== Manually running a SPICE client ====<br />
<br />
One way of connecting to a guest listening on Unix socket {{ic|/tmp/vm_spice.socket}} is to manually run the SPICE client using {{ic|$ remote-viewer spice+unix:///tmp/vm_spice.socket}} or {{ic|1=$ spicy --uri="spice+unix:///tmp/vm_spice.socket"}}, depending on the desired client. Since QEMU in SPICE mode acts similarly to a remote desktop server, it may be more convenient to run QEMU in daemon mode with the {{ic|-daemonize}} parameter.<br />
<br />
{{Tip|To connect to the guest through SSH tunelling, the following type of command can be used: {{bc|$ ssh -fL 5999:localhost:5930 ''my.domain.org'' sleep 10; spicy -h 127.0.0.1 -p 5999}}<br />
This example connects ''spicy'' to the local port {{ic|5999}} which is forwarded through SSH to the guest's SPICE server located at the address ''my.domain.org'', port {{ic|5930}}.<br />
Note the {{ic|-f}} option that requests ssh to execute the command {{ic|sleep 10}} in the background. This way, the ssh session runs while the client is active and auto-closes once the client ends.<br />
}}<br />
<br />
==== Running a SPICE client with QEMU ====<br />
<br />
QEMU can automatically start a SPICE client with an appropriate socket, if the display is set to SPICE with the {{ic|-display spice-app}} parameter. This will use the system's default SPICE client as the viewer, determined by your [[XDG_MIME_Applications#mimeapps.list|mimeapps.list]] files.<br />
<br />
=== Enabling SPICE support on the guest ===<br />
<br />
For '''Arch Linux guests''', for improved support for multiple monitors or clipboard sharing, the following packages should be installed:<br />
* {{Pkg|spice-vdagent}}: Spice agent xorg client that enables copy and paste between client and X-session and more.<br />
* {{Pkg|xf86-video-qxl}}: Xorg X11 qxl video driver<br />
For guests under '''other operating systems''', refer to the ''Guest'' section in [http://www.spice-space.org/download.html spice-space download].<br />
<br />
=== Password authentication with SPICE ===<br />
<br />
If you want to enable password authentication with SPICE you need to remove {{ic|disable-ticketing}} from the {{ic|-spice}} argument and instead add {{ic|1=password=''yourpassword''}}. For example:<br />
<br />
$ qemu-system-x86_64 -vga qxl -spice port=5900,password=''yourpassword'' -device virtio-serial-pci -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0 -chardev spicevmc,id=spicechannel0,name=vdagent<br />
<br />
Your SPICE client should now ask for the password to be able to connect to the SPICE server.<br />
<br />
=== TLS encrypted communication with SPICE ===<br />
<br />
You can also configure TLS encryption for communicating with the SPICE server. First, you need to have a directory which contains the following files (the names must be exactly as indicated):<br />
<br />
* {{ic|ca-cert.pem}}: the CA master certificate.<br />
* {{ic|server-cert.pem}}: the server certificate signed with {{ic|ca-cert.pem}}.<br />
* {{ic|server-key.pem}}: the server private key.<br />
<br />
An example of generation of self-signed certificates with your own generated CA for your server is shown in the [https://www.spice-space.org/spice-user-manual.html#_generating_self_signed_certificates Spice User Manual].<br />
<br />
Afterwards, you can run QEMU with SPICE as explained above but using the following {{ic|-spice}} argument: {{ic|1=-spice tls-port=5901,password=''yourpassword'',x509-dir=''/path/to/pki_certs''}}, where {{ic|''/path/to/pki_certs''}} is the directory path that contains the three needed files shown earlier.<br />
<br />
It is now possible to connect to the server using {{pkg|virt-viewer}}:<br />
<br />
$ remote-viewer spice://''hostname''?tls-port=5901 --spice-ca-file=''/path/to/ca-cert.pem'' --spice-host-subject="C=''XX'',L=''city'',O=''organization'',CN=''hostname''" --spice-secure-channels=all<br />
<br />
Keep in mind that the {{ic|--spice-host-subject}} parameter needs to be set according to your {{ic|server-cert.pem}} subject. You also need to copy {{ic|ca-cert.pem}} to every client to verify the server certificate.<br />
<br />
{{Tip|You can get the subject line of the server certificate in the correct format for {{ic|--spice-host-subject}} (with entries separated by commas) using the following command: {{bc|<nowiki>$ openssl x509 -noout -subject -in server-cert.pem | cut -d' ' -f2- | sed 's/\///' | sed 's/\//,/g'</nowiki>}}<br />
}}<br />
<br />
The equivalent {{Pkg|spice-gtk}} command is:<br />
<br />
$ spicy -h ''hostname'' -s 5901 --spice-ca-file=ca-cert.pem --spice-host-subject="C=''XX'',L=''city'',O=''organization'',CN=''hostname''" --spice-secure-channels=all<br />
<br />
== VNC ==<br />
<br />
One can add the {{ic|-vnc :''X''}} option to have QEMU redirect the VGA display to the VNC session. Substitute {{ic|''X''}} for the number of the display (0 will then listen on 5900, 1 on 5901...).<br />
<br />
$ qemu-system-x86_64 -vnc :0<br />
<br />
An example is also provided in the [[#Starting QEMU virtual machines on boot]] section.<br />
{{Warning|The default VNC server setup does not use any form of authentication. Any user can connect from any host.}}<br />
<br />
=== Basic password authentication ===<br />
<br />
An access password can be setup easily by using the {{ic|password}} option. The password must be indicated in the QEMU monitor and connection is only possible once the password is provided.<br />
<br />
$ qemu-system-x86_64 -vnc :0,password -monitor stdio<br />
<br />
In the QEMU monitor, password is set using the command {{ic|change vnc password}} and then indicating the password.<br />
<br />
The following command line directly runs vnc with a password:<br />
<br />
$ printf "change vnc password\n%s\n" MYPASSWORD | qemu-system-x86_64 -vnc :0,password -monitor stdio<br />
<br />
{{Note|The password is limited to 8 characters and can be guessed through brute force attack. More elaborated protection is strongly recommended for public network.}}<br />
<br />
== Audio ==<br />
<br />
=== Host ===<br />
<br />
The {{ic|-audiodev}} flag sets the audio backend driver and its options. The list of available audio backend drivers and their optional settings is detailed in the {{man|1|qemu}}. man page.<br />
<br />
At the bare minimum, you need to choose a driver and set an id.<br />
<br />
-audiodev pa,id=snd0<br />
<br />
=== Guest ===<br />
<br />
==== With audiodev ====<br />
<br />
===== Intel HD Audio =====<br />
<br />
For Intel HD Audio emulation add both controller and codec devices. To list the available Intel HDA Audio devices:<br />
<br />
$ qemu-system-x86_64 -device help | grep hda<br />
<br />
Add the audio controller<br />
<br />
-device ich9-intel-hda<br />
<br />
Add the audio codec and map it to a host audio backend id<br />
<br />
-device hda-output,audiodev=snd0<br />
<br />
===== Intel 82801AA AC97 =====<br />
<br />
For AC97 emulation just add the audio card device and map it to a host audio backend id<br />
<br />
-device AC97,audiodev=snd0<br />
<br />
==== Without audiodev ====<br />
<br />
To get list of the supported emulation audio drivers:<br />
$ qemu-system-x86_64 -soundhw help<br />
<br />
To use e.g. {{ic|hda}} driver for the guest use the {{ic|-soundhw hda}} command with QEMU.<br />
<br />
{{Note|Video graphic card emulated drivers for the guest machine may also cause a problem with the sound quality. Test one by one to make it work. You can list possible options with {{ic|<nowiki>qemu-system-x86_64 -h | grep vga</nowiki>}}.}}<br />
<br />
== Installing virtio drivers ==<br />
<br />
QEMU offers guests the ability to use paravirtualized block and network devices using the [http://wiki.libvirt.org/page/Virtio virtio] drivers, which provide better performance and lower overhead.<br />
<br />
* A virtio block device requires the option {{Ic|-drive}} for passing a disk image, with parameter {{Ic|1=if=virtio}}:<br />
$ qemu-system-x86_64 -boot order=c -drive file=''disk_image'',if=virtio<br />
<br />
* Almost the same goes for the network:<br />
$ qemu-system-x86_64 -nic user,model=virtio-net-pci<br />
<br />
{{Note|This will only work if the guest machine has drivers for virtio devices. Linux does, and the required drivers are included in Arch Linux, but there is no guarantee that virtio devices will work with other operating systems.}}<br />
<br />
=== Preparing an (Arch) Linux guest ===<br />
<br />
To use virtio devices after an Arch Linux guest has been installed, the following modules must be loaded in the guest: {{Ic|virtio}}, {{Ic|virtio_pci}}, {{Ic|virtio_blk}}, {{Ic|virtio_net}}, and {{Ic|virtio_ring}}. For 32-bit guests, the specific "virtio" module is not necessary.<br />
<br />
If you want to boot from a virtio disk, the initial ramdisk must contain the necessary modules. By default, this is handled by [[mkinitcpio]]'s {{ic|autodetect}} hook. Otherwise use the {{ic|MODULES}} array in {{ic|/etc/mkinitcpio.conf}} to include the necessary modules and rebuild the initial ramdisk.<br />
<br />
{{hc|/etc/mkinitcpio.conf|2=<br />
MODULES=(virtio virtio_blk virtio_pci virtio_net)}}<br />
<br />
Virtio disks are recognized with the prefix {{ic|'''v'''}} (e.g. {{ic|'''v'''da}}, {{ic|'''v'''db}}, etc.); therefore, changes must be made in at least {{ic|/etc/fstab}} and {{ic|/boot/grub/grub.cfg}} when booting from a virtio disk.<br />
<br />
{{Tip|When referencing disks by [[UUID]] in both {{ic|/etc/fstab}} and bootloader, nothing has to be done.}}<br />
<br />
Further information on paravirtualization with KVM can be found [http://www.linux-kvm.org/page/Boot_from_virtio_block_device here].<br />
<br />
You might also want to install {{Pkg|qemu-guest-agent}} to implement support for QMP commands that will enhance the hypervisor management capabilities. After installing the package you can enable and start the {{ic|qemu-ga.service}}.<br />
<br />
=== Preparing a Windows guest ===<br />
<br />
==== Block device drivers ====<br />
<br />
===== New Install of Windows =====<br />
<br />
Windows does not come with the virtio drivers. Therefore, you will need to load them during installation. There are basically two ways to do this: via Floppy Disk or via ISO files. Both images can be downloaded from the [https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/stable-virtio/virtio-win.iso Fedora repository].<br />
<br />
The floppy disk option is difficult because you will need to press F6 (Shift-F6 on newer Windows) at the very beginning of powering on the QEMU. This is difficult since you need time to connect your VNC console window. You can attempt to add a delay to the boot sequence. See {{man|1|qemu}} for more details about applying a delay at boot.<br />
<br />
The ISO option to load drivers is the preferred way, but it is available only on Windows Vista and Windows Server 2008 and later. The procedure is to load the image with virtio drivers in an additional cdrom device along with the primary disk device and Windows installer:<br />
<br />
$ qemu-system-x86_64 ... \<br />
-drive file=''windows_disk_image'',index=0,media=disk,if=virtio \<br />
-drive file=''windows.iso'',index=2,media=cdrom \<br />
-drive file=''virtio.iso'',index=3,media=cdrom \<br />
...<br />
<br />
During the installation, at some stage, the Windows installer will ask "Where do you want to install Windows?", it will give a warning that no disks are found. Follow the example instructions below (based on Windows Server 2012 R2 with Update).<br />
<br />
* Select the option ''Load Drivers''.<br />
* Uncheck the box for ''Hide drivers that aren't compatible with this computer's hardware''.<br />
* Click the browse button and open the CDROM for the virtio iso, usually named "virtio-win-XX".<br />
* Now browse to {{ic|E:\viostor\[your-os]\amd64}}, select it, and confirm.<br />
<br />
You should now see your virtio disk(s) listed here, ready to be selected, formatted and installed to.<br />
<br />
===== Change Existing Windows VM to use virtio =====<br />
<br />
Modifying an existing Windows guest for booting from virtio disk requires that the virtio driver is available in the guest and that it is loaded at boot time.<br />
<br />
One can find the virtio disk driver in the [https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/stable-virtio/virtio-win.iso Fedora repository].<br />
<br />
Now, create a new disk image that will be used to search for the virtio driver:<br />
<br />
$ qemu-img create -f qcow2 ''fake.qcow2'' 1G<br />
<br />
Run the original Windows guest (with the boot disk still in IDE mode) with the fake disk (in virtio mode) and a CD-ROM with the driver.<br />
<br />
$ qemu-system-x86_64 -m 512 -drive file=''windows_disk_image'',if=ide -drive file=''fake.qcow2'',if=virtio -cdrom virtio-win-0.1-81.iso<br />
<br />
Windows will detect the fake disk and look for a suitable driver. If it fails, go to ''Device Manager'', locate the SCSI drive with an exclamation mark icon (should be open), click ''Update driver'' and select the virtual CD-ROM. Do not navigate to the driver folder within the CD-ROM, simply select the CD-ROM drive and Windows will find the appropriate driver automatically (tested for Windows 7 SP1).<br />
<br />
Request Windows to boot in safe mode next time it starts up. This can be done using the ''msconfig.exe'' tool in Windows. In safe mode all the drivers will be loaded at boot time including the new virtio driver. Once Windows knows that the virtio driver is required at boot it will memorize it for future boot.<br />
<br />
Once instructed to boot in safe mode, you can turn off the virtual machine and launch it again, now with the boot disk attached in virtio mode:<br />
<br />
$ qemu-system-x86_64 -m 512 -drive file=''windows_disk_image'',if=virtio<br />
<br />
You should boot in safe mode with virtio driver loaded, you can now return to ''msconfig.exe'' disable safe mode boot and restart Windows.<br />
<br />
{{Note|If you encounter the blue screen of death using the {{ic|1=if=virtio}} parameter, it probably means the virtio disk driver is not installed or not loaded at boot time, reboot in safe mode and check your driver configuration.}}<br />
<br />
==== Network drivers ====<br />
<br />
Installing virtio network drivers is a bit easier, simply add the {{ic|-nic}} argument.<br />
<br />
$ qemu-system-x86_64 -m 512 -drive file=''windows_disk_image'',if=virtio -nic user,model=virtio-net-pci -cdrom virtio-win-0.1-74.iso<br />
<br />
Windows will detect the network adapter and try to find a driver for it. If it fails, go to the ''Device Manager'', locate the network adapter with an exclamation mark icon (should be open), click ''Update driver'' and select the virtual CD-ROM. Do not forget to select the checkbox which says to search for directories recursively.<br />
<br />
==== Balloon driver ====<br />
<br />
If you want to track you guest memory state (for example via {{ic|virsh}} command {{ic|dommemstat}}) or change guest's memory size in runtime (you still will not be able to change memory size, but can limit memory usage via inflating balloon driver) you will need to install guest balloon driver.<br />
<br />
For this you will need to go to ''Device Manager'', locate ''PCI standard RAM Controller'' in ''System devices'' (or unrecognized PCI controller from ''Other devices'') and choose ''Update driver''. In opened window you will need to choose ''Browse my computer...'' and select the CD-ROM (and do not forget the ''Include subdirectories'' checkbox). Reboot after installation. This will install the driver and you will be able to inflate the balloon (for example via hmp command {{ic|balloon ''memory_size''}}, which will cause balloon to take as much memory as possible in order to shrink the guest's available memory size to ''memory_size''). However, you still will not be able to track guest memory state. In order to do this you will need to install ''Balloon'' service properly. For that open command line as administrator, go to the CD-ROM, ''Balloon'' directory and deeper, depending on your system and architecture. Once you are in ''amd64'' (''x86'') directory, run {{ic|blnsrv.exe -i}} which will do the installation. After that {{ic|virsh}} command {{ic|dommemstat}} should be outputting all supported values.<br />
<br />
=== Preparing a FreeBSD guest ===<br />
<br />
Install the {{ic|emulators/virtio-kmod}} port if you are using FreeBSD 8.3 or later up until 10.0-CURRENT where they are included into the kernel. After installation, add the following to your {{ic|/boot/loader.conf}} file:<br />
<br />
{{bc|1=<br />
virtio_load="YES"<br />
virtio_pci_load="YES"<br />
virtio_blk_load="YES"<br />
if_vtnet_load="YES"<br />
virtio_balloon_load="YES"<br />
}}<br />
<br />
Then modify your {{ic|/etc/fstab}} by doing the following:<br />
<br />
# sed -ibak "s/ada/vtbd/g" /etc/fstab<br />
<br />
And verify that {{ic|/etc/fstab}} is consistent. If anything goes wrong, just boot into a rescue CD and copy {{ic|/etc/fstab.bak}} back to {{ic|/etc/fstab}}.<br />
<br />
== QEMU monitor ==<br />
<br />
While QEMU is running, a monitor console is provided in order to provide several ways to interact with the virtual machine running. The QEMU monitor offers interesting capabilities such as obtaining information about the current virtual machine, hotplugging devices, creating snapshots of the current state of the virtual machine, etc. To see the list of all commands, run {{ic|help}} or {{ic|?}} in the QEMU monitor console or review the relevant section of the [https://qemu.weilnetz.de/doc/qemu-doc.html#pcsys_005fmonitor official QEMU documentation].<br />
<br />
=== Accessing the monitor console ===<br />
<br />
==== Graphical view ====<br />
<br />
When using the {{ic|std}} default graphics option, one can access the QEMU monitor by pressing {{ic|Ctrl+Alt+2}} or by clicking ''View > compatmonitor0'' in the QEMU window. To return to the virtual machine graphical view either press {{ic|Ctrl+Alt+1}} or click ''View > VGA''.<br />
<br />
However, the standard method of accessing the monitor is not always convenient and does not work in all graphic outputs QEMU supports.<br />
<br />
==== Telnet ====<br />
<br />
To enable [[telnet]], run QEMU with the {{ic|-monitor telnet:127.0.0.1:''port'',server,nowait}} parameter. When the virtual machine is started you will be able to access the monitor via telnet:<br />
<br />
$ telnet 127.0.0.1 ''port''<br />
<br />
{{Note|If {{ic|127.0.0.1}} is specified as the IP to listen it will be only possible to connect to the monitor from the same host QEMU is running on. If connecting from remote hosts is desired, QEMU must be told to listen {{ic|0.0.0.0}} as follows: {{ic|-monitor telnet:0.0.0.0:''port'',server,nowait}}. Keep in mind that it is recommended to have a [[firewall]] configured in this case or make sure your local network is completely trustworthy since this connection is completely unauthenticated and unencrypted.}}<br />
<br />
==== UNIX socket ====<br />
<br />
Run QEMU with the {{ic|-monitor unix:''socketfile'',server,nowait}} parameter. Then you can connect with either {{pkg|socat}} or {{pkg|openbsd-netcat}}.<br />
<br />
For example, if QEMU is run via:<br />
<br />
$ qemu-system-x86_64 ''[...]'' -monitor unix:/tmp/monitor.sock,server,nowait ''[...]''<br />
<br />
It is possible to connect to the monitor with:<br />
<br />
$ socat - UNIX-CONNECT:/tmp/monitor.sock<br />
<br />
Or with:<br />
<br />
$ nc -U /tmp/monitor.sock<br />
<br />
==== TCP ====<br />
<br />
You can expose the monitor over TCP with the argument {{ic|-monitor tcp:127.0.0.1:''port'',server,nowait}}. Then connect with netcat, either {{pkg|openbsd-netcat}} or {{pkg|gnu-netcat}} by running:<br />
<br />
$ nc 127.0.0.1 ''port''<br />
<br />
{{Note|In order to be able to connect to the tcp socket from other devices other than the same host QEMU is being run on you need to listen to {{ic|0.0.0.0}} like explained in the telnet case. The same security warnings apply in this case as well.}}<br />
<br />
==== Standard I/O ====<br />
<br />
It is possible to access the monitor automatically from the same terminal QEMU is being run by running it with the argument {{ic|-monitor stdio}}.<br />
<br />
=== Sending keyboard presses to the virtual machine using the monitor console ===<br />
<br />
Some combinations of keys may be difficult to perform on virtual machines due to the host intercepting them instead in some configurations (a notable example is the {{ic|Ctrl+Alt+F*}} key combinations, which change the active tty). To avoid this problem, the problematic combination of keys may be sent via the monitor console instead. Switch to the monitor and use the {{ic|sendkey}} command to forward the necessary keypresses to the virtual machine. For example:<br />
<br />
(qemu) sendkey ctrl-alt-f2<br />
<br />
=== Creating and managing snapshots via the monitor console ===<br />
<br />
{{Note|This feature will '''only''' work when the virtual machine disk image is in ''qcow2'' format. It will not work with ''raw'' images.}}<br />
<br />
It is sometimes desirable to save the current state of a virtual machine and having the possibility of reverting the state of the virtual machine to that of a previously saved snapshot at any time. The QEMU monitor console provides the user with the necessary utilities to create snapshots, manage them, and revert the machine state to a saved snapshot.<br />
<br />
* Use {{ic|savevm ''name''}} in order to create a snapshot with the tag ''name''.<br />
* Use {{ic|loadvm ''name''}} to revert the virtual machine to the state of the snapshot ''name''.<br />
* Use {{ic|delvm ''name''}} to delete the snapshot tagged as ''name''.<br />
* Use {{ic|info snapshots}} to see a list of saved snapshots. Snapshots are identified by both an auto-incremented ID number and a text tag (set by the user on snapshot creation).<br />
<br />
=== Running the virtual machine in immutable mode ===<br />
<br />
It is possible to run a virtual machine in a frozen state so that all changes will be discarded when the virtual machine is powered off just by running QEMU with the {{ic|-snapshot}} parameter. When the disk image is written by the guest, changes will be saved in a temporary file in {{ic|/tmp}} and will be discarded when QEMU halts.<br />
<br />
However, if a machine is running in frozen mode it is still possible to save the changes to the disk image if it is afterwards desired by using the monitor console and running the following command:<br />
<br />
(qemu) commit all<br />
<br />
If snapshots are created when running in frozen mode they will be discarded as soon as QEMU is exited unless changes are explicitly commited to disk, as well.<br />
<br />
=== Pause and power options via the monitor console ===<br />
<br />
Some operations of a physical machine can be emulated by QEMU using some monitor commands:<br />
<br />
* {{ic|system_powerdown}} will send an ACPI shutdown request to the virtual machine. This effect is similar to the power button in a physical machine.<br />
* {{ic|system_reset}} will reset the virtual machine similarly to a reset button in a physical machine. This operation can cause data loss and file system corruption since the virtual machine is not cleanly restarted.<br />
* {{ic|stop}} will pause the virtual machine.<br />
* {{ic|cont}} will resume a virtual machine previously paused.<br />
<br />
=== Taking screenshots of the virtual machine ===<br />
<br />
Screenshots of the virtual machine graphic display can be obtained in the PPM format by running the following command in the monitor console:<br />
<br />
(qemu) screendump ''file.ppm''<br />
<br />
== QEMU machine protocol ==<br />
<br />
The QEMU machine protocol (QMP) is a JSON-based protocol which allows applications to control a QEMU instance. Similarly to the [[#QEMU monitor]] it offers ways to interact with a running machine and the JSON protocol allows to do it programmatically. The description of all the QMP commands can be found in [https://raw.githubusercontent.com/coreos/qemu/master/qmp-commands.hx qmp-commands].<br />
<br />
=== Start QMP ===<br />
<br />
The usual way to control the guest using the QMP protocol, is to open a TCP socket when launching the machine using the {{ic|-qmp}} option. Here it is using for example the TCP port 4444:<br />
<br />
$ qemu-system-x86_64 ''[...]'' -qmp tcp:localhost:4444,server,nowait<br />
<br />
Then one way to communicate with the QMP agent is to use [[netcat]]:<br />
<br />
{{hc|nc localhost 4444|{"QMP": {"version": {"qemu": {"micro": 0, "minor": 1, "major": 3}, "package": ""}, "capabilities": []} } }}<br />
<br />
At this stage, the only command that can be recognized is {{ic|qmp_capabilities}}, so that QMP enters into command mode. Type:<br />
<br />
{"execute": "qmp_capabilities"}<br />
<br />
Now, QMP is ready to receive commands, to retrieve the list of recognized commands, use:<br />
<br />
{"execute": "query-commands"}<br />
<br />
=== Live merging of child image into parent image ===<br />
<br />
It is possible to merge a running snapshot into its parent by issuing a {{ic|block-commit}} command. In its simplest form the following line will commit the child into its parent:<br />
<br />
{"execute": "block-commit", "arguments": {"device": "''devicename''"}}<br />
<br />
Upon reception of this command, the handler looks for the base image and converts it from read only to read write mode and then runs the commit job.<br />
<br />
Once the ''block-commit'' operation has completed, the event {{ic|BLOCK_JOB_READY}} will be emitted, signalling that the synchronization has finished. The job can then be gracefully completed by issuing the command {{ic|block-job-complete}}:<br />
<br />
{"execute": "block-job-complete", "arguments": {"device": "''devicename''"}}<br />
<br />
Until such a command is issued, the ''commit'' operation remains active.<br />
After successful completion, the base image remains in read write mode and becomes the new active layer. On the other hand, the child image becomes invalid and it is the responsibility of the user to clean it up.<br />
<br />
{{Tip|The list of device and their names can be retrieved by executing the command {{ic|query-block}} and parsing the results. The device name is in the {{ic|device}} field, for example {{ic|ide0-hd0}} for the hard disk in this example: {{hc|{"execute": "query-block"}|{"return": [{"io-status": "ok", "device": "'''ide0-hd0'''", "locked": false, "removable": false, "inserted": {"iops_rd": 0, "detect_zeroes": "off", "image": {"backing-image": {"virtual-size": 27074281472, "filename": "parent.qcow2", ... } }} }}<br />
<br />
=== Live creation of a new snapshot ===<br />
<br />
To create a new snapshot out of a running image, run the command:<br />
<br />
{"execute": "blockdev-snapshot-sync", "arguments": {"device": "''devicename''","snapshot-file": "''new_snapshot_name''.qcow2"}}<br />
<br />
This creates an overlay file named {{ic|''new_snapshot_name''.qcow2}} which then becomes the new active layer.<br />
<br />
== Tips and tricks ==<br />
=== Improve virtual machine performance ===<br />
<br />
There are a number of techniques that you can use to improve the performance of the virtual machine. For example:<br />
<br />
* Apply [[#Enabling KVM]]: add {{ic|-enable-kvm}} to the QEMU start command you use.<br />
* Use the {{ic|-cpu host}} option to make QEMU emulate the host's exact CPU. If you do not do this, it may be trying to emulate a more generic CPU.<br />
* Especially for Windows guests, enable [http://blog.wikichoon.com/2014/07/enabling-hyper-v-enlightenments-with-kvm.html Hyper-V enlightenments]: {{ic|1=-cpu host,hv_relaxed,hv_spinlocks=0x1fff,hv_vapic,hv_time}}.<br />
* If the host machine has multiple cores, assign the guest more cores using the {{ic|-smp}} option.<br />
* Make sure you have assigned the virtual machine enough memory. By default, QEMU only assigns 128 MiB of memory to each virtual machine. Use the {{ic|-m}} option to assign more memory. For example, {{ic|-m 1024}} runs a virtual machine with 1024 MiB of memory.<br />
* If supported by drivers in the guest operating system, use [http://wiki.libvirt.org/page/Virtio virtio] for network and/or block devices. For example:<br />
$ qemu-system-x86_64 -net nic,model=virtio -net tap,if=tap0,script=no -drive file=''disk_image'',media=disk,if=virtio<br />
* Use TAP devices instead of user-mode networking. See [[#Tap networking with QEMU]].<br />
* If the guest OS is doing heavy writing to its disk, you may benefit from certain mount options on the host's file system. For example, you can mount an [[Ext4|ext4 file system]] with the option {{ic|1=barrier=0}}. You should read the documentation for any options that you change because sometimes performance-enhancing options for file systems come at the cost of data integrity.<br />
* If you have a raw disk image, you may want to disable the cache:<br />
$ qemu-system-x86_64 -drive file=''disk_image'',if=virtio,'''cache=none'''<br />
* Use the native Linux AIO:<br />
$ qemu-system-x86_64 -drive file=''disk_image'',if=virtio''',aio=native,cache.direct=on'''<br />
* If you are running multiple virtual machines concurrently that all have the same operating system installed, you can save memory by enabling [[wikipedia:Kernel_SamePage_Merging_(KSM)|kernel same-page merging]]. See [[#Enabling KSM]].<br />
* In some cases, memory can be reclaimed from running virtual machines by running a memory ballooning driver in the guest operating system and launching QEMU using {{ic|-device virtio-balloon}}.<br />
* It is possible to use a emulation layer for an ICH-9 AHCI controller (although it may be unstable). The AHCI emulation supports [[Wikipedia:Native_Command_Queuing|NCQ]], so multiple read or write requests can be outstanding at the same time:<br />
$ qemu-system-x86_64 -drive id=disk,file=''disk_image'',if=none -device ich9-ahci,id=ahci -device ide-drive,drive=disk,bus=ahci.0<br />
<br />
See http://www.linux-kvm.org/page/Tuning_KVM for more information.<br />
<br />
=== Starting QEMU virtual machines on boot ===<br />
<br />
==== With libvirt ====<br />
<br />
If a virtual machine is set up with [[libvirt]], it can be configured with {{ic|virsh autostart}} or through the ''virt-manager'' GUI to start at host boot by going to the Boot Options for the virtual machine and selecting "Start virtual machine on host boot up".<br />
<br />
==== With systemd service ====<br />
<br />
To run QEMU VMs on boot, you can use following systemd unit and config.<br />
<br />
{{hc|/etc/systemd/system/qemu@.service|2=<br />
[Unit]<br />
Description=QEMU virtual machine<br />
<br />
[Service]<br />
Environment="haltcmd=kill -INT $MAINPID"<br />
EnvironmentFile=/etc/conf.d/qemu.d/%i<br />
ExecStart=/usr/bin/qemu-system-x86_64 -name %i -enable-kvm -m 512 -nographic $args<br />
ExecStop=/usr/bin/bash -c ${haltcmd}<br />
ExecStop=/usr/bin/bash -c 'while nc localhost 7100; do sleep 1; done'<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
}}<br />
<br />
{{Note|This service will wait for the console port to be released, which means that the VM has been shutdown, to graciously end.}}<br />
<br />
Then create per-VM configuration files, named {{ic|/etc/conf.d/qemu.d/''vm_name''}}, with the variables {{ic|args}} and {{ic|haltcmd}} set. Example configs:<br />
<br />
{{hc|/etc/conf.d/qemu.d/one|2=<br />
args="-hda /dev/vg0/vm1 -serial telnet:localhost:7000,server,nowait,nodelay \<br />
-monitor telnet:localhost:7100,server,nowait,nodelay -vnc :0"<br />
<br />
haltcmd="echo 'system_powerdown' {{!}} nc localhost 7100" # or netcat/ncat}}<br />
<br />
{{hc|/etc/conf.d/qemu.d/two|2=<br />
args="-hda /srv/kvm/vm2 -serial telnet:localhost:7001,server,nowait,nodelay -vnc :1"<br />
<br />
haltcmd="ssh powermanager@vm2 sudo poweroff"}}<br />
<br />
The description of the variables is the following:<br />
<br />
* {{ic|args}} - QEMU command line arguments to be used.<br />
* {{ic|haltcmd}} - Command to shut down a VM safely. In the first example, the QEMU monitor is exposed via telnet using {{ic|-monitor telnet:..}} and the VMs are powered off via ACPI by sending {{ic|system_powerdown}} to monitor with the {{ic|nc}} command. In the other example, SSH is used.<br />
<br />
To set which virtual machines will start on boot-up, [[enable]] the {{ic|qemu@''vm_name''.service}} systemd unit.<br />
<br />
=== Mouse integration ===<br />
<br />
To prevent the mouse from being grabbed when clicking on the guest operating system's window, add the options {{ic|-usb -device usb-tablet}}. This means QEMU is able to report the mouse position without having to grab the mouse. This also overrides PS/2 mouse emulation when activated. For example:<br />
<br />
$ qemu-system-x86_64 -hda ''disk_image'' -m 512 -usb -device usb-tablet<br />
<br />
If that does not work, try using {{ic|-vga qxl}} parameter, also look at the instructions [[#Mouse cursor is jittery or erratic]].<br />
<br />
=== Pass-through host USB device ===<br />
<br />
It is possible to access the physical device connected to a USB port of the host from the guest. The first step is to identify where the device is connected, this can be found running the {{ic|lsusb}} command. For example:<br />
<br />
{{hc|$ lsusb|<br />
...<br />
Bus '''003''' Device '''007''': ID '''0781''':'''5406''' SanDisk Corp. Cruzer Micro U3<br />
}}<br />
<br />
The outputs in bold above will be useful to identify respectively the ''host_bus'' and ''host_addr'' or the ''vendor_id'' and ''product_id''.<br />
<br />
In qemu, the idea is to emulate an EHCI (USB 2) or XHCI (USB 3) controller with the option {{ic|1=-device usb-ehci,id=ehci}} or {{ic|1=-device qemu-xhci,id=xhci}} respectively and then attach the physical device to it with the option {{ic|1=-device usb-host,..}}. We will consider that ''controller_id'' is either {{ic|ehci}} or {{ic|xhci}} for the rest of this section.<br />
<br />
Then, there are two ways to connect to the USB of the host with qemu:<br />
<br />
# Identify the device and connect to it on any bus and address it is attached to on the host, the generic syntax is: {{bc|1=-device usb-host,bus=''controller_id''.0,vendorid=0x''vendor_id'',productid=0x''product_id''}}Applied to the device used in the example above, it becomes:{{bc|1=-device usb-ehci,id=ehci -device usb-host,bus=ehci.0,vendorid=0x'''0781''',productid=0x'''5406'''}}One can also add the {{ic|1=...,port=''port_number''}} setting to the previous option to specify in which physical port of the virtual controller the device should be attached, useful in the case one wants to add multiple usb devices to the VM.<br />
# Starting from QEMU 5.1.0, the {{ic|usb-host}} {{ic|hostdevice}} property can also be used: {{bc|1=-device qemu-xhci,id=xhci -device usb-host,bus=xhci.0,hostdevice=/dev/bus/usb/002/004}}<br />
# Attach whatever is connected to a given USB bus and address, the syntax is:{{bc|1=-device usb-host,bus=''controller_id''.0,hostbus=''host_bus'',host_addr=''host_addr''}}Applied to the bus and the address in the example above, it becomes:{{bc|1=-device usb-ehci,id=ehci -device usb-host,bus=ehci.0,hostbus='''3''',hostaddr='''7'''}}<br />
<br />
{{Note|If you encounter permission errors when running QEMU, see [[udev#About udev rules]] for information on how to set permissions of the device.}}<br />
<br />
=== USB redirection with SPICE ===<br />
<br />
When using [[#SPICE]] it is possible to redirect USB devices from the client to the virtual machine without needing to specify them in the QEMU command. It is possible to configure the number of USB slots available for redirected devices (the number of slots will determine the maximum number of devices which can be redirected simultaneously). The main advantages of using SPICE for redirection compared to the previously-mentioned {{ic|-usbdevice}} method is the possibility of hot-swapping USB devices after the virtual machine has started, without needing to halt it in order to remove USB devices from the redirection or adding new ones. This method of USB redirection also allows us to redirect USB devices over the network, from the client to the server. In summary, it is the most flexible method of using USB devices in a QEMU virtual machine.<br />
<br />
We need to add one EHCI/UHCI controller per available USB redirection slot desired as well as one SPICE redirection channel per slot. For example, adding the following arguments to the QEMU command you use for starting the virtual machine in SPICE mode will start the virtual machine with three available USB slots for redirection:<br />
<br />
{{bc|1=-device ich9-usb-ehci1,id=usb \<br />
-device ich9-usb-uhci1,masterbus=usb.0,firstport=0,multifunction=on \<br />
-device ich9-usb-uhci2,masterbus=usb.0,firstport=2 \<br />
-device ich9-usb-uhci3,masterbus=usb.0,firstport=4 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev1 -device usb-redir,chardev=usbredirchardev1,id=usbredirdev1 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev2 -device usb-redir,chardev=usbredirchardev2,id=usbredirdev2 \<br />
-chardev spicevmc,name=usbredir,id=usbredirchardev3 -device usb-redir,chardev=usbredirchardev3,id=usbredirdev3}}<br />
See [https://www.spice-space.org/usbredir.html SPICE/usbredir] for more information.<br />
<br />
Both {{ic|spicy}} from {{Pkg|spice-gtk}} (''Input > Select USB Devices for redirection'') and {{ic|remote-viewer}} from {{pkg|virt-viewer}} (''File > USB device selection'') support this feature. Please make sure that you have installed the necessary SPICE Guest Tools on the virtual machine for this functionality to work as expected (see the [[#SPICE]] section for more information).<br />
<br />
{{Warning|Keep in mind that when a USB device is redirected from the client, it will not be usable from the client operating system itself until the redirection is stopped. It is specially important to never redirect the input devices (namely mouse and keyboard), since it will be then difficult to access the SPICE client menus to revert the situation, because the client will not respond to the input devices after being redirected to the virtual machine.}}<br />
<br />
=== Enabling KSM ===<br />
<br />
Kernel Samepage Merging (KSM) is a feature of the Linux kernel that allows for an application to register with the kernel to have its pages merged with other processes that also register to have their pages merged. The KSM mechanism allows for guest virtual machines to share pages with each other. In an environment where many of the guest operating systems are similar, this can result in significant memory savings.<br />
<br />
{{Note|Although KSM may reduce memory usage, it may increase CPU usage. Also note some security issues may occur, see [[Wikipedia:Kernel same-page merging]].}}<br />
<br />
To enable KSM:<br />
<br />
# echo 1 > /sys/kernel/mm/ksm/run<br />
<br />
To make it permanent, use [[systemd#systemd-tmpfiles - temporary files|systemd's temporary files]]:<br />
<br />
{{hc|/etc/tmpfiles.d/ksm.conf|<br />
w /sys/kernel/mm/ksm/run - - - - 1<br />
}}<br />
<br />
If KSM is running, and there are pages to be merged (i.e. at least two similar VMs are running), then {{ic|/sys/kernel/mm/ksm/pages_shared}} should be non-zero. See https://www.kernel.org/doc/html/latest/admin-guide/mm/ksm.html for more information.<br />
<br />
{{Tip|An easy way to see how well KSM is performing is to simply print the contents of all the files in that directory: {{bc|$ grep . /sys/kernel/mm/ksm/*}}}}<br />
<br />
=== Multi-monitor support ===<br />
<br />
The Linux QXL driver supports four heads (virtual screens) by default. This can be changed via the {{ic|1=qxl.heads=N}} kernel parameter.<br />
<br />
The default VGA memory size for QXL devices is 16M (VRAM size is 64M). This is not sufficient if you would like to enable two 1920x1200 monitors since that requires 2 × 1920 × 4 (color depth) × 1200 = 17.6 MiB VGA memory. This can be changed by replacing {{ic|-vga qxl}} by {{ic|<nowiki>-vga none -device qxl-vga,vgamem_mb=32</nowiki>}}. If you ever increase vgamem_mb beyond 64M, then you also have to increase the {{ic|vram_size_mb}} option.<br />
<br />
=== Copy and paste ===<br />
<br />
One way to share the clipboard between the host and the guest is to enable the SPICE remote desktop protocol and access the client with a SPICE client.<br />
One needs to follow the steps described in [[#SPICE]]. A guest run this way will support copy paste with the host.<br />
<br />
=== Windows-specific notes ===<br />
<br />
QEMU can run any version of Windows from Windows 95 through Windows 10.<br />
<br />
It is possible to run [[Windows PE]] in QEMU.<br />
<br />
==== Fast startup ====<br />
<br />
{{Note|An administrator account is required to change power settings.}}<br />
<br />
For Windows 8 (or later) guests it is better to disable "Turn on fast startup (recommended)" from the Power Options of the Control Panel as explained in the following [https://www.tenforums.com/tutorials/4189-turn-off-fast-startup-windows-10-a.html forum page], as it causes the guest to hang during every other boot.<br />
<br />
Fast Startup may also need to be disabled for changes to the {{ic|-smp}} option to be properly applied.<br />
<br />
==== Remote Desktop Protocol ====<br />
<br />
If you use a MS Windows guest, you might want to use RDP to connect to your guest VM. If you are using a VLAN or are not in the same network as the guest, use:<br />
<br />
$ qemu-system-x86_64 -nographic -net user,hostfwd=tcp::5555-:3389<br />
<br />
Then connect with either {{Pkg|rdesktop}} or {{Pkg|freerdp}} to the guest. For example:<br />
<br />
$ xfreerdp -g 2048x1152 localhost:5555 -z -x lan<br />
<br />
=== Clone Linux system installed on physical equipment ===<br />
<br />
Linux system installed on physical equipment can be cloned for running on QEMU vm. See [https://coffeebirthday.wordpress.com/2018/09/14/clone-linux-system-for-qemu-virtual-machine/ Clone Linux system from hardware for QEMU virtual machine]<br />
<br />
=== Chrooting into arm/arm64 environment from x86_64 ===<br />
<br />
Sometimes it is easier to work directly on a disk image instead of the real ARM based device. This can be achieved by mounting an SD card/storage containing the ''root'' partition and chrooting into it.<br />
<br />
Another use case for an ARM chroot is building ARM packages on an x86_64 machine - {{AUR|armutils-git}} can be used for that. Here, the chroot environment can be created from an image tarball from [https://archlinuxarm.org Arch Linux ARM] - see [https://nerdstuff.org/posts/2020/2020-003_simplest_way_to_create_an_arm_chroot/] for a detailed description of this approach.<br />
<br />
Either way, from the chroot it should be possible to run ''pacman'' and install more packages, compile large libraries etc. Since the executables are for the ARM architecture, the translation to x86 needs to be performed by [[QEMU]].<br />
<br />
Install {{AUR|binfmt-qemu-static}} and {{AUR|qemu-user-static}} from the [[AUR]] on the x86_64 machine/host. ''binfmt-qemu-static'' will take care of registering the qemu binaries to binfmt service.<br />
<br />
[[Restart]] {{ic|systemd-binfmt.service}}<br />
<br />
{{AUR|qemu-user-static}} is needed to allow the execution of compiled programs from other architectures. This is similar to what is provided by {{Pkg|qemu-arch-extra}}, but the "static" variant is required for chroot. Examples:<br />
<br />
qemu-arm-static path_to_sdcard/usr/bin/ls<br />
qemu-aarch64-static path_to_sdcard/usr/bin/ls<br />
<br />
These two lines execute the {{ic|ls}} command compiled for 32-bit ARM and 64-bit ARM respectively. Note that this will not work without chrooting, because it will look for libraries not present in the host system.<br />
<br />
{{AUR|qemu-user-static}} allows automatically prefixing the ARM exectuable with {{ic|qemu-arm-static}} or {{ic|qemu-aarch64-static}}.<br />
<br />
Make sure that the ARM executable support is active:<br />
<br />
{{hc|$ ls /proc/sys/fs/binfmt_misc|<br />
qemu-aarch64 qemu-arm qemu-cris qemu-microblaze qemu-mipsel qemu-ppc64 qemu-riscv64 qemu-sh4 qemu-sparc qemu-sparc64 status<br />
qemu-alpha qemu-armeb qemu-m68k qemu-mips qemu-ppc qemu-ppc64abi32 qemu-s390x qemu-sh4eb qemu-sparc32plus register<br />
}}<br />
<br />
Each executable must be listed.<br />
<br />
If it is not active, reinstall ''binfmt-qemu-static'' and restart ''systemd-binfmt''.<br />
<br />
Mount the SD card to {{ic|/mnt/scdard}} (the device name may be different).<br />
<br />
# mkdir -p /mnt/sdcard<br />
# mount /dev/mmcblk0p2 /mnt/sdcard<br />
<br />
Mount boot partition if needed (again, use the suitable device name):<br />
<br />
# mount /dev/mmcblk0p1 /mnt/sdcard/boot<br />
<br />
Finally ''chroot'' into the SD card root as described in [[Change root#Using chroot]]:<br />
<br />
# chroot /mnt/sdcard /bin/bash<br />
<br />
Alternatively, you can use ''arch-chroot'' from {{Pkg|arch-install-scripts}}, as it will provide an easier way to get network support:<br />
# arch-chroot /mnt/sdcard /bin/bash<br />
<br />
You can also use ''systemd-nspawn'' to chroot into the ARM environment:<br />
# systemd-nspawn -D /mnt/sdcard -M myARMMachine --bind-ro=/etc/resolv.conf<br />
<br />
{{ic|1=--bind-ro=/etc/resolv.conf}} is optional and gives a working network DNS inside the chroot<br />
<br />
== Troubleshooting ==<br />
<br />
=== Mouse cursor is jittery or erratic ===<br />
<br />
If the cursor jumps around the screen uncontrollably, entering this on the terminal before starting QEMU might help:<br />
<br />
$ export SDL_VIDEO_X11_DGAMOUSE=0<br />
<br />
If this helps, you can add this to your {{ic|~/.bashrc}} file.<br />
<br />
=== No visible Cursor ===<br />
<br />
Add {{ic|-show-cursor}} to QEMU's options to see a mouse cursor.<br />
<br />
If that still does not work, make sure you have set your display device appropriately, for example: {{ic|-vga qxl}}.<br />
<br />
Another option to try is {{ic|-usb -device usb-tablet}} as mentioned in [[#Mouse integration]]. This overrides the default PS/2 mouse emulation and synchronizes pointer location between host and guest as an added bonus.<br />
<br />
=== Two different mouse cursors are visible ===<br />
<br />
Apply the tip [[#Mouse integration]].<br />
<br />
=== Keyboard issues when using VNC ===<br />
<br />
When using VNC, you might experience keyboard problems described (in gory details) [https://www.berrange.com/posts/2010/07/04/more-than-you-or-i-ever-wanted-to-know-about-virtual-keyboard-handling/ here]. The solution is ''not'' to use the {{ic|-k}} option on QEMU, and to use {{ic|gvncviewer}} from {{Pkg|gtk-vnc}}. See also [http://www.mail-archive.com/libvir-list@redhat.com/msg13340.html this] message posted on libvirt's mailing list.<br />
<br />
=== Keyboard seems broken or the arrow keys do not work ===<br />
<br />
Should you find that some of your keys do not work or "press" the wrong key (in particular, the arrow keys), you likely need to specify your keyboard layout as an option. The keyboard layouts can be found in {{ic|/usr/share/qemu/keymaps}}.<br />
<br />
$ qemu-system-x86_64 -k ''keymap'' ''disk_image''<br />
<br />
=== Guest display stretches on window resize ===<br />
<br />
To restore default window size, press {{ic|Ctrl+Alt+u}}.<br />
<br />
=== ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy ===<br />
<br />
If an error message like this is printed when starting QEMU with {{ic|-enable-kvm}} option:<br />
<br />
ioctl(KVM_CREATE_VM) failed: 16 Device or resource busy<br />
failed to initialize KVM: Device or resource busy<br />
<br />
that means another [[hypervisor]] is currently running. It is not recommended or possible to run several hypervisors in parallel.<br />
<br />
=== libgfapi error message ===<br />
<br />
The error message displayed at startup:<br />
<br />
Failed to open module: libgfapi.so.0: cannot open shared object file: No such file or directory<br />
<br />
[[Install]] {{pkg|glusterfs}} or ignore the error message as GlusterFS is a optional dependency.<br />
<br />
=== Kernel panic on LIVE-environments===<br />
<br />
If you start a live-environment (or better: booting a system) you may encounter this:<br />
<br />
[ end Kernel panic - not syncing: VFS: Unable to mount root fs on unknown block(0,0)<br />
<br />
or some other boot hindering process (e.g. cannot unpack initramfs, cant start service foo).<br />
Try starting the VM with the {{ic|-m VALUE}} switch and an appropriate amount of RAM, if the ram is to low you will probably encounter similar issues as above/without the memory-switch.<br />
<br />
=== Windows 7 guest suffers low-quality sound ===<br />
<br />
Using the {{ic|hda}} audio driver for Windows 7 guest may result in low-quality sound. Changing the audio driver to {{ic|ac97}} by passing the {{ic|-soundhw ac97}} arguments to QEMU and installing the AC97 driver from [https://www.realtek.com/en/component/zoo/category/pc-audio-codecs-ac-97-audio-codecs-software Realtek AC'97 Audio Codecs] in the guest may solve the problem. See [https://bugzilla.redhat.com/show_bug.cgi?id=1176761#c16 Red Hat Bugzilla – Bug 1176761] for more information.<br />
<br />
=== Could not access KVM kernel module: Permission denied ===<br />
<br />
If you encounter the following error:<br />
<br />
libvirtError: internal error: process exited while connecting to monitor: Could not access KVM kernel module: Permission denied failed to initialize KVM: Permission denied<br />
<br />
Systemd 234 assigns a dynamic ID for the {{ic|kvm}} group (see {{Bug|54943}}). To avoid this error, you need edit the file {{ic|/etc/libvirt/qemu.conf}} and change the line with {{ic|1=group = "78"}} to {{ic|1=group = "kvm"}}.<br />
<br />
=== "System Thread Exception Not Handled" when booting a Windows VM ===<br />
<br />
Windows 8 or Windows 10 guests may raise a generic compatibility exception at boot, namely "System Thread Exception Not Handled", which tends to be caused by legacy drivers acting strangely on real machines. On KVM machines this issue can generally be solved by setting the CPU model to {{ic|core2duo}}.<br />
<br />
=== Certain Windows games/applications crashing/causing a bluescreen ===<br />
<br />
Occasionally, applications running in the VM may crash unexpectedly, whereas they would run normally on a physical machine. If, while running {{ic|dmesg -wH}}, you encounter an error mentioning {{ic|MSR}}, the reason for those crashes is that KVM injects a [[wikipedia:General protection fault|General protection fault]] (GPF) when the guest tries to access unsupported [[wikipedia:Model-specific register|Model-specific registers]] (MSRs) - this often results in guest applications/OS crashing. A number of those issues can be solved by passing the {{ic|1=ignore_msrs=1}} option to the KVM module, which will ignore unimplemented MSRs.<br />
<br />
{{hc|/etc/modprobe.d/kvm.conf|2=<br />
...<br />
options kvm ignore_msrs=1<br />
...<br />
}}<br />
<br />
Cases where adding this option might help:<br />
<br />
* GeForce Experience complaining about an unsupported CPU being present.<br />
* StarCraft 2 and L.A. Noire reliably blue-screening Windows 10 with {{ic|KMODE_EXCEPTION_NOT_HANDLED}}. The blue screen information does not identify a driver file in these cases.<br />
<br />
{{Warning|While this is normally safe and some applications might not work without this, silently ignoring unknown MSR accesses could potentially break other software within the VM or other VMs.}}<br />
<br />
=== Applications in the VM experience long delays or take a long time to start ===<br />
<br />
This may be caused by insufficient available entropy in the VM. Consider allowing the guest to access the hosts's entropy pool by adding a [https://wiki.qemu.org/Features/VirtIORNG VirtIO RNG device] to the VM, or by installing an entropy generating daemon such as [[Haveged]].<br />
<br />
Anecdotally, OpenSSH takes a while to start accepting connections under insufficient entropy, without the logs revealing why.<br />
<br />
=== High interrupt latency and microstuttering ===<br />
<br />
This problem manifests itself as small pauses (stutters) and is particularly noticeable in graphics-intensive applications, such as games.<br />
<br />
* One of the causes is CPU power saving features, which are controlled by [[CPU frequency scaling]]. Change this to {{ic|performance}} for all processor cores. <br />
* Another possible cause is PS/2 inputs. Switch from PS/2 to Virtio inputs, see [[PCI passthrough via OVMF#Passing keyboard/mouse via Evdev]].<br />
<br />
=== QXL video causes low resolution ===<br />
<br />
QEMU 4.1.0 introduced a regression where QXL video can fall back to low resolutions, when being displayed through spice. [https://bugs.launchpad.net/qemu/+bug/1843151] For example, when KMS starts, text resolution may become as low as 4x10 characters. When trying to increase GUI resolution, it may go to the lowest supported resolution.<br />
<br />
As a workaround, create your device in this form:<br />
<br />
-device qxl-vga,max_outputs=1...<br />
<br />
=== Hang during VM initramfs ===<br />
<br />
Linux 5.2.11 introduced a KVM regression where under some circumstances a VM may permanently hang during the early boot phase, when the initramfs is being loaded or ran. [https://www.spinics.net/lists/kvm/msg195171.html] Linux 5.3 fixed the regression. The host shows qemu using 100% CPU * number of virtual CPUs. Reported case is with a host using hyperthreading, and a VM being given more than host's {{ic|nproc}}/2 virtual CPUs. It is unknown what exact circumstances trigger one of the threads to delete a memory region to cause this. The workarounds are:<br />
<br />
* Upgrade to Linux 5.3.<br />
* Downgrade to Linux 5.2.10<br />
* Until fixed, try giving the VM no more than the host's {{ic|nproc}}/2 virtual CPUs<br />
* Custom compile linux, reverting commit 2ad350fb4c (note this re-introduces a regression triggered when removing a memslot)<br />
<br />
=== VM does not boot when using a Secure Boot enabled OVMF ===<br />
<br />
{{ic|/usr/share/edk2-ovmf/x64/OVMF_CODE.secboot.fd}} from {{Pkg|edk2-ovmf}} is built with [[Wikipedia:System Management Mode|SMM]] support. If S3 support is not disabled in the VM, then the VM might not boot at all.<br />
<br />
Add the {{ic|1=-global ICH9-LPC.disable_s3=1}} option to the ''qemu'' command.<br />
<br />
See {{Bug|59465}} and https://github.com/tianocore/edk2/blob/master/OvmfPkg/README for more details and the required options to use Secure Boot in QEMU.<br />
<br />
=== Guest CPU interrupts are not firing ===<br />
<br />
If you are writing your own operating system by following the [https://wiki.osdev.org/ OSDev wiki], or are simply getting stepping through the guest architecture assembly code using QEMU's {{ic|gdb}} interface using the {{ic|-s}} flag, it's useful to know that many emulators, QEMU included, usually implement some CPU interrupts leaving many hardware interrupts unimplemented. One way to know if your code if firing an interrupt, is by using:<br />
<br />
-d int<br />
<br />
to enable showing interrupts/exceptions on stdout.<br />
<br />
To see what other guest debugging features QEMU has to offer, see:<br />
<br />
qemu-system-x86_64 -d help<br />
<br />
or replace {{ic|x86_64}} for your chosen guest architecture.<br />
<br />
== See also ==<br />
<br />
* [http://qemu.org Official QEMU website]<br />
* [http://www.linux-kvm.org Official KVM website]<br />
* [http://qemu.weilnetz.de/qemu-doc.html QEMU Emulator User Documentation]<br />
* [[Wikibooks:QEMU|QEMU Wikibook]]<br />
* [http://alien.slackbook.org/dokuwiki/doku.php?id=slackware:qemu Hardware virtualization with QEMU] by AlienBOB (last updated in 2008)<br />
* [http://blog.falconindy.com/articles/build-a-virtual-army.html Building a Virtual Army] by Falconindy<br />
* [http://git.qemu.org/?p=qemu.git;a=tree;f=docs Lastest docs]<br />
* [http://qemu.weilnetz.de/ QEMU on Windows]<br />
* [[wikipedia:Qemu|Wikipedia]]<br />
* [[debian:QEMU|Debian Wiki - QEMU]]<br />
* [https://people.gnome.org/~markmc/qemu-networking.html QEMU Networking on gnome.org]<br />
* [http://bsdwiki.reedmedia.net/wiki/networking_qemu_virtual_bsd_systems.html Networking QEMU Virtual BSD Systems]<br />
* [https://www.gnu.org/software/hurd/hurd/running/qemu.html QEMU on gnu.org]<br />
* [https://wiki.freebsd.org/qemu QEMU on FreeBSD as host]<br />
* [https://wiki.mikejung.biz/KVM_/_Xen KVM/QEMU Virtio Tuning and SSD VM Optimization Guide]<br />
* [https://doc.opensuse.org/documentation/leap/virtualization/html/book-virt/part-virt-qemu.html Managing Virtual Machines with QEMU - openSUSE documentation]<br />
* [https://www.ibm.com/support/knowledgecenter/en/linuxonibm/liaat/liaatkvm.htm KVM on IBM Knowledge Center]</div>Malcontenthttps://wiki.archlinux.org/index.php?title=Talk:Bitcoin&diff=586792Talk:Bitcoin2019-10-21T00:29:51Z<p>Malcontent: /* Full node (blockchain size) */</p>
<hr />
<div>== <s>Links to software packages</s> ==<br />
It would be useful to have links to software packages here. I know there is significant controversy in the bitcoin space, but I don't think that should preclude listing related software packages. My edit including links to the core & bitcoin-cash qt clients was reverted with "Bitcoin Cash is NOT bitcoin and it's better not to list it here, please go back to Discussion". Bitcoin cash is very overtly a fork of the bitcoin blockchain - with bch proponents contending it IS bitcoin & core proponents contending it is not. I'm not partial to either side, but bch is a part of bitcoin's history. That aside, I think it would be useful to at least mention main repo packages like (core's) bitcoin-qt, which was what brought me to this wiki page in the first place. Since bch client is AUR and this area is contentious tabling inclusion of fork-from-core software could make sense pending further discussion. Now ok to include bitcoin-qt link? Just trying to improve the wiki...thanks for input in this regard.--[[User:Xris|Xris]] ([[User talk:Xris|talk]]) 21:25, 1 October 2018 (UTC)<br />
<br />
I am adding link to repo package now.--[[User:Xris|Xris]] ([[User talk:Xris|talk]]) 11:45, 3 October 2018 (UTC)<br />
<br />
:Reverted due to previous consensus to avoid flame wars. Please read the [https://wiki.archlinux.org/index.php?title=Talk:Bitcoin&oldid=465690 previous discussions] for the reasoning. -- [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 15:46, 3 October 2018 (UTC)<br />
:: [[User:Lahwaacz|Lahwaacz]]: about your last edit: [https://wiki.archlinux.org/index.php?title=Bitcoin&type=revision&diff=545785&oldid=545731 Informational sites: this is not an informational site - it is biased towards one implementation]:<br />
:: I will just say that you can't be neutral about this issue, Bitcoin Core has the [http://luke.dashjr.org/programs/bitcoin/files/charts/software.html majority of the nodes deployment], and it is Bitcoin through the consensus of those nodes. The nodes are what determine what is Bitcoin and what isn't, so I think reverting my edit was a mistake, and you should revert back to my change -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 01:16, 5 October 2018 (UTC)<br />
<br />
::: We're not going through this whole "discussion" again. The article stays in revision [https://wiki.archlinux.org/index.php?title=Bitcoin&oldid=545787]. Closing. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 08:10, 5 October 2018 (UTC)<br />
:::: OK. I understand you don't want to create another flame war, I can respect that. However, the article is about Bitcoin, and Bitcoin Core is the de facto Bitcoin client. This is fact, not bias, and I feel the article does a poor job at informing the user about this fact. -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 21:25, 5 October 2018 (UTC)<br />
<br />
Thank you Lahwaacz for linking the prior discussion. I'm surprised and saddened by reading through some of those threads. I frankly find much of it confusing, as it refers to IRC discussions with mentions of ultimatums without clear details. What exactly is the controversy relating to linking to software packages? There are vague claims about making packages seem like "ads" or being "scary". I've been using Arch as my primary desktop for a few years in large part due to the great, task-focused, and impartial Arch wiki. This page does not fit that bill at all, and is merely confusing to those seeking to setup and configure bitcoin software on Arch (whatever the package type). Despite the verbosity regarding consensus there is no information about how to configure bitcoin on Arch. There are seemingly Arch-specific idiosyncrasies with bitcoin, as evidenced by the [https://bugs.archlinux.org/task/60235?project=5&string=bitcoin-qt recent bug] that makes core bitcoin-qt not start and just hang - this is what led me to this page for these edits in the first place. I appreciate the shenanigans & proposals from both the e.g. core (and related horrific r/bitcoin) and competing software camps (e.g. bch), but pretending that none of these exist just makes it more confusing for those looking to configure related software on Arch. Given the wikis and FAQs of other distributions, and even the bitcoin software developers themselves, are lacking in many ways, it seems an opportunity for clarity in software setup (in addition to Arch perhaps encountering unique errors in bitcoin code given rolling release support of newer dependent library packages). While not well updated and mainly deferring to core, other distributions have not had trouble at least providing basic information about the core packages ([https://fedoraproject.org/wiki/BITCOIN Fedora], [https://help.ubuntu.com/community/bitcoin Ubuntu]). At minimum providing information about configuring the core reference implementation would be of great practical utility. If you are going to censor edits on how to configure bitcoin related software (as has seemingly been done many times), I would at least request a clear explicit explanation about why this is being done (as I cannot clearly infer this from prior threads that refer to off-wiki IRC chats). I appreciate the input and responses so far, and look forward to thoughts on how to better help people use bitcoin-related software on Arch through this page.--[[User:Xris|Xris]] ([[User talk:Xris|talk]]) 15:50, 7 October 2018 (UTC)<br />
<br />
:In order to stay impartial and high-quality, the content on the ArchWiki is reviewed (or "censored"). The topic about bitcoin is special in regard that none of the reviewers/maintainers/administrators seems to have enough time or patience or interest to gain some sensible knowledge about this mess. As a result, we concluded that the most controversial topics should not be described at all. Unfortunately, the list and implicit comparison of bitcoin software falls into this category, because their developers/protagonists were competing to get the most of the page by twisting the facts. As you have probably found, there were two options considered: either remove the software details or remove the whole page. While definitely not ideal, I think the current page is still better than nothing. -- [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 21:33, 20 October 2018 (UTC)<br />
<br />
== <s>Installing and Running Bitcoin Packages</s> ==<br />
<br />
This wikipedia page discusses bitcoin *concepts* but doesn't even mention the bitcoin packages. I would like to add information on bitcoin-daemon, bitcoin-cli from repositories and instructions for building from source. [[User:Lmat|Lmat]] ([[User talk:Lmat|talk]]) 21:01, 10 January 2019 (UTC)<br />
<br />
:I think you mean wiki page. Please read the last reply in [[#Links to software packages]]. --[[User:Larivact|Larivact]] ([[User talk:Larivact|talk]]) 21:15, 10 January 2019 (UTC)<br />
<br />
::I see, thank you for pointing that out. It looks like my concerns have been explicitly dismissed already. [[User:Lmat|Lmat]] ([[User talk:Lmat|talk]]) 22:53, 10 January 2019 (UTC)<br />
<br />
== <s>Full node (blockchain size)</s> ==<br />
<br />
Please update the size to 260GB (as of October 2019). -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 00:04, 19 October 2019 (UTC)<br />
<br />
:[https://wiki.archlinux.org/index.php?title=Bitcoin&diff=586691&oldid=559367] -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 15:14, 20 October 2019 (UTC)<br />
<br />
:: Thanks -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 00:29, 21 October 2019 (UTC)</div>Malcontenthttps://wiki.archlinux.org/index.php?title=Talk:Bitcoin&diff=586570Talk:Bitcoin2019-10-19T00:04:43Z<p>Malcontent: </p>
<hr />
<div>== <s>Links to software packages</s> ==<br />
It would be useful to have links to software packages here. I know there is significant controversy in the bitcoin space, but I don't think that should preclude listing related software packages. My edit including links to the core & bitcoin-cash qt clients was reverted with "Bitcoin Cash is NOT bitcoin and it's better not to list it here, please go back to Discussion". Bitcoin cash is very overtly a fork of the bitcoin blockchain - with bch proponents contending it IS bitcoin & core proponents contending it is not. I'm not partial to either side, but bch is a part of bitcoin's history. That aside, I think it would be useful to at least mention main repo packages like (core's) bitcoin-qt, which was what brought me to this wiki page in the first place. Since bch client is AUR and this area is contentious tabling inclusion of fork-from-core software could make sense pending further discussion. Now ok to include bitcoin-qt link? Just trying to improve the wiki...thanks for input in this regard.--[[User:Xris|Xris]] ([[User talk:Xris|talk]]) 21:25, 1 October 2018 (UTC)<br />
<br />
I am adding link to repo package now.--[[User:Xris|Xris]] ([[User talk:Xris|talk]]) 11:45, 3 October 2018 (UTC)<br />
<br />
:Reverted due to previous consensus to avoid flame wars. Please read the [https://wiki.archlinux.org/index.php?title=Talk:Bitcoin&oldid=465690 previous discussions] for the reasoning. -- [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 15:46, 3 October 2018 (UTC)<br />
:: [[User:Lahwaacz|Lahwaacz]]: about your last edit: [https://wiki.archlinux.org/index.php?title=Bitcoin&type=revision&diff=545785&oldid=545731 Informational sites: this is not an informational site - it is biased towards one implementation]:<br />
:: I will just say that you can't be neutral about this issue, Bitcoin Core has the [http://luke.dashjr.org/programs/bitcoin/files/charts/software.html majority of the nodes deployment], and it is Bitcoin through the consensus of those nodes. The nodes are what determine what is Bitcoin and what isn't, so I think reverting my edit was a mistake, and you should revert back to my change -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 01:16, 5 October 2018 (UTC)<br />
<br />
::: We're not going through this whole "discussion" again. The article stays in revision [https://wiki.archlinux.org/index.php?title=Bitcoin&oldid=545787]. Closing. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 08:10, 5 October 2018 (UTC)<br />
:::: OK. I understand you don't want to create another flame war, I can respect that. However, the article is about Bitcoin, and Bitcoin Core is the de facto Bitcoin client. This is fact, not bias, and I feel the article does a poor job at informing the user about this fact. -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 21:25, 5 October 2018 (UTC)<br />
<br />
Thank you Lahwaacz for linking the prior discussion. I'm surprised and saddened by reading through some of those threads. I frankly find much of it confusing, as it refers to IRC discussions with mentions of ultimatums without clear details. What exactly is the controversy relating to linking to software packages? There are vague claims about making packages seem like "ads" or being "scary". I've been using Arch as my primary desktop for a few years in large part due to the great, task-focused, and impartial Arch wiki. This page does not fit that bill at all, and is merely confusing to those seeking to setup and configure bitcoin software on Arch (whatever the package type). Despite the verbosity regarding consensus there is no information about how to configure bitcoin on Arch. There are seemingly Arch-specific idiosyncrasies with bitcoin, as evidenced by the [https://bugs.archlinux.org/task/60235?project=5&string=bitcoin-qt recent bug] that makes core bitcoin-qt not start and just hang - this is what led me to this page for these edits in the first place. I appreciate the shenanigans & proposals from both the e.g. core (and related horrific r/bitcoin) and competing software camps (e.g. bch), but pretending that none of these exist just makes it more confusing for those looking to configure related software on Arch. Given the wikis and FAQs of other distributions, and even the bitcoin software developers themselves, are lacking in many ways, it seems an opportunity for clarity in software setup (in addition to Arch perhaps encountering unique errors in bitcoin code given rolling release support of newer dependent library packages). While not well updated and mainly deferring to core, other distributions have not had trouble at least providing basic information about the core packages ([https://fedoraproject.org/wiki/BITCOIN Fedora], [https://help.ubuntu.com/community/bitcoin Ubuntu]). At minimum providing information about configuring the core reference implementation would be of great practical utility. If you are going to censor edits on how to configure bitcoin related software (as has seemingly been done many times), I would at least request a clear explicit explanation about why this is being done (as I cannot clearly infer this from prior threads that refer to off-wiki IRC chats). I appreciate the input and responses so far, and look forward to thoughts on how to better help people use bitcoin-related software on Arch through this page.--[[User:Xris|Xris]] ([[User talk:Xris|talk]]) 15:50, 7 October 2018 (UTC)<br />
<br />
:In order to stay impartial and high-quality, the content on the ArchWiki is reviewed (or "censored"). The topic about bitcoin is special in regard that none of the reviewers/maintainers/administrators seems to have enough time or patience or interest to gain some sensible knowledge about this mess. As a result, we concluded that the most controversial topics should not be described at all. Unfortunately, the list and implicit comparison of bitcoin software falls into this category, because their developers/protagonists were competing to get the most of the page by twisting the facts. As you have probably found, there were two options considered: either remove the software details or remove the whole page. While definitely not ideal, I think the current page is still better than nothing. -- [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 21:33, 20 October 2018 (UTC)<br />
<br />
== <s>Installing and Running Bitcoin Packages</s> ==<br />
<br />
This wikipedia page discusses bitcoin *concepts* but doesn't even mention the bitcoin packages. I would like to add information on bitcoin-daemon, bitcoin-cli from repositories and instructions for building from source. [[User:Lmat|Lmat]] ([[User talk:Lmat|talk]]) 21:01, 10 January 2019 (UTC)<br />
<br />
:I think you mean wiki page. Please read the last reply in [[#Links to software packages]]. --[[User:Larivact|Larivact]] ([[User talk:Larivact|talk]]) 21:15, 10 January 2019 (UTC)<br />
<br />
::I see, thank you for pointing that out. It looks like my concerns have been explicitly dismissed already. [[User:Lmat|Lmat]] ([[User talk:Lmat|talk]]) 22:53, 10 January 2019 (UTC)<br />
<br />
== Full node (blockchain size) ==<br />
<br />
Please update the size to 260GB (as of October 2019). -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 00:04, 19 October 2019 (UTC)</div>Malcontenthttps://wiki.archlinux.org/index.php?title=Enlightenment&diff=575260Enlightenment2019-06-12T13:32:26Z<p>Malcontent: Fix typo</p>
<hr />
<div>[[Category:Desktop environments]]<br />
[[cs:Enlightenment]]<br />
[[de:Enlightenment]]<br />
[[es:Enlightenment]]<br />
[[fr:Enlightenment]]<br />
[[it:Enlightenment]]<br />
[[ja:Enlightenment]]<br />
[[lt:Enlightenment]]<br />
[[pl:Enlightenment]]<br />
[[ru:Enlightenment]]<br />
[[zh-hans:Enlightenment]]<br />
{{Related articles start}}<br />
{{Related|Desktop environment}}<br />
{{Related|Display manager}}<br />
{{Related|Window manager}}<br />
{{Related articles end}}<br />
<br />
== Enlightenment ==<br />
<br />
This comprises both the [https://www.enlightenment.org/ Enlightenment] [[window manager]] and Enlightenment Foundation Libraries (EFL), which provide additional desktop environment features such as a toolkit, object canvas, and abstracted objects. It has been under development since 2005, but in February 2011 the core EFLs saw their first stable 1.0 release.<br />
<br />
=== Installation ===<br />
<br />
[[Install]] the {{Pkg|enlightenment}} package.<br />
<br />
You might also want to install {{Pkg|terminology}}, which is an EFL-based terminal emulator that integrates well with Enlightenment.<br />
<br />
==== From the AUR ====<br />
<br />
{{Warning|Some of these PKGBUILDs use unstable development code. Use them at your own risk.}}<br />
<br />
Development PKGBUILDs which download and install the very latest development code are available as {{AUR|enlightenment-git}} and its dependencies.<br />
<br />
The following are EFL-based applications, most in an early stage of development and not yet released:<br />
* {{AUR|ecrire-git}} – Ecrire text editor<br />
* {{AUR|edi}} – An EFL based IDE<br />
* {{AUR|eluminance-git}} – Eluminance photo browser<br />
* {{AUR|enjoy-git}} – [https://trac.enlightenment.org/e/wiki/Enjoy Enjoy] music player<br />
* {{AUR|eperiodique}} – [http://eperiodique.sourceforge.net/ Eperiodique] periodic table viewer<br />
* {{AUR|ephoto}} and {{AUR|ephoto-git}} – [http://smhouston.us/ephoto/ Ephoto] picture viewer<br />
* {{AUR|epour}} – Torrent client based on EFL<br />
* {{AUR|epymc-git}} – E Python Media Center<br />
* {{AUR|equate-git}} – Equate calculator<br />
* {{AUR|eruler-git}} – Eruler on-screen ruler and measurement tools<br />
* {{AUR|efbb-git}} – Escape from Booty Bay angry birds style game<br />
* {{AUR|elemines-git}} – [http://elemines.sourceforge.net/ Elemines] minesweeper style game<br />
* {{AUR|rage}} and {{AUR|rage-git}} – Rage video player<br />
* {{AUR|terminology-git}} – Current git master for {{Pkg|terminology}}<br />
<br />
=== Starting Enlightenment ===<br />
<br />
Simply choose ''Enlightenment'' session from your favourite [[display manager]] or configure [[xinitrc]] to start it from the console.<br />
<br />
==== Entrance ====<br />
<br />
{{Merge|Display manager|2=Display managers should be listed centrally. Note that Entrance was delisted from the display manager page on June 30th, 2017 on account of it being abandoned by upstream. [https://wiki.archlinux.org/index.php?title=Display_manager&type=revision&diff=480740&oldid=480517] However, as of June 2017 there is a [https://github.com/Obsidian-StudiosInc/entrance new upstream on GitHub].}}<br />
<br />
{{Warning|Entrance is highly experimental, and does not have proper systemd support. Use it at your own risk.}}<br />
<br />
Enlightenment has a new display manager called Entrance, which is provided by the {{AUR|entrance-git}} package. Entrance is quite sophisticated and its configuration is controlled by {{ic|/etc/entrance/entrance.conf}}. It can be used by enabling {{ic|entrance.service}} [[systemd#Using units|using systemd]].<br />
<br />
==== Starting Enlightenment manually ====<br />
<br />
If you prefer to start Enlightenment manually from the console, add the following line to your {{ic|~/.xinitrc}} file:<br />
<br />
{{hc|~/.xinitrc|<br />
exec enlightenment_start<br />
}}<br />
<br />
After that Enlightenment can be launched by typing {{ic|startx}}. See [[xinitrc]] for details.<br />
<br />
To try the experimental [[Wayland]] compositor, enter {{ic|enlightenment_start}} in a [[tty]]. You will probably want to install {{AUR|efl-git}} and {{AUR|enlightenment-git}} for this as it's still experimental, yet relatively complete.<br />
<br />
=== Configuration ===<br />
<br />
Enlightenment has a sophisticated configuration system that can be accessed from the Main menu's Settings submenu.<br />
<br />
==== Network ====<br />
<br />
'''ConnMan'''<br />
<br />
Enlightenment's preferred network manager is [[ConnMan]] which can be installed from the {{Pkg|connman}} package. Follow the instructions on [[ConnMan]] to do the configuration.<br />
<br />
For extended configuration, you may also install Econnman (available in AUR as {{AUR|econnman}} or {{AUR|econnman-git}}) and its associated dependencies. This is not required for general functionality though.<br />
<br />
'''Adding the ConnMan Gadget to the Shelf'''<br />
<br />
# Settings -> Extensions -> Modules<br />
# under System<br />
# Connection Manager<br />
# Load that (select then hit ''Load'').<br />
# Right-click on the shelf at the bottom of the screen.<br />
# Go to Shelf -> Contents<br />
# Then, just scroll around and find ''ConnMan''.<br />
# and hit ''Add''.<br />
<br />
'''NetworkManager'''<br />
<br />
You can also use {{Pkg|networkmanager}} to manage your network connections - see [[NetworkManager]] for more information.<br />
<br />
Note however that the applet will need Appindicator support to show in Enlightenment's [[#System tray|system tray]]. See [[NetworkManager#Appindicator]]. As an alternative to using the applet, NetworkManager includes both CLI and TUI interfaces for network configuration - see [[NetworkManager#Usage]].<br />
<br />
==== Polkit agent ====<br />
<br />
Enlightenment does not ship with a [[Polkit#Authentication agents|graphical polkit authentication agent]]. If you want to access some privileged actions (e.g. mount a filesystem on a system device), you have to install one and autostart it. For that you should go to ''Settings Panel > Apps > Startup Applications > System'' and activate it. There is an EFL based authentication agent available in the AUR, {{AUR|polkit-efl-git}}.<br />
<br />
==== GNOME Keyring integration ====<br />
<br />
It is possible to use gnome-keyring in Enlightenment. However, at the time of writing, you need a small hack to make it work in full.<br />
First, you must tell Enlightenment to autostart gnome-keyring. For that you should go to ''Settings Panel > Apps > Startup Applications > System'' and activate ''Certificate and Key Storage'', ''GPG Password Agent'', ''SSH Key Agent'' and "Secret Storage Service".<br />
After this, you should edit your {{ic|~/.pam_environment}} and add the following:<br />
<br />
#Set gnome-keyring as the ssh authentication agent<br />
SSH_AUTH_SOCK=/run/user/${UID}/keyring/ssh<br />
<br />
This "hack" is used to override the automatic setting of the variable by "enlightenment-start" from "ssh-agent" to gnome-keyring. <br />
<br />
More information on this topic in the [[GNOME Keyring]] article.<br />
<br />
==== System tray ====<br />
<br />
{{Note|Since Enlightenment 20, Xembed support has been removed [https://twitter.com/_enlightenment_/status/538000507315314688] meaning that many 'legacy' applets can no longer be displayed in the Systray. To use these applets, you will need to use a standalone system tray application such as {{Pkg|stalonetray}} instead.}}<br />
<br />
Enlightenment has support for a system tray but it is disabled by default. To enable the system tray, open the Enlightenment main menu, navigate to the ''Settings'' submenu and click on the ''Modules'' option. Scroll down until you see the ''Systray'' option. Highlight that option and click the ''Load'' button. Now that the module has been loaded, it can be added to the shelf. Right click on the shelf you wish to add the Systray to, hightlight the ''Shelf'' submenu and click on the ''Contents'' option. Scroll down until you see ''Systray''. Highlight that option and click the ''Add'' button.<br />
<br />
==== Notifications ====<br />
<br />
Enlightenment provides a notification server through its Notification extension.<br />
* Notifications may be displayed in any corner of the "screen" as defined below<br />
* Available screen policies are Primary Screen, Current Screen, All Screens, and Xinerama<br />
* Notifications may be filtered based on urgency (Low, Normal, or Critical in any combination)<br />
* A default notification timeout may be set and optionally enforced for all notifications<br />
* The notification server may also optionally ignore replace ID requests<br />
<br />
=== Themes ===<br />
<br />
More themes to customize the look of Enlightenment are available from:<br />
* [https://extra.enlightenment.org/themes/ extra.enlightenment.org]<br />
* [https://www.enlightenment-themes.org/ enlightenment-themes.org]<br />
* [http://relighted.c0n.de/#100 relighted.c0n.de] for the default theme in 200 different colors<br />
* [http://git.enlightenment.org/themes git.enlightenment.org] (git clone the theme you like, run 'make' and you end up with a .edj theme file)<br />
* [http://packages.bodhilinux.com/bodhi/pool/stable/b/ packages.bodhilinux.com] has a good collection (you will need to extract the .edj file from the .deb; bsdtar will do this and is part of the base ArchLinux install). A nice catalog can be seen at [https://web.archive.org/web/20140120083020/http://art.bodhilinux.com/doku.php?id=bodhi_e17_themes_v3 their wiki].<br />
* [https://web.archive.org/web/20161025233126/https://exchange.enlightenment.org/theme exchange.enlightenment.org] (archived)<br />
<br />
You can install the themes (coming in .edj format) using the theme configuration dialog or by moving them to {{ic|~/.e/e/themes}}. <br />
<br />
{{Note|Enlightenment does not provide a stable theme API, and there have been numerous theme API changes over the years, even after E17 was released. Themes that have not been updated regularly are unlikely to work.}}<br />
<br />
{{Tip|1=To make GTK and Qt applications match the default theme of Enlightenment you can download a theme like the [http://gnome-look.org/content/show.php/?content=163472 E17 GTK theme]. Place it in {{ic|~/.themes/}} or install the {{AUR|gtk-theme-e17gtk-git}} package and select application themes from Enlightenments settings, and set it to that, this will make all GTK2 and GTK3 applications match the default Enlightenment theme, you can then configure Qt applications (or configure Qt's default settings) to use the Gtk+ theme so it will mimic the theme your GTK applications are using, this way you can make sure most applications will blend in perfectly with your default enlightenment theme. See also [[Uniform look for Qt and GTK applications]].}}<br />
<br />
==== GTK+ ====<br />
<br />
To alter the GTK+ theme, go to ''Settings > All > Look > Application Theme''.<br />
<br />
=== Modules and Gadgets ===<br />
<br />
;Module:Name used in enlightenment to refer to the "backing" code for a gadget. <br />
;Gadget:Front-end or user interface that should help the end users of Enlightenment do something.<br />
<br />
Many Modules provide Gadgets that can be added to your desktop or on a shelf. Some Modules (such as CPUFreq) only provide a single Gadget while others (such as Composite) provide additional features without any gadgets. Note that certain gadgets such as Systray can only be added to a shelf while others such as Moon can only be loaded on the desktop. <br />
<br />
==== "Extra" modules ====<br />
<br />
{{Warning|These are 3rd party modules and not officially supported by the Enlightenment developers. They are also pulled directly from git, so they are development code that may or may not work at any time. Use at your own risk.}}<br />
Beyond the modules described here, more "extra" modules are available from {{AUR|e-modules-extra-git}}.<br />
<br />
'''Scale Windows'''<br />
<br />
The ''Scale Windows'' module, which requires compositing to be enabled, adds several features. The scale windows effect shrinks all open windows and brings them all into view. This is known in "Mission Control" in macOS. The scale pager effect zooms out and shows all desktops as a wall, like the compiz expo plugin. Both can be added to the desktop as a gadget or bound to a key binding, mouse binding or screen edge binding. <br />
<br />
Some people like to change the standard window selection key binding {{ic|ALT + Tab}} to use Scale Windows to select windows. To change this setting, you navigate to ''Menu > Settings > Settings Panel > Input > Keys''. From here, you can set any key binding you would like. <br />
<br />
To replace the window selection key binding functionality with Scale Windows, scroll through the left panel until you find the ''ALT'' section and then find and select {{ic|ALT + Tab}}. Then, scroll through the right panel looking for the "Scale Windows" section and choose either ''Select Next'' or ''Select Next (All)'' depending on whether you would like to see windows from only the current desktop or from all desktops and click ''Apply'' to save the binding.<br />
<br />
Available from [https://git.enlightenment.org/enlightenment/modules/comp-scale.git/ upstream git].<br />
<br />
=== Default Keybindings ===<br />
<br />
{| class="wikitable"<br />
|+ Some default Enlightenment keybindings<br />
| Shift + F10 <br />
| Maximize Vertically <br />
|-<br />
| Ctrl + Menu <br />
| Show "Clients" (windows) Menu <br />
|-<br />
| Alt + Escape <br />
| Show "Everything Launcher" (apps, windows, etc) <br />
|-<br />
| Win + Left <br />
| Maximize Left <br />
|-<br />
| Win + Right <br />
| Maximize Right <br />
|-<br />
| Alt + Shift + F10 <br />
| Maximize Horizontally <br />
|-<br />
| Alt + Shift + Left <br />
| Flip to the Desktop on the Left <br />
|-<br />
| Alt + Shift + Right <br />
| Flip to the Desktop on the Right <br />
|-<br />
| Ctrl + Alt + D <br />
| Show the desktop <br />
|-<br />
| Ctrl + Alt + F <br />
| Toggle Fullscreen <br />
|-<br />
| Ctrl + Alt + I <br />
| Toggle iconic mode <br />
|-<br />
| Ctrl + Alt + K <br />
| Kill window<br />
|-<br />
| Ctrl + Alt + L <br />
| Lock the desktop <br />
|-<br />
| Ctrl + Alt + N <br />
| Maximize Window <br />
|-<br />
| Ctrl + Alt + R <br />
| Toggle Shade up <br />
|-<br />
| Ctrl + Alt + W <br />
| Window menu <br />
|-<br />
| Ctrl + Alt + X <br />
| Close a window <br />
|-<br />
| Ctrl + Alt + Down <br />
| Lower <br />
|-<br />
| Ctrl + Alt + Up <br />
| Raise <br />
|-<br />
| Ctrl + Alt + Left <br />
| Flip to desktop on left <br />
|-<br />
| Ctrl + Alt + Right <br />
| Flip to desktop on right <br />
|-<br />
| Ctrl + Alt + Delete <br />
| End session dialog<br />
|-<br />
| Ctrl + Alt + Insert <br />
| Launch the default terminal <br />
|}<br />
<br />
=== Troubleshooting ===<br />
<br />
If you find some unexpected behavior, there are a few things you can do:<br />
# try to see if the same behavior exists with the default theme<br />
# disable any 3rd party modules you may have installed<br />
# backup {{ic|~/.e}} and remove it (e.g. {{ic|mv ~/.e ~/.e.back}})<br />
<br />
If you are sure you found a bug please report it [https://phab.enlightenment.org/maniphest/task/create/ directly upstream]. <br />
<br />
==== Compositing ====<br />
<br />
When the configuration needs to be reset and the settings windows can no longer be approached, configuration for the compositor can be reset using the hardcoded keybinding {{ic|Ctrl + Alt + Shift + Home}}.<br />
<br />
==== Unreadable fonts ====<br />
<br />
If fonts are too small and your screen is unreadable, be sure the right font packages are installed. {{Pkg|ttf-dejavu}} and {{Pkg|ttf-bitstream-vera}} are valid candidates.<br />
<br />
You also should consider just increasing the scaling size under the Scaling. You can set scaling under ''Settings > Settings Panel > Look > Scaling''.<br />
<br />
==== Backlight always dimmed ====<br />
<br />
You may find that Enlightenment routinely dims the backlight to 0% on logout and will only restore it to 100% when you log into another Enlightenment session. Enlightenment assumes that whatever comes after it will set the backlight to whatever it prefers, if anything as this is what Enlightenment does at start. This is especially problematic when using another desktop environment alongside Enlightenment that cannot control backlight as the backlight will not automatically be restored to its normal level when using that desktop environment. To fix this issue, open the Enlightenment ''Settings Panel'' and, under the ''Look'' tab, click on the ''Composite'' option. Tick the ''Don't fade backlight'' box and click ''OK''.<br />
<br />
==== Inconsistent cursor theme ====<br />
<br />
You may find that the cursor theme for the desktop is different to the one used in applications such as [[Firefox]]. This is because desktop applications are using X cursor themes whilst Enlightenment has its own set of cursor themes. For consistency, you can set Enlightenment to always use the X cursor theme. To do this, open the Enlightenment ''Settings Panel'' and click on the ''Input'' tab. Click on the ''Mouse'' option. Change the theme from ''Enlightenment'' to ''X'' and click ''OK''. You should now find that the same cursor theme is used everywhere. If the X cursor theme itself is not always consistent, see [[Cursor themes#XDG specification]].<br />
<br />
==== Background images ====<br />
<br />
You can just select wallpapers in the wallpaper settings dialog and import any image with the provided settings dialog, or you can put desired wallpapers into {{ic|~/.e/e/backgrounds/}}<br />
<br />
LMB anywhere on the desktop will give access to the settings, select {{ic|/Desktop/Backgrounds/}}<br />
<br />
Any new image copied in the {{ic|~/.e/e/backgrounds/}} folder will get the list of available backgrounds auto-updated. You can drop animated gifs and even mp4 and other video files in here and use them as wallpapers if you want. Select desired wallpaper from drop-down menu. Inside the appropriate tabs in the global settings, you can adjust things like tiling of the background image, filling screen and such.<br />
<br />
== Enlightenment DR16 ==<br />
<br />
Enlightenment, Development Release 16 was first released in 2000, and reached version 1.0 in 2009. Originally, the DR16 stood for the 0.16 version of the Enlightenment project. You'll find it as "Enlightenment16" now in the Arch repositories, it is still under development today, regularly updated by its maintainer Kim 'kwo' Woelders. With compositing, shadows and transparencies, E16 kept all of the speed that presided over its foundation by original author Carsten "Rasterman" Haitzler but with up to date refinement.<br />
<br />
=== To install E16 ===<br />
<br />
Install {{AUR|enlightenment16}}.<br />
<br />
See {{ic|/usr/share/doc/e16/e16.html}} for in depth documentation. The man page is at {{man|1|e16}}{{Dead link|2019|04|20}} and only gives startup options.<br />
<br />
=== Basic Configuration ===<br />
<br />
Most configuration files for E16 reside in {{ic|~/.e16}} and are text-based, editable at will. That includes the Menus too.<br />
<br />
Shortcut keys can be either modified by hand, or with the e16keyedit software provided as source on the [http://sourceforge.net/projects/enlightenment/ sourceforge] page of the e16 project. Note that the keyboard shortcuts file is not created in {{ic|~/.e16}} by default. You can copy the packaged version to your home directory if you wish to make changes:<br />
$ cp /usr/share/e16/config/bindings.cfg ~/.e16<br />
<br />
==== Start/Restart/Stop Scripts ====<br />
<br />
Create an Init, a Start and a Stop folder in your {{ic|~/.e16}} folder: any .sh script found there will either be executed at Startup (from Init folder), at each Restart (from Start folder), or at Shutdown (from Stop folder); provided you allowed it through the MMB / settings / session / <enable scripts> button and made them executable with {{ic|chmod +x ''yourscript.sh''}}. Typical examples involves starting pulseaudio or your favorite network manager applet.<br />
<br />
==== Compositor ====<br />
<br />
Shadows, Transparent effects ''et al'' can be found in MMB or RMB /Settings, under Composite .<br />
<br />
== See also ==<br />
* [http://www.enlightenment.org/ Enlightenment Homepage]<br />
* [http://exchange.enlightenment.org/ Enlightenment Exchange]<br />
* [http://docs.enlightenment.org/ Enlightenment Developer Documentation]<br />
* [http://www.bodhilinux.com/e17guide/e17guideEN/ Bodhi Guide to Enlightenment]<br />
* [http://www.e17-stuff.org/ E17-Stuff]<br />
* [http://sourceforge.net/projects/enlightenment/ DR16 download resource]<br />
* [https://lists.sourceforge.net/lists/listinfo/enlightenment-users Enlightenment users mail list]<br />
* [https://lists.sourceforge.net/lists/listinfo/enlightenment-devel Enlightenment developer mail list]<br />
* ircs://chat.freenode.net#e</div>Malcontenthttps://wiki.archlinux.org/index.php?title=USBGuard&diff=560468USBGuard2018-12-26T04:36:33Z<p>Malcontent: Qt: fix typo</p>
<hr />
<div>[[Category:Hardware detection and troubleshooting]]<br />
[[Category:Security]]<br />
[[ja:Usbguard]]<br />
[https://github.com/dkopecek/usbguard USBGuard] offers a white/black-listing mechanism for USB-devices. Inspiration for this is drawn from exploits like BadUSB.<br />
It makes use of a device blocking infrastructure included in the Linux kernel and consists of a daemon and some front-ends.<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|usbguard}} package, or {{Aur|usbguard-git}} for the development version.<br />
For the applet [[Install]] {{Pkg|usbguard-qt}}.<br />
<br />
== Configuration ==<br />
<br />
The main configuration file is found in {{ic|/etc/usbguard/usbguard-daemon.conf}}. To edit it, you need root privileges.<br />
<br />
If you want to control the daemon via IPC, be sure to add your username to {{ic|IPCAllowedUsers}} or your group to {{ic|IPCAllowedGroups}} to make rules persistent. In most cases, you want this.<br />
<br />
Per default, usbguard blocks all newly connected devices and devices connected before daemon startup are left as is. This can be changed with the {{ic|PresentDevicePolicy}} option. Setting this key to {{ic|apply-policy}} is the most secure setting, which ensures security even when the daemon hits a restart.<br />
<br />
With the key {{ic|ImplicitPolicyTarget}} you can configure the default treatment of devices, if no rules match. The most secure option here is {{ic|block}}.<br />
<br />
For an in-depth documentation of configuration see the very well commented configuration file.<br />
<br />
== Usage ==<br />
<br />
USBGuard has a core daemon, a CLI, a Qt GUI, a DBUS interface and an API via libusbguard.<br />
<br />
If you want to use the Qt GUI or another program communicating via DBUS, [[enable]] and [[start]] {{ic|usbguard-dbus.service}}.<br />
<br />
If you only want to communicate via API (with the CLI tool or another software using libusbguard) [[enable]] and [[start]] {{ic|usbguard.service}}.<br />
<br />
{{Warning|Make sure to actually configure the daemon before starting/enabling it or all USB devices will immediately be blocked!}}<br />
<br />
The CLI is available via {{ic|usbguard}}.<br />
<br />
See the according man pages for more info.<br />
<br />
A Qt applet can be started with {{ic|usbguard-applet-qt}} and provides an interactive graphical interface.<br />
<br />
=== Rules ===<br />
<br />
To configure usbguard to your needs, you can edit {{ic|/etc/usbguard/rules.conf}}. However manual editing of the rules is normally not necessary. You can generate a ruleset based on your currently attached USB devices by executing {{ic|usbguard generate-policy > /etc/usbguard/rules.conf}} as root.<br />
<br />
The rules syntax is formally explained [https://github.com/USBGuard/usbguard/blob/master/doc/man/usbguard-rules.conf.5.adoc here].<br />
An example for a hp printer connected via USB can look like this:<br />
<br />
allow id 03f0:0c17 serial "00CNFD234631" name "hp LaserJet 2020" hash "a0ef07fceb6fb77698f79a44a450121m" parent-hash "69d19c1a5733a31e7e6d9530e6k434a6" with-interface { 07:01:03 07:01:02 07:01:01 }<br />
<br />
A rule begins with a policy. {{ic|allow}} whitelists a device, {{ic|block}} stops the device from being processed now and {{ic|reject}} removes the device from the system.<br />
Then follows a set of attributes with their options, as detailed below.<br />
<br />
{| class="wikitable"<br />
! Attribute || Description<br />
|-<br />
| id usb-device-id || Match a USB device ID. <br />
|-<br />
| id [operator] { usb-device-id ... } || Match a set of USB device IDs.<br />
|-<br />
| hash "value" || Match a hash computed from the device attribute values and the USB descriptor data. The hash is computed for every device by USBGuard.<br />
|-<br />
| hash [operator] { "value" ... } || Match a set of device hashes.<br />
|-<br />
| parent-hash "value" || Match a hash of the parent device.<br />
|-<br />
| parent-hash [operator] { "value" ... } || Match a set of parent device hashes.<br />
|-<br />
| name "device-name" || Match the USB device name attribute.<br />
|-<br />
| name [operator] { "device-name" ... } || Match a set of USB device names.<br />
|-<br />
| serial "serial-number" || Match the USB iSerial device attribute.<br />
|-<br />
| serial [operator] { "serial-number" ... } || Match a set of USB iSerial device attributes.<br />
|-<br />
| via-port "port-id" || Match the USB port through which the device is connected. Note that some systems have unstable port numbering which change after the system reboots or certain kernel modules are reloaded (and maybe in other cases). Use the parent-hash attribute if you want to ensure that a device is connected via a specific parent device. <br />
|-<br />
| via-port [operator] { "port-id" ... } || Match a set of USB ports.<br />
|-<br />
| with-interface interface-type || Match an interface type that the USB device provides.<br />
|-<br />
| with-interface [operator] { interface-type interface-type ... } || Match a set of interface types against the set of interfaces that the USB device provides.<br />
<br />
|}<br />
<br />
== See also ==<br />
<br />
* [https://github.com/dkopecek/usbguard/ USBGuard Website]<br />
* [https://raw.githubusercontent.com/dkopecek/usbguard/master/doc/usbguard-component-diagram.png USBGuard component diagram]<br />
* [https://srlabs.de/bites/usb-peripherals-turn/ BadUSB background info]<br />
* [https://www.kernel.org/doc/Documentation/usb/authorization.txt Kernel interface for USB device control]</div>Malcontenthttps://wiki.archlinux.org/index.php?title=Talk:Bitcoin&diff=555048Talk:Bitcoin2018-11-13T14:55:38Z<p>Malcontent: /* Changed protection level for "Bitcoin": managed by the maintenance team */</p>
<hr />
<div>== <s>Other Cryptocurrencies</s> ==<br />
<br />
I noticed this is the only real and complete page on any cryptocurrency in the Arch Wiki, perhaps with a bit too much information. Maybe it needs a split or more generalities?<br />
<br />
More importantly, from the perspective of OS Users, it seems like we might be better served by something that addresses cryptocurrencies as a whole, or maybe 2 pages: Cryptocurrency Mining and Cryptocurrency User/Trading that delves into setup of each of the roles for each currency in Arch. I suspect this could eventually split into pages per currency. Discussion? [[User:Physicist1616|Physicist1616]] ([[User talk:Physicist1616|talk]]) 00:03, 24 October 2017 (UTC)<br />
<br />
:Which cryptocurrencies do you have in mind? Note that most of the previous discussions lead to [https://wiki.archlinux.org/index.php?title=Talk:Bitcoin&action=history flame wars], so let's avoid that. Any controversial topic will simply not be covered on this wiki. -- [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 14:59, 24 October 2017 (UTC)<br />
<br />
::Bitcoin (Obviously, but also ASIC miners and the main intermediary currency), Ethereum (GPU miners and recently successful), and Monero (CPU miners and allegedly more focused on privacy than others). I'm not shilling for any of those and so would be fine discussing an alternative to any or adding more to the list. The diversity in how each of those three are mined attracted me. <s>I can't imagine what flame wars could happen other than, "mine is better than yours". Perhaps that's just a failure of imagination.</s> Ok, read the history; yeah, philosophy doesn't belong here, nor does excess detail on how and why or where BTC is going/splitting/etc. This is an OS wiki. [[User:Physicist1616|Physicist1616]] ([[User talk:Physicist1616|talk]]) 16:58, 27 October 2017 (UTC)<br />
<br />
== <s>Links to software packages</s> ==<br />
It would be useful to have links to software packages here. I know there is significant controversy in the bitcoin space, but I don't think that should preclude listing related software packages. My edit including links to the core & bitcoin-cash qt clients was reverted with "Bitcoin Cash is NOT bitcoin and it's better not to list it here, please go back to Discussion". Bitcoin cash is very overtly a fork of the bitcoin blockchain - with bch proponents contending it IS bitcoin & core proponents contending it is not. I'm not partial to either side, but bch is a part of bitcoin's history. That aside, I think it would be useful to at least mention main repo packages like (core's) bitcoin-qt, which was what brought me to this wiki page in the first place. Since bch client is AUR and this area is contentious tabling inclusion of fork-from-core software could make sense pending further discussion. Now ok to include bitcoin-qt link? Just trying to improve the wiki...thanks for input in this regard.--[[User:Xris|Xris]] ([[User talk:Xris|talk]]) 21:25, 1 October 2018 (UTC)<br />
<br />
I am adding link to repo package now.--[[User:Xris|Xris]] ([[User talk:Xris|talk]]) 11:45, 3 October 2018 (UTC)<br />
<br />
:Reverted due to previous consensus to avoid flame wars. Please read the [https://wiki.archlinux.org/index.php?title=Talk:Bitcoin&oldid=465690 previous discussions] for the reasoning. -- [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 15:46, 3 October 2018 (UTC)<br />
:: [[User:Lahwaacz|Lahwaacz]]: about your last edit: [https://wiki.archlinux.org/index.php?title=Bitcoin&type=revision&diff=545785&oldid=545731 Informational sites: this is not an informational site - it is biased towards one implementation]:<br />
:: I will just say that you can't be neutral about this issue, Bitcoin Core has the [http://luke.dashjr.org/programs/bitcoin/files/charts/software.html majority of the nodes deployment], and it is Bitcoin through the consensus of those nodes. The nodes are what determine what is Bitcoin and what isn't, so I think reverting my edit was a mistake, and you should revert back to my change -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 01:16, 5 October 2018 (UTC)<br />
<br />
::: We're not going through this whole "discussion" again. The article stays in revision [https://wiki.archlinux.org/index.php?title=Bitcoin&oldid=545787]. Closing. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 08:10, 5 October 2018 (UTC)<br />
:::: OK. I understand you don't want to create another flame war, I can respect that. However, the article is about Bitcoin, and Bitcoin Core is the de facto Bitcoin client. This is fact, not bias, and I feel the article does a poor job at informing the user about this fact. -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 21:25, 5 October 2018 (UTC)<br />
<br />
Thank you Lahwaacz for linking the prior discussion. I'm surprised and saddened by reading through some of those threads. I frankly find much of it confusing, as it refers to IRC discussions with mentions of ultimatums without clear details. What exactly is the controversy relating to linking to software packages? There are vague claims about making packages seem like "ads" or being "scary". I've been using Arch as my primary desktop for a few years in large part due to the great, task-focused, and impartial Arch wiki. This page does not fit that bill at all, and is merely confusing to those seeking to setup and configure bitcoin software on Arch (whatever the package type). Despite the verbosity regarding consensus there is no information about how to configure bitcoin on Arch. There are seemingly Arch-specific idiosyncrasies with bitcoin, as evidenced by the [https://bugs.archlinux.org/task/60235?project=5&string=bitcoin-qt recent bug] that makes core bitcoin-qt not start and just hang - this is what led me to this page for these edits in the first place. I appreciate the shenanigans & proposals from both the e.g. core (and related horrific r/bitcoin) and competing software camps (e.g. bch), but pretending that none of these exist just makes it more confusing for those looking to configure related software on Arch. Given the wikis and FAQs of other distributions, and even the bitcoin software developers themselves, are lacking in many ways, it seems an opportunity for clarity in software setup (in addition to Arch perhaps encountering unique errors in bitcoin code given rolling release support of newer dependent library packages). While not well updated and mainly deferring to core, other distributions have not had trouble at least providing basic information about the core packages ([https://fedoraproject.org/wiki/BITCOIN Fedora], [https://help.ubuntu.com/community/bitcoin Ubuntu]). At minimum providing information about configuring the core reference implementation would be of great practical utility. If you are going to censor edits on how to configure bitcoin related software (as has seemingly been done many times), I would at least request a clear explicit explanation about why this is being done (as I cannot clearly infer this from prior threads that refer to off-wiki IRC chats). I appreciate the input and responses so far, and look forward to thoughts on how to better help people use bitcoin-related software on Arch through this page.--[[User:Xris|Xris]] ([[User talk:Xris|talk]]) 15:50, 7 October 2018 (UTC)<br />
<br />
:In order to stay impartial and high-quality, the content on the ArchWiki is reviewed (or "censored"). The topic about bitcoin is special in regard that none of the reviewers/maintainers/administrators seems to have enough time or patience or interest to gain some sensible knowledge about this mess. As a result, we concluded that the most controversial topics should not be described at all. Unfortunately, the list and implicit comparison of bitcoin software falls into this category, because their developers/protagonists were competing to get the most of the page by twisting the facts. As you have probably found, there were two options considered: either remove the software details or remove the whole page. While definitely not ideal, I think the current page is still better than nothing. -- [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 21:33, 20 October 2018 (UTC)<br />
<br />
== <s>Changed protection level for "Bitcoin": managed by the maintenance team</s> ==<br />
<br />
I'm very upset about this change.<br />
<br />
So now the Bitcoin page is managed by people who have no clue about bitcoin, and it forbids contributions from its actual users. Why this isn't surprising at all? -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 14:36, 13 November 2018 (UTC)<br />
<br />
:Everyone has to stick to [[ArchWiki:Contributing#The_3_fundamental_rules]], including the maintenance team. That includes the concept of using the discussion page, as we're doing right now. The very reason the page was protected was that "its actual users" disregarded those rules. See also Lahwaacz's reply above.<br />
:I encourage you to take the change at face value and continue discussing changes as before. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 14:43, 13 November 2018 (UTC)<br />
:: Yes, I am aware of the past flamewar on this page, and I apologize for my last statement. If users can still provide feedback and contribute to the page via the discussion page (which I think is the case), I am OK with this change. -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 14:55, 13 November 2018 (UTC)</div>Malcontenthttps://wiki.archlinux.org/index.php?title=Talk:Bitcoin&diff=555032Talk:Bitcoin2018-11-13T14:36:50Z<p>Malcontent: /* Changed protection level for "Bitcoin": managed by the maintenance team */</p>
<hr />
<div>== <s>Other Cryptocurrencies</s> ==<br />
<br />
I noticed this is the only real and complete page on any cryptocurrency in the Arch Wiki, perhaps with a bit too much information. Maybe it needs a split or more generalities?<br />
<br />
More importantly, from the perspective of OS Users, it seems like we might be better served by something that addresses cryptocurrencies as a whole, or maybe 2 pages: Cryptocurrency Mining and Cryptocurrency User/Trading that delves into setup of each of the roles for each currency in Arch. I suspect this could eventually split into pages per currency. Discussion? [[User:Physicist1616|Physicist1616]] ([[User talk:Physicist1616|talk]]) 00:03, 24 October 2017 (UTC)<br />
<br />
:Which cryptocurrencies do you have in mind? Note that most of the previous discussions lead to [https://wiki.archlinux.org/index.php?title=Talk:Bitcoin&action=history flame wars], so let's avoid that. Any controversial topic will simply not be covered on this wiki. -- [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 14:59, 24 October 2017 (UTC)<br />
<br />
::Bitcoin (Obviously, but also ASIC miners and the main intermediary currency), Ethereum (GPU miners and recently successful), and Monero (CPU miners and allegedly more focused on privacy than others). I'm not shilling for any of those and so would be fine discussing an alternative to any or adding more to the list. The diversity in how each of those three are mined attracted me. <s>I can't imagine what flame wars could happen other than, "mine is better than yours". Perhaps that's just a failure of imagination.</s> Ok, read the history; yeah, philosophy doesn't belong here, nor does excess detail on how and why or where BTC is going/splitting/etc. This is an OS wiki. [[User:Physicist1616|Physicist1616]] ([[User talk:Physicist1616|talk]]) 16:58, 27 October 2017 (UTC)<br />
<br />
== <s>Links to software packages</s> ==<br />
It would be useful to have links to software packages here. I know there is significant controversy in the bitcoin space, but I don't think that should preclude listing related software packages. My edit including links to the core & bitcoin-cash qt clients was reverted with "Bitcoin Cash is NOT bitcoin and it's better not to list it here, please go back to Discussion". Bitcoin cash is very overtly a fork of the bitcoin blockchain - with bch proponents contending it IS bitcoin & core proponents contending it is not. I'm not partial to either side, but bch is a part of bitcoin's history. That aside, I think it would be useful to at least mention main repo packages like (core's) bitcoin-qt, which was what brought me to this wiki page in the first place. Since bch client is AUR and this area is contentious tabling inclusion of fork-from-core software could make sense pending further discussion. Now ok to include bitcoin-qt link? Just trying to improve the wiki...thanks for input in this regard.--[[User:Xris|Xris]] ([[User talk:Xris|talk]]) 21:25, 1 October 2018 (UTC)<br />
<br />
I am adding link to repo package now.--[[User:Xris|Xris]] ([[User talk:Xris|talk]]) 11:45, 3 October 2018 (UTC)<br />
<br />
:Reverted due to previous consensus to avoid flame wars. Please read the [https://wiki.archlinux.org/index.php?title=Talk:Bitcoin&oldid=465690 previous discussions] for the reasoning. -- [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 15:46, 3 October 2018 (UTC)<br />
:: [[User:Lahwaacz|Lahwaacz]]: about your last edit: [https://wiki.archlinux.org/index.php?title=Bitcoin&type=revision&diff=545785&oldid=545731 Informational sites: this is not an informational site - it is biased towards one implementation]:<br />
:: I will just say that you can't be neutral about this issue, Bitcoin Core has the [http://luke.dashjr.org/programs/bitcoin/files/charts/software.html majority of the nodes deployment], and it is Bitcoin through the consensus of those nodes. The nodes are what determine what is Bitcoin and what isn't, so I think reverting my edit was a mistake, and you should revert back to my change -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 01:16, 5 October 2018 (UTC)<br />
<br />
::: We're not going through this whole "discussion" again. The article stays in revision [https://wiki.archlinux.org/index.php?title=Bitcoin&oldid=545787]. Closing. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 08:10, 5 October 2018 (UTC)<br />
:::: OK. I understand you don't want to create another flame war, I can respect that. However, the article is about Bitcoin, and Bitcoin Core is the de facto Bitcoin client. This is fact, not bias, and I feel the article does a poor job at informing the user about this fact. -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 21:25, 5 October 2018 (UTC)<br />
<br />
Thank you Lahwaacz for linking the prior discussion. I'm surprised and saddened by reading through some of those threads. I frankly find much of it confusing, as it refers to IRC discussions with mentions of ultimatums without clear details. What exactly is the controversy relating to linking to software packages? There are vague claims about making packages seem like "ads" or being "scary". I've been using Arch as my primary desktop for a few years in large part due to the great, task-focused, and impartial Arch wiki. This page does not fit that bill at all, and is merely confusing to those seeking to setup and configure bitcoin software on Arch (whatever the package type). Despite the verbosity regarding consensus there is no information about how to configure bitcoin on Arch. There are seemingly Arch-specific idiosyncrasies with bitcoin, as evidenced by the [https://bugs.archlinux.org/task/60235?project=5&string=bitcoin-qt recent bug] that makes core bitcoin-qt not start and just hang - this is what led me to this page for these edits in the first place. I appreciate the shenanigans & proposals from both the e.g. core (and related horrific r/bitcoin) and competing software camps (e.g. bch), but pretending that none of these exist just makes it more confusing for those looking to configure related software on Arch. Given the wikis and FAQs of other distributions, and even the bitcoin software developers themselves, are lacking in many ways, it seems an opportunity for clarity in software setup (in addition to Arch perhaps encountering unique errors in bitcoin code given rolling release support of newer dependent library packages). While not well updated and mainly deferring to core, other distributions have not had trouble at least providing basic information about the core packages ([https://fedoraproject.org/wiki/BITCOIN Fedora], [https://help.ubuntu.com/community/bitcoin Ubuntu]). At minimum providing information about configuring the core reference implementation would be of great practical utility. If you are going to censor edits on how to configure bitcoin related software (as has seemingly been done many times), I would at least request a clear explicit explanation about why this is being done (as I cannot clearly infer this from prior threads that refer to off-wiki IRC chats). I appreciate the input and responses so far, and look forward to thoughts on how to better help people use bitcoin-related software on Arch through this page.--[[User:Xris|Xris]] ([[User talk:Xris|talk]]) 15:50, 7 October 2018 (UTC)<br />
<br />
:In order to stay impartial and high-quality, the content on the ArchWiki is reviewed (or "censored"). The topic about bitcoin is special in regard that none of the reviewers/maintainers/administrators seems to have enough time or patience or interest to gain some sensible knowledge about this mess. As a result, we concluded that the most controversial topics should not be described at all. Unfortunately, the list and implicit comparison of bitcoin software falls into this category, because their developers/protagonists were competing to get the most of the page by twisting the facts. As you have probably found, there were two options considered: either remove the software details or remove the whole page. While definitely not ideal, I think the current page is still better than nothing. -- [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 21:33, 20 October 2018 (UTC)<br />
<br />
== Changed protection level for "Bitcoin": managed by the maintenance team ==<br />
<br />
I'm very upset about this change.<br />
<br />
So now the Bitcoin page is managed by people who have no clue about bitcoin, and it forbids contributions from its actual users. Why this isn't surprising at all? -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 14:36, 13 November 2018 (UTC)</div>Malcontenthttps://wiki.archlinux.org/index.php?title=Talk:Bitcoin&diff=555031Talk:Bitcoin2018-11-13T14:36:20Z<p>Malcontent: </p>
<hr />
<div>== <s>Other Cryptocurrencies</s> ==<br />
<br />
I noticed this is the only real and complete page on any cryptocurrency in the Arch Wiki, perhaps with a bit too much information. Maybe it needs a split or more generalities?<br />
<br />
More importantly, from the perspective of OS Users, it seems like we might be better served by something that addresses cryptocurrencies as a whole, or maybe 2 pages: Cryptocurrency Mining and Cryptocurrency User/Trading that delves into setup of each of the roles for each currency in Arch. I suspect this could eventually split into pages per currency. Discussion? [[User:Physicist1616|Physicist1616]] ([[User talk:Physicist1616|talk]]) 00:03, 24 October 2017 (UTC)<br />
<br />
:Which cryptocurrencies do you have in mind? Note that most of the previous discussions lead to [https://wiki.archlinux.org/index.php?title=Talk:Bitcoin&action=history flame wars], so let's avoid that. Any controversial topic will simply not be covered on this wiki. -- [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 14:59, 24 October 2017 (UTC)<br />
<br />
::Bitcoin (Obviously, but also ASIC miners and the main intermediary currency), Ethereum (GPU miners and recently successful), and Monero (CPU miners and allegedly more focused on privacy than others). I'm not shilling for any of those and so would be fine discussing an alternative to any or adding more to the list. The diversity in how each of those three are mined attracted me. <s>I can't imagine what flame wars could happen other than, "mine is better than yours". Perhaps that's just a failure of imagination.</s> Ok, read the history; yeah, philosophy doesn't belong here, nor does excess detail on how and why or where BTC is going/splitting/etc. This is an OS wiki. [[User:Physicist1616|Physicist1616]] ([[User talk:Physicist1616|talk]]) 16:58, 27 October 2017 (UTC)<br />
<br />
== <s>Links to software packages</s> ==<br />
It would be useful to have links to software packages here. I know there is significant controversy in the bitcoin space, but I don't think that should preclude listing related software packages. My edit including links to the core & bitcoin-cash qt clients was reverted with "Bitcoin Cash is NOT bitcoin and it's better not to list it here, please go back to Discussion". Bitcoin cash is very overtly a fork of the bitcoin blockchain - with bch proponents contending it IS bitcoin & core proponents contending it is not. I'm not partial to either side, but bch is a part of bitcoin's history. That aside, I think it would be useful to at least mention main repo packages like (core's) bitcoin-qt, which was what brought me to this wiki page in the first place. Since bch client is AUR and this area is contentious tabling inclusion of fork-from-core software could make sense pending further discussion. Now ok to include bitcoin-qt link? Just trying to improve the wiki...thanks for input in this regard.--[[User:Xris|Xris]] ([[User talk:Xris|talk]]) 21:25, 1 October 2018 (UTC)<br />
<br />
I am adding link to repo package now.--[[User:Xris|Xris]] ([[User talk:Xris|talk]]) 11:45, 3 October 2018 (UTC)<br />
<br />
:Reverted due to previous consensus to avoid flame wars. Please read the [https://wiki.archlinux.org/index.php?title=Talk:Bitcoin&oldid=465690 previous discussions] for the reasoning. -- [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 15:46, 3 October 2018 (UTC)<br />
:: [[User:Lahwaacz|Lahwaacz]]: about your last edit: [https://wiki.archlinux.org/index.php?title=Bitcoin&type=revision&diff=545785&oldid=545731 Informational sites: this is not an informational site - it is biased towards one implementation]:<br />
:: I will just say that you can't be neutral about this issue, Bitcoin Core has the [http://luke.dashjr.org/programs/bitcoin/files/charts/software.html majority of the nodes deployment], and it is Bitcoin through the consensus of those nodes. The nodes are what determine what is Bitcoin and what isn't, so I think reverting my edit was a mistake, and you should revert back to my change -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 01:16, 5 October 2018 (UTC)<br />
<br />
::: We're not going through this whole "discussion" again. The article stays in revision [https://wiki.archlinux.org/index.php?title=Bitcoin&oldid=545787]. Closing. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 08:10, 5 October 2018 (UTC)<br />
:::: OK. I understand you don't want to create another flame war, I can respect that. However, the article is about Bitcoin, and Bitcoin Core is the de facto Bitcoin client. This is fact, not bias, and I feel the article does a poor job at informing the user about this fact. -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 21:25, 5 October 2018 (UTC)<br />
<br />
Thank you Lahwaacz for linking the prior discussion. I'm surprised and saddened by reading through some of those threads. I frankly find much of it confusing, as it refers to IRC discussions with mentions of ultimatums without clear details. What exactly is the controversy relating to linking to software packages? There are vague claims about making packages seem like "ads" or being "scary". I've been using Arch as my primary desktop for a few years in large part due to the great, task-focused, and impartial Arch wiki. This page does not fit that bill at all, and is merely confusing to those seeking to setup and configure bitcoin software on Arch (whatever the package type). Despite the verbosity regarding consensus there is no information about how to configure bitcoin on Arch. There are seemingly Arch-specific idiosyncrasies with bitcoin, as evidenced by the [https://bugs.archlinux.org/task/60235?project=5&string=bitcoin-qt recent bug] that makes core bitcoin-qt not start and just hang - this is what led me to this page for these edits in the first place. I appreciate the shenanigans & proposals from both the e.g. core (and related horrific r/bitcoin) and competing software camps (e.g. bch), but pretending that none of these exist just makes it more confusing for those looking to configure related software on Arch. Given the wikis and FAQs of other distributions, and even the bitcoin software developers themselves, are lacking in many ways, it seems an opportunity for clarity in software setup (in addition to Arch perhaps encountering unique errors in bitcoin code given rolling release support of newer dependent library packages). While not well updated and mainly deferring to core, other distributions have not had trouble at least providing basic information about the core packages ([https://fedoraproject.org/wiki/BITCOIN Fedora], [https://help.ubuntu.com/community/bitcoin Ubuntu]). At minimum providing information about configuring the core reference implementation would be of great practical utility. If you are going to censor edits on how to configure bitcoin related software (as has seemingly been done many times), I would at least request a clear explicit explanation about why this is being done (as I cannot clearly infer this from prior threads that refer to off-wiki IRC chats). I appreciate the input and responses so far, and look forward to thoughts on how to better help people use bitcoin-related software on Arch through this page.--[[User:Xris|Xris]] ([[User talk:Xris|talk]]) 15:50, 7 October 2018 (UTC)<br />
<br />
:In order to stay impartial and high-quality, the content on the ArchWiki is reviewed (or "censored"). The topic about bitcoin is special in regard that none of the reviewers/maintainers/administrators seems to have enough time or patience or interest to gain some sensible knowledge about this mess. As a result, we concluded that the most controversial topics should not be described at all. Unfortunately, the list and implicit comparison of bitcoin software falls into this category, because their developers/protagonists were competing to get the most of the page by twisting the facts. As you have probably found, there were two options considered: either remove the software details or remove the whole page. While definitely not ideal, I think the current page is still better than nothing. -- [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 21:33, 20 October 2018 (UTC)<br />
<br />
== Changed protection level for "Bitcoin": managed by the maintenance team ==<br />
<br />
I'm very upset about this change.<br />
<br />
So now the Bitcoin page is managed by people who have no clue about bitcoin, and it rejects contributions from its actual users. Why this isn't surprising at all? -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 14:36, 13 November 2018 (UTC)</div>Malcontenthttps://wiki.archlinux.org/index.php?title=Talk:Bitcoin&diff=546266Talk:Bitcoin2018-10-05T21:26:22Z<p>Malcontent: Minor English correction</p>
<hr />
<div>== <s>Other Cryptocurrencies</s> ==<br />
<br />
I noticed this is the only real and complete page on any cryptocurrency in the Arch Wiki, perhaps with a bit too much information. Maybe it needs a split or more generalities?<br />
<br />
More importantly, from the perspective of OS Users, it seems like we might be better served by something that addresses cryptocurrencies as a whole, or maybe 2 pages: Cryptocurrency Mining and Cryptocurrency User/Trading that delves into setup of each of the roles for each currency in Arch. I suspect this could eventually split into pages per currency. Discussion? [[User:Physicist1616|Physicist1616]] ([[User talk:Physicist1616|talk]]) 00:03, 24 October 2017 (UTC)<br />
<br />
:Which cryptocurrencies do you have in mind? Note that most of the previous discussions lead to [https://wiki.archlinux.org/index.php?title=Talk:Bitcoin&action=history flame wars], so let's avoid that. Any controversial topic will simply not be covered on this wiki. -- [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 14:59, 24 October 2017 (UTC)<br />
<br />
::Bitcoin (Obviously, but also ASIC miners and the main intermediary currency), Ethereum (GPU miners and recently successful), and Monero (CPU miners and allegedly more focused on privacy than others). I'm not shilling for any of those and so would be fine discussing an alternative to any or adding more to the list. The diversity in how each of those three are mined attracted me. <s>I can't imagine what flame wars could happen other than, "mine is better than yours". Perhaps that's just a failure of imagination.</s> Ok, read the history; yeah, philosophy doesn't belong here, nor does excess detail on how and why or where BTC is going/splitting/etc. This is an OS wiki. [[User:Physicist1616|Physicist1616]] ([[User talk:Physicist1616|talk]]) 16:58, 27 October 2017 (UTC)<br />
<br />
== <s>Links to software packages</s> ==<br />
It would be useful to have links to software packages here. I know there is significant controversy in the bitcoin space, but I don't think that should preclude listing related software packages. My edit including links to the core & bitcoin-cash qt clients was reverted with "Bitcoin Cash is NOT bitcoin and it's better not to list it here, please go back to Discussion". Bitcoin cash is very overtly a fork of the bitcoin blockchain - with bch proponents contending it IS bitcoin & core proponents contending it is not. I'm not partial to either side, but bch is a part of bitcoin's history. That aside, I think it would be useful to at least mention main repo packages like (core's) bitcoin-qt, which was what brought me to this wiki page in the first place. Since bch client is AUR and this area is contentious tabling inclusion of fork-from-core software could make sense pending further discussion. Now ok to include bitcoin-qt link? Just trying to improve the wiki...thanks for input in this regard.--[[User:Xris|Xris]] ([[User talk:Xris|talk]]) 21:25, 1 October 2018 (UTC)<br />
<br />
I am adding link to repo package now.--[[User:Xris|Xris]] ([[User talk:Xris|talk]]) 11:45, 3 October 2018 (UTC)<br />
<br />
:Reverted due to previous consensus to avoid flame wars. Please read the [https://wiki.archlinux.org/index.php?title=Talk:Bitcoin&oldid=465690 previous discussions] for the reasoning. -- [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 15:46, 3 October 2018 (UTC)<br />
:: [[User:Lahwaacz|Lahwaacz]]: about your last edit: [https://wiki.archlinux.org/index.php?title=Bitcoin&type=revision&diff=545785&oldid=545731 Informational sites: this is not an informational site - it is biased towards one implementation]:<br />
:: I will just say that you can't be neutral about this issue, Bitcoin Core has the [http://luke.dashjr.org/programs/bitcoin/files/charts/software.html majority of the nodes deployment], and it is Bitcoin through the consensus of those nodes. The nodes are what determine what is Bitcoin and what isn't, so I think reverting my edit was a mistake, and you should revert back to my change -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 01:16, 5 October 2018 (UTC)<br />
<br />
::: We're not going through this whole "discussion" again. The article stays in revision [https://wiki.archlinux.org/index.php?title=Bitcoin&oldid=545787]. Closing. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 08:10, 5 October 2018 (UTC)<br />
:::: OK. I understand you don't want to create another flame war, I can respect that. However, the article is about Bitcoin, and Bitcoin Core is the de facto Bitcoin client. This is fact, not bias, and I feel the article does a poor job at informing the user about this fact. -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 21:25, 5 October 2018 (UTC)</div>Malcontenthttps://wiki.archlinux.org/index.php?title=Talk:Bitcoin&diff=546265Talk:Bitcoin2018-10-05T21:25:02Z<p>Malcontent: /* Links to software packages */</p>
<hr />
<div>== <s>Other Cryptocurrencies</s> ==<br />
<br />
I noticed this is the only real and complete page on any cryptocurrency in the Arch Wiki, perhaps with a bit too much information. Maybe it needs a split or more generalities?<br />
<br />
More importantly, from the perspective of OS Users, it seems like we might be better served by something that addresses cryptocurrencies as a whole, or maybe 2 pages: Cryptocurrency Mining and Cryptocurrency User/Trading that delves into setup of each of the roles for each currency in Arch. I suspect this could eventually split into pages per currency. Discussion? [[User:Physicist1616|Physicist1616]] ([[User talk:Physicist1616|talk]]) 00:03, 24 October 2017 (UTC)<br />
<br />
:Which cryptocurrencies do you have in mind? Note that most of the previous discussions lead to [https://wiki.archlinux.org/index.php?title=Talk:Bitcoin&action=history flame wars], so let's avoid that. Any controversial topic will simply not be covered on this wiki. -- [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 14:59, 24 October 2017 (UTC)<br />
<br />
::Bitcoin (Obviously, but also ASIC miners and the main intermediary currency), Ethereum (GPU miners and recently successful), and Monero (CPU miners and allegedly more focused on privacy than others). I'm not shilling for any of those and so would be fine discussing an alternative to any or adding more to the list. The diversity in how each of those three are mined attracted me. <s>I can't imagine what flame wars could happen other than, "mine is better than yours". Perhaps that's just a failure of imagination.</s> Ok, read the history; yeah, philosophy doesn't belong here, nor does excess detail on how and why or where BTC is going/splitting/etc. This is an OS wiki. [[User:Physicist1616|Physicist1616]] ([[User talk:Physicist1616|talk]]) 16:58, 27 October 2017 (UTC)<br />
<br />
== <s>Links to software packages</s> ==<br />
It would be useful to have links to software packages here. I know there is significant controversy in the bitcoin space, but I don't think that should preclude listing related software packages. My edit including links to the core & bitcoin-cash qt clients was reverted with "Bitcoin Cash is NOT bitcoin and it's better not to list it here, please go back to Discussion". Bitcoin cash is very overtly a fork of the bitcoin blockchain - with bch proponents contending it IS bitcoin & core proponents contending it is not. I'm not partial to either side, but bch is a part of bitcoin's history. That aside, I think it would be useful to at least mention main repo packages like (core's) bitcoin-qt, which was what brought me to this wiki page in the first place. Since bch client is AUR and this area is contentious tabling inclusion of fork-from-core software could make sense pending further discussion. Now ok to include bitcoin-qt link? Just trying to improve the wiki...thanks for input in this regard.--[[User:Xris|Xris]] ([[User talk:Xris|talk]]) 21:25, 1 October 2018 (UTC)<br />
<br />
I am adding link to repo package now.--[[User:Xris|Xris]] ([[User talk:Xris|talk]]) 11:45, 3 October 2018 (UTC)<br />
<br />
:Reverted due to previous consensus to avoid flame wars. Please read the [https://wiki.archlinux.org/index.php?title=Talk:Bitcoin&oldid=465690 previous discussions] for the reasoning. -- [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 15:46, 3 October 2018 (UTC)<br />
:: [[User:Lahwaacz|Lahwaacz]]: about your last edit: [https://wiki.archlinux.org/index.php?title=Bitcoin&type=revision&diff=545785&oldid=545731 Informational sites: this is not an informational site - it is biased towards one implementation]:<br />
:: I will just say that you can't be neutral about this issue, Bitcoin Core has the [http://luke.dashjr.org/programs/bitcoin/files/charts/software.html majority of the nodes deployment], and it is Bitcoin through the consensus of those nodes. The nodes are what determine what is Bitcoin and what isn't, so I think reverting my edit was a mistake, and you should revert back to my change -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 01:16, 5 October 2018 (UTC)<br />
<br />
::: We're not going through this whole "discussion" again. The article stays in revision [https://wiki.archlinux.org/index.php?title=Bitcoin&oldid=545787]. Closing. -- [[User:Alad|Alad]] ([[User talk:Alad|talk]]) 08:10, 5 October 2018 (UTC)<br />
:::: OK. I understand you don't want to create another flame war, I can respect that. However, the article is about Bitcoin, and Bitcoin Core is the de facto Bitcoin client. This is fact, not bias, and I feel the article does a poor job to inform the user about this fact. -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 21:25, 5 October 2018 (UTC)</div>Malcontenthttps://wiki.archlinux.org/index.php?title=Talk:Bitcoin&diff=546189Talk:Bitcoin2018-10-05T13:45:29Z<p>Malcontent: /* Links to software packages */</p>
<hr />
<div></div>Malcontenthttps://wiki.archlinux.org/index.php?title=Talk:Bitcoin&diff=546125Talk:Bitcoin2018-10-05T01:16:57Z<p>Malcontent: /* Links to software packages */</p>
<hr />
<div>== Other Cryptocurrencies ==<br />
<br />
I noticed this is the only real and complete page on any cryptocurrency in the Arch Wiki, perhaps with a bit too much information. Maybe it needs a split or more generalities?<br />
<br />
More importantly, from the perspective of OS Users, it seems like we might be better served by something that addresses cryptocurrencies as a whole, or maybe 2 pages: Cryptocurrency Mining and Cryptocurrency User/Trading that delves into setup of each of the roles for each currency in Arch. I suspect this could eventually split into pages per currency. Discussion? [[User:Physicist1616|Physicist1616]] ([[User talk:Physicist1616|talk]]) 00:03, 24 October 2017 (UTC)<br />
<br />
:Which cryptocurrencies do you have in mind? Note that most of the previous discussions lead to [https://wiki.archlinux.org/index.php?title=Talk:Bitcoin&action=history flame wars], so let's avoid that. Any controversial topic will simply not be covered on this wiki. -- [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 14:59, 24 October 2017 (UTC)<br />
<br />
::Bitcoin (Obviously, but also ASIC miners and the main intermediary currency), Ethereum (GPU miners and recently successful), and Monero (CPU miners and allegedly more focused on privacy than others). I'm not shilling for any of those and so would be fine discussing an alternative to any or adding more to the list. The diversity in how each of those three are mined attracted me. <s>I can't imagine what flame wars could happen other than, "mine is better than yours". Perhaps that's just a failure of imagination.</s> Ok, read the history; yeah, philosophy doesn't belong here, nor does excess detail on how and why or where BTC is going/splitting/etc. This is an OS wiki. [[User:Physicist1616|Physicist1616]] ([[User talk:Physicist1616|talk]]) 16:58, 27 October 2017 (UTC)<br />
<br />
== Links to software packages ==<br />
It would be useful to have links to software packages here. I know there is significant controversy in the bitcoin space, but I don't think that should preclude listing related software packages. My edit including links to the core & bitcoin-cash qt clients was reverted with "Bitcoin Cash is NOT bitcoin and it's better not to list it here, please go back to Discussion". Bitcoin cash is very overtly a fork of the bitcoin blockchain - with bch proponents contending it IS bitcoin & core proponents contending it is not. I'm not partial to either side, but bch is a part of bitcoin's history. That aside, I think it would be useful to at least mention main repo packages like (core's) bitcoin-qt, which was what brought me to this wiki page in the first place. Since bch client is AUR and this area is contentious tabling inclusion of fork-from-core software could make sense pending further discussion. Now ok to include bitcoin-qt link? Just trying to improve the wiki...thanks for input in this regard.--[[User:Xris|Xris]] ([[User talk:Xris|talk]]) 21:25, 1 October 2018 (UTC)<br />
<br />
I am adding link to repo package now.--[[User:Xris|Xris]] ([[User talk:Xris|talk]]) 11:45, 3 October 2018 (UTC)<br />
<br />
:Reverted due to previous consensus to avoid flame wars. Please read the [https://wiki.archlinux.org/index.php?title=Talk:Bitcoin&oldid=465690 previous discussions] for the reasoning. -- [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 15:46, 3 October 2018 (UTC)<br />
:: [[User:Lahwaacz|Lahwaacz]]: about your last edit: [https://wiki.archlinux.org/index.php?title=Bitcoin&type=revision&diff=545785&oldid=545731 Informational sites: this is not an informational site - it is biased towards one implementation]:<br />
:: I will just say that you can't be neutral about this issue, Bitcoin Core has the [http://luke.dashjr.org/programs/bitcoin/files/charts/software.html majority of the nodes deployment], and it is Bitcoin through the consensus of those nodes. The nodes are what determine what is Bitcoin and what isn't, so I think reverting my edit was a mistake, and you should revert back to my change -- [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 01:16, 5 October 2018 (UTC)</div>Malcontenthttps://wiki.archlinux.org/index.php?title=Talk:Bitcoin&diff=546124Talk:Bitcoin2018-10-05T01:16:23Z<p>Malcontent: /* Links to software packages */</p>
<hr />
<div>== Other Cryptocurrencies ==<br />
<br />
I noticed this is the only real and complete page on any cryptocurrency in the Arch Wiki, perhaps with a bit too much information. Maybe it needs a split or more generalities?<br />
<br />
More importantly, from the perspective of OS Users, it seems like we might be better served by something that addresses cryptocurrencies as a whole, or maybe 2 pages: Cryptocurrency Mining and Cryptocurrency User/Trading that delves into setup of each of the roles for each currency in Arch. I suspect this could eventually split into pages per currency. Discussion? [[User:Physicist1616|Physicist1616]] ([[User talk:Physicist1616|talk]]) 00:03, 24 October 2017 (UTC)<br />
<br />
:Which cryptocurrencies do you have in mind? Note that most of the previous discussions lead to [https://wiki.archlinux.org/index.php?title=Talk:Bitcoin&action=history flame wars], so let's avoid that. Any controversial topic will simply not be covered on this wiki. -- [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 14:59, 24 October 2017 (UTC)<br />
<br />
::Bitcoin (Obviously, but also ASIC miners and the main intermediary currency), Ethereum (GPU miners and recently successful), and Monero (CPU miners and allegedly more focused on privacy than others). I'm not shilling for any of those and so would be fine discussing an alternative to any or adding more to the list. The diversity in how each of those three are mined attracted me. <s>I can't imagine what flame wars could happen other than, "mine is better than yours". Perhaps that's just a failure of imagination.</s> Ok, read the history; yeah, philosophy doesn't belong here, nor does excess detail on how and why or where BTC is going/splitting/etc. This is an OS wiki. [[User:Physicist1616|Physicist1616]] ([[User talk:Physicist1616|talk]]) 16:58, 27 October 2017 (UTC)<br />
<br />
== Links to software packages ==<br />
It would be useful to have links to software packages here. I know there is significant controversy in the bitcoin space, but I don't think that should preclude listing related software packages. My edit including links to the core & bitcoin-cash qt clients was reverted with "Bitcoin Cash is NOT bitcoin and it's better not to list it here, please go back to Discussion". Bitcoin cash is very overtly a fork of the bitcoin blockchain - with bch proponents contending it IS bitcoin & core proponents contending it is not. I'm not partial to either side, but bch is a part of bitcoin's history. That aside, I think it would be useful to at least mention main repo packages like (core's) bitcoin-qt, which was what brought me to this wiki page in the first place. Since bch client is AUR and this area is contentious tabling inclusion of fork-from-core software could make sense pending further discussion. Now ok to include bitcoin-qt link? Just trying to improve the wiki...thanks for input in this regard.--[[User:Xris|Xris]] ([[User talk:Xris|talk]]) 21:25, 1 October 2018 (UTC)<br />
<br />
I am adding link to repo package now.--[[User:Xris|Xris]] ([[User talk:Xris|talk]]) 11:45, 3 October 2018 (UTC)<br />
<br />
:Reverted due to previous consensus to avoid flame wars. Please read the [https://wiki.archlinux.org/index.php?title=Talk:Bitcoin&oldid=465690 previous discussions] for the reasoning. -- [[User:Lahwaacz|Lahwaacz]] ([[User talk:Lahwaacz|talk]]) 15:46, 3 October 2018 (UTC)<br />
:: [[User:Lahwaacz|Lahwaacz]]: about your last edit: [https://wiki.archlinux.org/index.php?title=Bitcoin&type=revision&diff=545785&oldid=545731 Informational sites: this is not an informational site - it is biased towards one implementation]:<br />
:: I will just say that you can't be neutral about this issue, Bitcoin Core has the [http://luke.dashjr.org/programs/bitcoin/files/charts/software.html majority of the nodes deployment], and it is Bitcoin through the consensus of those nodes. The nodes are what determine what is Bitcoin and what isn't, so I think reverting my edit was a mistake, and you should revert back to my change. [[User:Malcontent|Malcontent]] ([[User talk:Malcontent|talk]]) 01:16, 5 October 2018 (UTC)</div>Malcontenthttps://wiki.archlinux.org/index.php?title=Bitcoin&diff=545675Bitcoin2018-10-02T19:32:14Z<p>Malcontent: Add link to bitcoincore.org (reference implementation with the widest adoption)</p>
<hr />
<div>[[Category:Cryptocurrencies]]<br />
[[ja:Bitcoin]]<br />
{{Related articles start}}<br />
{{Related|Nxt}}<br />
{{Related articles end}}<br />
[[Wikipedia:Bitcoin|Bitcoin]] is a decentralized P2P electronic cash system without a central server or trusted parties. Users hold the cryptographic keys to their own money and make transactions directly with each other, with the help of the network to check for double-spending. Bitcoins, usually denoted by BTC (e.g. 0.1 BTC), can also be exchanged for traditional currencies like US dollars.<br />
<br />
== Introduction ==<br />
<br />
The Bitcoin network runs on peer-to-peer networking, digital signatures and cryptographic proof to make and verify transactions. Nodes broadcast transactions to the network, which records them in a public record of all transactions, called the blockchain. A '''block''' is a record of some or all of the most recent Bitcoin transactions that have not yet been recorded in any prior blocks. In order to preserve the integrity of the blockchain, each block in the chain confirms the integrity of the previous one, all the way back to the first one, using hashing.<br />
<br />
New bitcoins are generated by the network through the process of [[#Mining|mining]]. Mining involves inserting a new block into the current blockchain, this is difficult because it requires generating a valid hash (in this case a large integer).<br />
<br />
A variation in difficulty is achieved by requiring that this integer is below a certain threshold - the data in the block is perturbed by a [[Wikipedia:Cryptographic nonce|nonce value]], until the data in the block hashes to produce an integer below the threshold - which takes a lot of processing power. The threshold is set by the number of people currently mining for bitcoins so as to achieve a general speed of about 1 block every 10 minutes.<br />
<br />
=== Consensus ===<br />
<br />
{{Accuracy|Contested section, see [[Talk:Bitcoin#Consensus_changes]]}}<br />
<br />
The ''Consensus'' is a Bitcoin specific term to describe P2P network participants' compatibility, with the ''Consensus rules'' describing implementation details of the protocol to adhere to.<br />
<br />
From [https://en.bitcoin.it/wiki/Consensus Bitcoin.it wiki]:<br />
:The consensus rules are the specific set of rules that all Bitcoin full nodes will unfailingly enforce when considering the validity of a block and its transactions. For example, the Bitcoin consensus rules require that blocks only create a certain number of bitcoins. If a block creates more bitcoins than is allowed, all full nodes will reject this block, even if every other node and miner in the world accepts it. Adding new consensus rules can generally be done as a softfork, while removing any consensus rule requires a hardfork. Rules regarding the behavior of the mere network protocol are not consensus rules, even if a change to the network protocol behavior breaks backward-compatibility. The consensus rules are only concerned with the validity of blocks and transactions.<br />
<br />
:These rules are called consensus rules because Bitcoin requires that all participants in the Bitcoin economy have consensus (with the meaning of the next definition) as to the consensus rules. If the economy disagrees about the consensus rules, then the currency and economy splits into two or more totally-independent pieces.<br />
<br />
{{Warning|It is integral to understand that a bitcoin software you may use is only capable of transacting with parties with which it is in consensus with, i.e. implements the same rules (algorithms) to come to the same result. Should the software's consensus with the network be broken, or consensus of the network at large be broken, the software will only be able to transact with those parties with which it is still in consensus.}}<br />
<br />
==== Nature of consensus failure ====<br />
<br />
The nature of consensus is a very strict yet completely voluntary uncoordinated interaction of many independent users. It is both a requirement of the networks correct operation, and a facilitator of its correct operation at the same time. You can be considered to be in consensus with any other node that will accept any data structure relevant to consensus as valid that you have accepted as valid (ignoring of course an instance where two different miners both find valid blocks at the same time and each relay theirs to part of the network, the next valid block will decide which preceding block was valid based on which one it extends from). Consensus can be broken violating explicit consensus rules (violating a rule explicitly spelled out as a consensus rule, i.e. the cap of 21 million bitcoin, rate at which they are issued, the maximum size of a block, that a transaction is only valid if citing a valid unspent coin, etc.) or violating unexplicit rules (due to a bug or unintended consequence of design, i.e. a valid structure erroneously being invalidated due to software bug/improper format/etc., or the use of an attack avenue to overstress the node with load due to a bug or bad design). Both types of consensus failures could potentially come to be intentionally or unintentionally.<br />
<br />
A discussion of two consensus breaks in Bitcoin Core's history, one explicit, one unexplicit: https://bitcointalk.org/index.php?topic=702755.0<br />
<br />
A discussion of design flaw on reddit (with citation links to official developers discussion): https://www.reddit.com/r/Bitcoin/comments/5h70s3/bitcoin_unlimited_bu_the_developers_have_realized/<br />
<br />
== How to get Bitcoins? ==<br />
<br />
{{Warning|Your private keys are what allows you to spend your Bitcoin under valid consensus rules. They also allow '''anyone''' else possessing them to spend your Bitcoin. Keeping your private keys safe is the equivalent of keeping your Bitcoin safe, the two are inseparable. Most important:<br />
# Encrypt your wallet with a strong password<br />
# Backup your keys and transactions<br />
The Bitcoin Wiki article on [https://en.bitcoin.it/wiki/Securing_your_wallet Wallet Security] contains further information.}}<br />
<br />
There are a variety of ways to acquire bitcoins:<br />
* Accept bitcoins as payment for goods or services.<br />
* There are several services where you can trade them for [https://en.bitcoin.it/wiki/Buying_bitcoins traditional currency].<br />
* Find someone to trade cash for bitcoins in-person through a local directory. To find traders near you, you can use [https://localbitcoins.com/ LocalBitcoins] or a [https://coinmap.org/ bitcoin map].<br />
* Participate in a [https://en.bitcoin.it/wiki/Pooled_mining mining pool].<br />
* If you have very good hardware, you can solo mine and attempt to create a new block (currently yields 12.5 BTC plus fees). See [[#Mining]].<br />
<br />
== Bitcoin software ==<br />
<br />
{{Warning|In order to transact or interact with other clients you must be running compatible software. This is currently a complicated and contentious matter in the Bitcoin community. You are advised to ''very carefully'' research your choice for installation and continuous usage.}}<br />
<br />
Some points to illustrate above warning:<br />
* As mentioned earlier, different clients implement different rules on [[#Consensus]]. For example: <br />
** A [[#Thin client]] does ''per se'' not implement all rules, but only a subset.<br />
** A [[#Full node]] client may be forked to ''allow'' customizing options which are incompatible with the network Consensus at large.<br />
** Another full node may be programmed to validate in Consensus until it has itself reached a majority coverage, in order to leverage majority to implement different rules. The assumption is that the minority will follow suit, see [[#Nature of consensus failure]] for examples.<br />
* A lot of Linux distributions do not officially package bitcoin clients, and one reason are its special requirements to function on the P2P network. Some bitcoin developers even come to the conclusion the clients should [http://luke.dashjr.org/tmp/code/20130723-linux-distribution-packaging-and-bitcoin.md.asc not be packaged] at all. See a related [https://bugzilla.redhat.com/show_bug.cgi?id=1020292 fedora request] for further information. Using a rolling release distribution does pose additional risks in this respect.<br />
<br />
The above implies you should also take continuous due care to test related updates.<br />
<br />
{{Note|As a consequence of highly conflicting and non-resolvable opinions of contributors to this article on ''how'' the different available packages should be described, it had to be exceptionally decided '''not to list any individual packages''' at all.}}<br />
<br />
=== Thin client ===<br />
<br />
The thin clients are also named Simple Payment Verification (SPV) clients.<br />
<br />
Thin clients do not fully validate the blockchain or compute a full Unspent Transaction Output Set (UTXO). They derive their security in proxy by connecting to a fullnode and downloading the blockheaders. They are still able to guarantee the Proof of Work behind a block is valid, and each blockheader contains a merkle root of all the transactions in the block. This allows them to query full node clients for the blockheaders and the data to prove their transaction is in the merkle root in the blockheader. They however must trust that miners are mining valid blocks, and have no way to make sure rules like the issuance rate or cap of Bitcoins are being followed. <br />
<br />
{{Warning|In the event of a consensus failure at large on the network, or one affecting the node(s) an SPV client is connected to, the SPV client is incapable of detecting which partition of the network it is on, or communicating to, or being sent information by. It is extremely insecure to send or receive money with an SPV client in the event of such a consensus failure occurring.}}<br />
<br />
There are several Bitcoin thin client implementations in the [[official repositories]] and in the [[AUR]].<br />
<br />
=== Full node ===<br />
<br />
A full node is a bitcoin client which starts with the initial genesis block of the blockchain, and sequentially validates the signature chain of every historical Bitcoin transaction and validity of each historical block to construct upon arriving at the tip of the chain the current Unspent Transaction Output Set (UTXO). This is the current set of unspent coins, and which private keys they are encumbered to. It is called a full node because it obviously verifies the cryptographic integrity of the UTXO set itself. A full node client may or may not also participate in relaying unconfirmed transactions around the network and operate a mempool of all unconfirmed transactions, and may or may not participate in serving the full historical blockchain to new full node clients bootstrapping themselves.<br />
<br />
There are several Bitcoin full node implementations in the [[official repositories]] and in the [[AUR]].<br />
<br />
If you decide to install one: It is possible to run a full node that deletes almost all historical blocks, only keeping the recent history to a certain threshold, but only after having downloaded (200GB as of October 2018) and verified them (which is CPU intensive) in sequence to arrive at the present period it retains. This is to ensure the same guarantee of the cryptographic integrity of the UTXO set. Afterwards, one may [https://bitcoin.org/en/full-node#reduce-storage reduce storage] and [https://bitcoin.org/en/full-node#reduce-traffic limit bandwith].<br />
<br />
The initial download of the blockchain can be sped up by increasing the database cache as much as your RAM allows, add {{ic|1=dbcache=M}} to {{ic|~/.bitcoin/bitcoin.conf}} where M is the number of megabytes of RAM to allocate.<br />
<br />
=== Mining ===<br />
<br />
{{Note|Mining is only really commercially viable with decent hardware, for a comparison of hardware and their performance see the [https://en.bitcoin.it/wiki/Mining_hardware_comparison bitcoin.it wiki]. To see if your setup is viable use a [https://en.bitcoin.it/wiki/Profitability_Calculator Profit Calculator].}}<br />
<br />
The concept of Bitcoin mining is based on searching for an input that is hard to find but easy to prove the existence of. Bitcoin miners construct blocks that consist of a set of transactions users are trying to make and link them to the previously solved block. Miners add a random piece of data to this, and hash a summary of the block. If the hash of this summary is below the desired target of the network, the block is considered valid. Since it is easy to reproduce any individual hash, they are impossible to predict, so the miner does not know which piece of data will create a desirable hash.<br />
<br />
Mining requires the use of a ''miner'', which is a program used to compute the required hashes and thus create Bitcoins. To learn more about mining please read this [https://en.bitcoin.it/wiki/Mining article].<br />
<br />
There are several Bitcoin miners in the [[official repositories]], as well as in the [[AUR]].<br />
<br />
== See also ==<br />
<br />
==== Informational sites ====<br />
<br />
* [https://bitcoin.org/bitcoin.pdf Bitcoin Whitepaper] - The original whitepaper published by Satoshi Nakamoto before the launch of the live Bitcoin network. <br />
* [https://www.bitcoin.org/ bitcoin.org] - Today the site is an independent open source project with contributors from around the world. Final publication authority is held by the co-owners, but all regular activity is organized through the public pull request process and managed by the site co-maintainers.<br />
* [https://bitcoincore.org/ bitcoincore.org] - Official website of the Bitcoin reference implementation that is used by the majority of nodes on the network.<br />
* [https://en.bitcoin.it/wiki/Main_Page bitcoin.it Wiki] - Bitcoin Wikipedia.<br />
* [http://satoshi.nakamotoinstitute.org/ Satoshi Nakamoto Institute] - Thoughts and quotes from the designer.<br />
* [https://coin.dance/ Coin Dance] - Broad purpose network statistics.<br />
* [https://21.co/learn/introduction-to-bitcoin-concepts/#introduction-to-bitcoin-concepts Introduction to Bitcoin concepts]. - at 21.co<br />
<br />
==== Discussion groups ====<br />
<br />
* [https://bitcointalk.org/ bitcointalk.org] - Forum<br />
* IRC Channels on Freenode:<br />
** '''#bitcoin''' - General Bitcoin-related<br />
** '''#bitcoin-mining''' - Mining discussion<br />
<br />
==== Blockchain explorers ====<br />
<br />
* [https://blockchain.info/ Blockchain.info] - Blockchain explorer/Webwallet.<br />
* [https://btc.blockr.io/ Blockr.io] - Blockchain explorer.<br />
* [https://github.com/znort987/blockparser blockparser] - Fast, quick and dirty bitcoin blockchain parser.<br />
* [https://tradeblock.com/bitcoin/ Tradeblock] - Blockchain explorer with graphical real-time tools.<br />
* [https://live.blockcypher.com/ Blockcypher] - Blockchain explorer.<br />
* [http://bitlox2twvzwbzpk.onion/ BitLox (bitlox2twvzwbzpk.onion)] - [[Tor]] based blockchain explorer.</div>Malcontenthttps://wiki.archlinux.org/index.php?title=Bitcoin&diff=545519Bitcoin2018-10-01T21:00:33Z<p>Malcontent: Update blockchain size</p>
<hr />
<div>[[Category:Cryptocurrencies]]<br />
[[ja:Bitcoin]]<br />
{{Related articles start}}<br />
{{Related|Nxt}}<br />
{{Related articles end}}<br />
[[Wikipedia:Bitcoin|Bitcoin]] is a decentralized P2P electronic cash system without a central server or trusted parties. Users hold the cryptographic keys to their own money and make transactions directly with each other, with the help of the network to check for double-spending. Bitcoins, usually denoted by BTC (e.g. 0.1 BTC), can also be exchanged for traditional currencies like US dollars.<br />
<br />
== Introduction ==<br />
<br />
The Bitcoin network runs on peer-to-peer networking, digital signatures and cryptographic proof to make and verify transactions. Nodes broadcast transactions to the network, which records them in a public record of all transactions, called the blockchain. A '''block''' is a record of some or all of the most recent Bitcoin transactions that have not yet been recorded in any prior blocks. In order to preserve the integrity of the blockchain, each block in the chain confirms the integrity of the previous one, all the way back to the first one, using hashing.<br />
<br />
New bitcoins are generated by the network through the process of [[#Mining|mining]]. Mining involves inserting a new block into the current blockchain, this is difficult because it requires generating a valid hash (in this case a large integer).<br />
<br />
A variation in difficulty is achieved by requiring that this integer is below a certain threshold - the data in the block is perturbed by a [[Wikipedia:Cryptographic nonce|nonce value]], until the data in the block hashes to produce an integer below the threshold - which takes a lot of processing power. The threshold is set by the number of people currently mining for bitcoins so as to achieve a general speed of about 1 block every 10 minutes.<br />
<br />
=== Consensus ===<br />
<br />
{{Accuracy|Contested section, see [[Talk:Bitcoin#Consensus_changes]]}}<br />
<br />
The ''Consensus'' is a Bitcoin specific term to describe P2P network participants' compatibility, with the ''Consensus rules'' describing implementation details of the protocol to adhere to.<br />
<br />
From [https://en.bitcoin.it/wiki/Consensus Bitcoin.it wiki]:<br />
:The consensus rules are the specific set of rules that all Bitcoin full nodes will unfailingly enforce when considering the validity of a block and its transactions. For example, the Bitcoin consensus rules require that blocks only create a certain number of bitcoins. If a block creates more bitcoins than is allowed, all full nodes will reject this block, even if every other node and miner in the world accepts it. Adding new consensus rules can generally be done as a softfork, while removing any consensus rule requires a hardfork. Rules regarding the behavior of the mere network protocol are not consensus rules, even if a change to the network protocol behavior breaks backward-compatibility. The consensus rules are only concerned with the validity of blocks and transactions.<br />
<br />
:These rules are called consensus rules because Bitcoin requires that all participants in the Bitcoin economy have consensus (with the meaning of the next definition) as to the consensus rules. If the economy disagrees about the consensus rules, then the currency and economy splits into two or more totally-independent pieces.<br />
<br />
{{Warning|It is integral to understand that a bitcoin software you may use is only capable of transacting with parties with which it is in consensus with, i.e. implements the same rules (algorithms) to come to the same result. Should the software's consensus with the network be broken, or consensus of the network at large be broken, the software will only be able to transact with those parties with which it is still in consensus.}}<br />
<br />
==== Nature of consensus failure ====<br />
<br />
The nature of consensus is a very strict yet completely voluntary uncoordinated interaction of many independent users. It is both a requirement of the networks correct operation, and a facilitator of its correct operation at the same time. You can be considered to be in consensus with any other node that will accept any data structure relevant to consensus as valid that you have accepted as valid (ignoring of course an instance where two different miners both find valid blocks at the same time and each relay theirs to part of the network, the next valid block will decide which preceding block was valid based on which one it extends from). Consensus can be broken violating explicit consensus rules (violating a rule explicitly spelled out as a consensus rule, i.e. the cap of 21 million bitcoin, rate at which they are issued, the maximum size of a block, that a transaction is only valid if citing a valid unspent coin, etc.) or violating unexplicit rules (due to a bug or unintended consequence of design, i.e. a valid structure erroneously being invalidated due to software bug/improper format/etc., or the use of an attack avenue to overstress the node with load due to a bug or bad design). Both types of consensus failures could potentially come to be intentionally or unintentionally.<br />
<br />
A discussion of two consensus breaks in Bitcoin Core's history, one explicit, one unexplicit: https://bitcointalk.org/index.php?topic=702755.0<br />
<br />
A discussion of design flaw on reddit (with citation links to official developers discussion): https://www.reddit.com/r/Bitcoin/comments/5h70s3/bitcoin_unlimited_bu_the_developers_have_realized/<br />
<br />
== How to get Bitcoins? ==<br />
<br />
{{Warning|Your private keys are what allows you to spend your Bitcoin under valid consensus rules. They also allow '''anyone''' else possessing them to spend your Bitcoin. Keeping your private keys safe is the equivalent of keeping your Bitcoin safe, the two are inseparable. Most important:<br />
# Encrypt your wallet with a strong password<br />
# Backup your keys and transactions<br />
The Bitcoin Wiki article on [https://en.bitcoin.it/wiki/Securing_your_wallet Wallet Security] contains further information.}}<br />
<br />
There are a variety of ways to acquire bitcoins:<br />
* Accept bitcoins as payment for goods or services.<br />
* There are several services where you can trade them for [https://en.bitcoin.it/wiki/Buying_bitcoins traditional currency].<br />
* Find someone to trade cash for bitcoins in-person through a local directory. To find traders near you, you can use [https://localbitcoins.com/ LocalBitcoins] or a [https://coinmap.org/ bitcoin map].<br />
* Participate in a [https://en.bitcoin.it/wiki/Pooled_mining mining pool].<br />
* If you have very good hardware, you can solo mine and attempt to create a new block (currently yields 12.5 BTC plus fees). See [[#Mining]].<br />
<br />
== Bitcoin software ==<br />
<br />
{{Warning|In order to transact or interact with other clients you must be running compatible software. This is currently a complicated and contentious matter in the Bitcoin community. You are advised to ''very carefully'' research your choice for installation and continuous usage.}}<br />
<br />
Some points to illustrate above warning:<br />
* As mentioned earlier, different clients implement different rules on [[#Consensus]]. For example: <br />
** A [[#Thin client]] does ''per se'' not implement all rules, but only a subset.<br />
** A [[#Full node]] client may be forked to ''allow'' customizing options which are incompatible with the network Consensus at large.<br />
** Another full node may be programmed to validate in Consensus until it has itself reached a majority coverage, in order to leverage majority to implement different rules. The assumption is that the minority will follow suit, see [[#Nature of consensus failure]] for examples.<br />
* A lot of Linux distributions do not officially package bitcoin clients, and one reason are its special requirements to function on the P2P network. Some bitcoin developers even come to the conclusion the clients should [http://luke.dashjr.org/tmp/code/20130723-linux-distribution-packaging-and-bitcoin.md.asc not be packaged] at all. See a related [https://bugzilla.redhat.com/show_bug.cgi?id=1020292 fedora request] for further information. Using a rolling release distribution does pose additional risks in this respect.<br />
<br />
The above implies you should also take continuous due care to test related updates.<br />
<br />
{{Note|As a consequence of highly conflicting and non-resolvable opinions of contributors to this article on ''how'' the different available packages should be described, it had to be exceptionally decided '''not to list any individual packages''' at all.}}<br />
<br />
=== Thin client ===<br />
<br />
The thin clients are also named Simple Payment Verification (SPV) clients.<br />
<br />
Thin clients do not fully validate the blockchain or compute a full Unspent Transaction Output Set (UTXO). They derive their security in proxy by connecting to a fullnode and downloading the blockheaders. They are still able to guarantee the Proof of Work behind a block is valid, and each blockheader contains a merkle root of all the transactions in the block. This allows them to query full node clients for the blockheaders and the data to prove their transaction is in the merkle root in the blockheader. They however must trust that miners are mining valid blocks, and have no way to make sure rules like the issuance rate or cap of Bitcoins are being followed. <br />
<br />
{{Warning|In the event of a consensus failure at large on the network, or one affecting the node(s) an SPV client is connected to, the SPV client is incapable of detecting which partition of the network it is on, or communicating to, or being sent information by. It is extremely insecure to send or receive money with an SPV client in the event of such a consensus failure occurring.}}<br />
<br />
There are several Bitcoin thin client implementations in the [[official repositories]] and in the [[AUR]].<br />
<br />
=== Full node ===<br />
<br />
A full node is a bitcoin client which starts with the initial genesis block of the blockchain, and sequentially validates the signature chain of every historical Bitcoin transaction and validity of each historical block to construct upon arriving at the tip of the chain the current Unspent Transaction Output Set (UTXO). This is the current set of unspent coins, and which private keys they are encumbered to. It is called a full node because it obviously verifies the cryptographic integrity of the UTXO set itself. A full node client may or may not also participate in relaying unconfirmed transactions around the network and operate a mempool of all unconfirmed transactions, and may or may not participate in serving the full historical blockchain to new full node clients bootstrapping themselves.<br />
<br />
There are several Bitcoin full node implementations in the [[official repositories]] and in the [[AUR]].<br />
<br />
If you decide to install one: It is possible to run a full node that deletes almost all historical blocks, only keeping the recent history to a certain threshold, but only after having downloaded (200GB as of October 2018) and verified them (which is CPU intensive) in sequence to arrive at the present period it retains. This is to ensure the same guarantee of the cryptographic integrity of the UTXO set. Afterwards, one may [https://bitcoin.org/en/full-node#reduce-storage reduce storage] and [https://bitcoin.org/en/full-node#reduce-traffic limit bandwith].<br />
<br />
The initial download of the blockchain can be sped up by increasing the database cache as much as your RAM allows, add {{ic|1=dbcache=M}} to {{ic|~/.bitcoin/bitcoin.conf}} where M is the number of megabytes of RAM to allocate.<br />
<br />
=== Mining ===<br />
<br />
{{Note|Mining is only really commercially viable with decent hardware, for a comparison of hardware and their performance see the [https://en.bitcoin.it/wiki/Mining_hardware_comparison bitcoin.it wiki]. To see if your setup is viable use a [https://en.bitcoin.it/wiki/Profitability_Calculator Profit Calculator].}}<br />
<br />
The concept of Bitcoin mining is based on searching for an input that is hard to find but easy to prove the existence of. Bitcoin miners construct blocks that consist of a set of transactions users are trying to make and link them to the previously solved block. Miners add a random piece of data to this, and hash a summary of the block. If the hash of this summary is below the desired target of the network, the block is considered valid. Since it is easy to reproduce any individual hash, they are impossible to predict, so the miner does not know which piece of data will create a desirable hash.<br />
<br />
Mining requires the use of a ''miner'', which is a program used to compute the required hashes and thus create Bitcoins. To learn more about mining please read this [https://en.bitcoin.it/wiki/Mining article].<br />
<br />
There are several Bitcoin miners in the [[official repositories]], as well as in the [[AUR]].<br />
<br />
== See also ==<br />
<br />
==== Informational sites ====<br />
<br />
* [https://bitcoin.org/bitcoin.pdf Bitcoin Whitepaper] - The original whitepaper published by Satoshi Nakamoto before the launch of the live Bitcoin network. <br />
* [https://www.bitcoin.org/ bitcoin.org] - Today the site is an independent open source project with contributors from around the world. Final publication authority is held by the co-owners, but all regular activity is organized through the public pull request process and managed by the site co-maintainers.<br />
* [https://en.bitcoin.it/wiki/Main_Page bitcoin.it Wiki] - Bitcoin Wikipedia.<br />
* [http://satoshi.nakamotoinstitute.org/ Satoshi Nakamoto Institute] - Thoughts and quotes from the designer.<br />
* [https://coin.dance/ Coin Dance] - Broad purpose network statistics.<br />
* [https://21.co/learn/introduction-to-bitcoin-concepts/#introduction-to-bitcoin-concepts Introduction to Bitcoin concepts]. - at 21.co<br />
<br />
==== Discussion groups ====<br />
<br />
* [https://bitcointalk.org/ bitcointalk.org] - Forum<br />
* IRC Channels on Freenode:<br />
** '''#bitcoin''' - General Bitcoin-related<br />
** '''#bitcoin-mining''' - Mining discussion<br />
<br />
==== Blockchain explorers ====<br />
<br />
* [https://blockchain.info/ Blockchain.info] - Blockchain explorer/Webwallet.<br />
* [https://btc.blockr.io/ Blockr.io] - Blockchain explorer.<br />
* [https://github.com/znort987/blockparser blockparser] - Fast, quick and dirty bitcoin blockchain parser.<br />
* [https://tradeblock.com/bitcoin/ Tradeblock] - Blockchain explorer with graphical real-time tools.<br />
* [https://live.blockcypher.com/ Blockcypher] - Blockchain explorer.<br />
* [http://bitlox2twvzwbzpk.onion/ BitLox (bitlox2twvzwbzpk.onion)] - [[Tor]] based blockchain explorer.</div>Malcontenthttps://wiki.archlinux.org/index.php?title=Bitcoin&diff=545517Bitcoin2018-10-01T20:56:44Z<p>Malcontent: Bitcoin Cash is NOT bitcoin and it's better not to list it here, please go back to Discussion</p>
<hr />
<div>[[Category:Cryptocurrencies]]<br />
[[ja:Bitcoin]]<br />
{{Related articles start}}<br />
{{Related|Nxt}}<br />
{{Related articles end}}<br />
[[Wikipedia:Bitcoin|Bitcoin]] is a decentralized P2P electronic cash system without a central server or trusted parties. Users hold the cryptographic keys to their own money and make transactions directly with each other, with the help of the network to check for double-spending. Bitcoins, usually denoted by BTC (e.g. 0.1 BTC), can also be exchanged for traditional currencies like US dollars.<br />
<br />
== Introduction ==<br />
<br />
The Bitcoin network runs on peer-to-peer networking, digital signatures and cryptographic proof to make and verify transactions. Nodes broadcast transactions to the network, which records them in a public record of all transactions, called the blockchain. A '''block''' is a record of some or all of the most recent Bitcoin transactions that have not yet been recorded in any prior blocks. In order to preserve the integrity of the blockchain, each block in the chain confirms the integrity of the previous one, all the way back to the first one, using hashing.<br />
<br />
New bitcoins are generated by the network through the process of [[#Mining|mining]]. Mining involves inserting a new block into the current blockchain, this is difficult because it requires generating a valid hash (in this case a large integer).<br />
<br />
A variation in difficulty is achieved by requiring that this integer is below a certain threshold - the data in the block is perturbed by a [[Wikipedia:Cryptographic nonce|nonce value]], until the data in the block hashes to produce an integer below the threshold - which takes a lot of processing power. The threshold is set by the number of people currently mining for bitcoins so as to achieve a general speed of about 1 block every 10 minutes.<br />
<br />
=== Consensus ===<br />
<br />
{{Accuracy|Contested section, see [[Talk:Bitcoin#Consensus_changes]]}}<br />
<br />
The ''Consensus'' is a Bitcoin specific term to describe P2P network participants' compatibility, with the ''Consensus rules'' describing implementation details of the protocol to adhere to.<br />
<br />
From [https://en.bitcoin.it/wiki/Consensus Bitcoin.it wiki]:<br />
:The consensus rules are the specific set of rules that all Bitcoin full nodes will unfailingly enforce when considering the validity of a block and its transactions. For example, the Bitcoin consensus rules require that blocks only create a certain number of bitcoins. If a block creates more bitcoins than is allowed, all full nodes will reject this block, even if every other node and miner in the world accepts it. Adding new consensus rules can generally be done as a softfork, while removing any consensus rule requires a hardfork. Rules regarding the behavior of the mere network protocol are not consensus rules, even if a change to the network protocol behavior breaks backward-compatibility. The consensus rules are only concerned with the validity of blocks and transactions.<br />
<br />
:These rules are called consensus rules because Bitcoin requires that all participants in the Bitcoin economy have consensus (with the meaning of the next definition) as to the consensus rules. If the economy disagrees about the consensus rules, then the currency and economy splits into two or more totally-independent pieces.<br />
<br />
{{Warning|It is integral to understand that a bitcoin software you may use is only capable of transacting with parties with which it is in consensus with, i.e. implements the same rules (algorithms) to come to the same result. Should the software's consensus with the network be broken, or consensus of the network at large be broken, the software will only be able to transact with those parties with which it is still in consensus.}}<br />
<br />
==== Nature of consensus failure ====<br />
<br />
The nature of consensus is a very strict yet completely voluntary uncoordinated interaction of many independent users. It is both a requirement of the networks correct operation, and a facilitator of its correct operation at the same time. You can be considered to be in consensus with any other node that will accept any data structure relevant to consensus as valid that you have accepted as valid (ignoring of course an instance where two different miners both find valid blocks at the same time and each relay theirs to part of the network, the next valid block will decide which preceding block was valid based on which one it extends from). Consensus can be broken violating explicit consensus rules (violating a rule explicitly spelled out as a consensus rule, i.e. the cap of 21 million bitcoin, rate at which they are issued, the maximum size of a block, that a transaction is only valid if citing a valid unspent coin, etc.) or violating unexplicit rules (due to a bug or unintended consequence of design, i.e. a valid structure erroneously being invalidated due to software bug/improper format/etc., or the use of an attack avenue to overstress the node with load due to a bug or bad design). Both types of consensus failures could potentially come to be intentionally or unintentionally.<br />
<br />
A discussion of two consensus breaks in Bitcoin Core's history, one explicit, one unexplicit: https://bitcointalk.org/index.php?topic=702755.0<br />
<br />
A discussion of design flaw on reddit (with citation links to official developers discussion): https://www.reddit.com/r/Bitcoin/comments/5h70s3/bitcoin_unlimited_bu_the_developers_have_realized/<br />
<br />
== How to get Bitcoins? ==<br />
<br />
{{Warning|Your private keys are what allows you to spend your Bitcoin under valid consensus rules. They also allow '''anyone''' else possessing them to spend your Bitcoin. Keeping your private keys safe is the equivalent of keeping your Bitcoin safe, the two are inseparable. Most important:<br />
# Encrypt your wallet with a strong password<br />
# Backup your keys and transactions<br />
The Bitcoin Wiki article on [https://en.bitcoin.it/wiki/Securing_your_wallet Wallet Security] contains further information.}}<br />
<br />
There are a variety of ways to acquire bitcoins:<br />
* Accept bitcoins as payment for goods or services.<br />
* There are several services where you can trade them for [https://en.bitcoin.it/wiki/Buying_bitcoins traditional currency].<br />
* Find someone to trade cash for bitcoins in-person through a local directory. To find traders near you, you can use [https://localbitcoins.com/ LocalBitcoins] or a [https://coinmap.org/ bitcoin map].<br />
* Participate in a [https://en.bitcoin.it/wiki/Pooled_mining mining pool].<br />
* If you have very good hardware, you can solo mine and attempt to create a new block (currently yields 12.5 BTC plus fees). See [[#Mining]].<br />
<br />
== Bitcoin software ==<br />
<br />
{{Warning|In order to transact or interact with other clients you must be running compatible software. This is currently a complicated and contentious matter in the Bitcoin community. You are advised to ''very carefully'' research your choice for installation and continuous usage.}}<br />
<br />
Some points to illustrate above warning:<br />
* As mentioned earlier, different clients implement different rules on [[#Consensus]]. For example: <br />
** A [[#Thin client]] does ''per se'' not implement all rules, but only a subset.<br />
** A [[#Full node]] client may be forked to ''allow'' customizing options which are incompatible with the network Consensus at large.<br />
** Another full node may be programmed to validate in Consensus until it has itself reached a majority coverage, in order to leverage majority to implement different rules. The assumption is that the minority will follow suit, see [[#Nature of consensus failure]] for examples.<br />
* A lot of Linux distributions do not officially package bitcoin clients, and one reason are its special requirements to function on the P2P network. Some bitcoin developers even come to the conclusion the clients should [http://luke.dashjr.org/tmp/code/20130723-linux-distribution-packaging-and-bitcoin.md.asc not be packaged] at all. See a related [https://bugzilla.redhat.com/show_bug.cgi?id=1020292 fedora request] for further information. Using a rolling release distribution does pose additional risks in this respect.<br />
<br />
The above implies you should also take continuous due care to test related updates.<br />
<br />
{{Note|As a consequence of highly conflicting and non-resolvable opinions of contributors to this article on ''how'' the different available packages should be described, it had to be exceptionally decided '''not to list any individual packages''' at all.}}<br />
<br />
=== Thin client ===<br />
<br />
The thin clients are also named Simple Payment Verification (SPV) clients.<br />
<br />
Thin clients do not fully validate the blockchain or compute a full Unspent Transaction Output Set (UTXO). They derive their security in proxy by connecting to a fullnode and downloading the blockheaders. They are still able to guarantee the Proof of Work behind a block is valid, and each blockheader contains a merkle root of all the transactions in the block. This allows them to query full node clients for the blockheaders and the data to prove their transaction is in the merkle root in the blockheader. They however must trust that miners are mining valid blocks, and have no way to make sure rules like the issuance rate or cap of Bitcoins are being followed. <br />
<br />
{{Warning|In the event of a consensus failure at large on the network, or one affecting the node(s) an SPV client is connected to, the SPV client is incapable of detecting which partition of the network it is on, or communicating to, or being sent information by. It is extremely insecure to send or receive money with an SPV client in the event of such a consensus failure occurring.}}<br />
<br />
There are several Bitcoin thin client implementations in the [[official repositories]] and in the [[AUR]].<br />
<br />
=== Full node ===<br />
<br />
A full node is a bitcoin client which starts with the initial genesis block of the blockchain, and sequentially validates the signature chain of every historical Bitcoin transaction and validity of each historical block to construct upon arriving at the tip of the chain the current Unspent Transaction Output Set (UTXO). This is the current set of unspent coins, and which private keys they are encumbered to. It is called a full node because it obviously verifies the cryptographic integrity of the UTXO set itself. A full node client may or may not also participate in relaying unconfirmed transactions around the network and operate a mempool of all unconfirmed transactions, and may or may not participate in serving the full historical blockchain to new full node clients bootstrapping themselves.<br />
<br />
There are several Bitcoin full node implementations in the [[official repositories]] and in the [[AUR]].<br />
<br />
If you decide to install one: It is possible to run a full node that deletes almost all historical blocks, only keeping the recent history to a certain threshold, but only after having downloaded (150GB as of October 2017) and verified them (which is CPU intensive) in sequence to arrive at the present period it retains. This is to ensure the same guarantee of the cryptographic integrity of the UTXO set. Afterwards, one may [https://bitcoin.org/en/full-node#reduce-storage reduce storage] and [https://bitcoin.org/en/full-node#reduce-traffic limit bandwith].<br />
<br />
The initial download of the blockchain can be sped up by increasing the database cache as much as your RAM allows, add {{ic|1=dbcache=M}} to {{ic|~/.bitcoin/bitcoin.conf}} where M is the number of megabytes of RAM to allocate.<br />
<br />
=== Mining ===<br />
<br />
{{Note|Mining is only really commercially viable with decent hardware, for a comparison of hardware and their performance see the [https://en.bitcoin.it/wiki/Mining_hardware_comparison bitcoin.it wiki]. To see if your setup is viable use a [https://en.bitcoin.it/wiki/Profitability_Calculator Profit Calculator].}}<br />
<br />
The concept of Bitcoin mining is based on searching for an input that is hard to find but easy to prove the existence of. Bitcoin miners construct blocks that consist of a set of transactions users are trying to make and link them to the previously solved block. Miners add a random piece of data to this, and hash a summary of the block. If the hash of this summary is below the desired target of the network, the block is considered valid. Since it is easy to reproduce any individual hash, they are impossible to predict, so the miner does not know which piece of data will create a desirable hash.<br />
<br />
Mining requires the use of a ''miner'', which is a program used to compute the required hashes and thus create Bitcoins. To learn more about mining please read this [https://en.bitcoin.it/wiki/Mining article].<br />
<br />
There are several Bitcoin miners in the [[official repositories]], as well as in the [[AUR]].<br />
<br />
== See also ==<br />
<br />
==== Informational sites ====<br />
<br />
* [https://bitcoin.org/bitcoin.pdf Bitcoin Whitepaper] - The original whitepaper published by Satoshi Nakamoto before the launch of the live Bitcoin network. <br />
* [https://www.bitcoin.org/ bitcoin.org] - Today the site is an independent open source project with contributors from around the world. Final publication authority is held by the co-owners, but all regular activity is organized through the public pull request process and managed by the site co-maintainers.<br />
* [https://en.bitcoin.it/wiki/Main_Page bitcoin.it Wiki] - Bitcoin Wikipedia.<br />
* [http://satoshi.nakamotoinstitute.org/ Satoshi Nakamoto Institute] - Thoughts and quotes from the designer.<br />
* [https://coin.dance/ Coin Dance] - Broad purpose network statistics.<br />
* [https://21.co/learn/introduction-to-bitcoin-concepts/#introduction-to-bitcoin-concepts Introduction to Bitcoin concepts]. - at 21.co<br />
<br />
==== Discussion groups ====<br />
<br />
* [https://bitcointalk.org/ bitcointalk.org] - Forum<br />
* IRC Channels on Freenode:<br />
** '''#bitcoin''' - General Bitcoin-related<br />
** '''#bitcoin-mining''' - Mining discussion<br />
<br />
==== Blockchain explorers ====<br />
<br />
* [https://blockchain.info/ Blockchain.info] - Blockchain explorer/Webwallet.<br />
* [https://btc.blockr.io/ Blockr.io] - Blockchain explorer.<br />
* [https://github.com/znort987/blockparser blockparser] - Fast, quick and dirty bitcoin blockchain parser.<br />
* [https://tradeblock.com/bitcoin/ Tradeblock] - Blockchain explorer with graphical real-time tools.<br />
* [https://live.blockcypher.com/ Blockcypher] - Blockchain explorer.<br />
* [http://bitlox2twvzwbzpk.onion/ BitLox (bitlox2twvzwbzpk.onion)] - [[Tor]] based blockchain explorer.</div>Malcontenthttps://wiki.archlinux.org/index.php?title=Intel_graphics&diff=530782Intel graphics2018-07-23T22:05:30Z<p>Malcontent: /* OpenGL 2.1 with i915 driver */</p>
<hr />
<div>[[Category:Graphics]]<br />
[[Category:X server]]<br />
[[cs:Intel graphics]]<br />
[[de:Intel]]<br />
[[es:Intel graphics]]<br />
[[fr:Intel]]<br />
[[hu:Intel graphics]]<br />
[[it:Intel graphics]]<br />
[[ja:Intel Graphics]]<br />
[[pl:Intel graphics]]<br />
[[pt:Intel graphics]]<br />
[[ru:Intel graphics]]<br />
[[zh-hans:Intel graphics]]<br />
[[zh-hant:Intel graphics]]<br />
{{Related articles start}}<br />
{{Related|Intel GMA 3600}}<br />
{{Related|Xorg}}<br />
{{Related|Kernel mode setting}}<br />
{{Related|Xrandr}}<br />
{{Related|Hybrid graphics}}<br />
{{Related|Vulkan}}<br />
{{Related articles end}}<br />
<br />
Since Intel provides and supports open source drivers, Intel graphics are essentially plug-and-play.<br />
<br />
For a comprehensive list of Intel GPU models and corresponding chipsets and CPUs, see [[Wikipedia:List of Intel graphics processing units]].<br />
<br />
{{Note|PowerVR-based graphics ([[Intel GMA 3600|GMA 3600]] series) are not supported by open source drivers.}}<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|mesa}} package, which provides the DRI driver for 3D acceleration.<br />
<br />
* For 32-bit application support, also install the {{Pkg|lib32-mesa}} package from the [[multilib]] repository.<br />
* For the DDX driver (which provides 2D acceleration in [[Xorg]]), [[install]] the {{Pkg|xf86-video-intel}} package. (Often not recommended, see note below.)<br />
* For [[Vulkan]] support (''Ivy Bridge'' and newer), install the {{Pkg|vulkan-intel}} package.<br />
<br />
Also see [[Hardware video acceleration]].<br />
<br />
{{Note|1=Some ([http://www.phoronix.com/scan.php?page=news_item&px=Ubuntu-Debian-Abandon-Intel-DDX Debian & Ubuntu], [http://www.phoronix.com/scan.php?page=news_item&px=Fedora-Xorg-Intel-DDX-Switch Fedora], [https://community.kde.org/Plasma/5.9_Errata#Intel_GPUs KDE]) recommend not installing the {{Pkg|xf86-video-intel}} driver, and instead falling back on the modesetting driver for fourth generation and newer GPUs. See [https://www.reddit.com/r/archlinux/comments/4cojj9/it_is_probably_time_to_ditch_xf86videointel/], [http://www.phoronix.com/scan.php?page=article&item=intel-modesetting-2017&num=1], [[Xorg#Installation]], and {{man|4|modesetting}}. However, the modesetting driver can cause problems such as [https://bugs.chromium.org/p/chromium/issues/detail?id=370022 Chromium Issue 370022]. Also, the modesetting driver will not be benefited by Intel GuC/HuC/DMC firmware.}}<br />
<br />
== Loading ==<br />
<br />
The Intel kernel module should load fine automatically on system boot.<br />
<br />
If it does not happen, then:<br />
<br />
* Make sure you do '''not''' have {{ic|nomodeset}} or {{ic|1=vga=}} as a [[kernel parameter]], since Intel requires kernel mode-setting.<br />
* Also, check that you have not disabled Intel by using any modprobe blacklisting within {{ic|/etc/modprobe.d/}} or {{ic|/usr/lib/modprobe.d/}}.<br />
<br />
=== Enable early KMS ===<br />
<br />
[[Kernel mode setting]] (KMS) is supported by Intel chipsets that use the i915 DRM driver and is mandatory and enabled by default.<br />
<br />
Refer to [[Kernel mode setting#Early KMS start]] for instructions on how to enable KMS as soon as possible at the boot process.<br />
<br />
=== Enable GuC / HuC firmware loading ===<br />
<br />
For Skylake and newer processors, some video features (e.g. CBR rate control on SKL low-power encoding mode) may require the use of an updated GPU firmware, which is currently (as of 4.16) not enabled by default. Enabling GuC/HuC firmware loading can cause issues on some systems; disable it if you experience freezing (for example, after resuming from hibernation).<br />
<br />
It is necessary to add {{ic|1=i915.enable_guc=3}} to the [[kernel parameters]] to enable both GuG and HuC firmware loading. Alternatively, if the [[initramfs]] already includes the {{ic|i915}} module (see [[Kernel mode setting#Early KMS start]]), you can set these options through a file in {{ic|/etc/modprobe.d/}}, e.g.:<br />
<br />
{{hc|/etc/modprobe.d/i915.conf|2=<br />
options i915 enable_guc=3<br />
}}<br />
<br />
You can verify both are enabled by using ''dmesg'':<br />
{{hc|$ dmesg|2=<br />
[drm] HuC: Loaded firmware i915/kbl_huc_ver02_00_1810.bin (version 2.0)<br />
[drm] GuC: Loaded firmware i915/kbl_guc_ver9_39.bin (version 9.39)<br />
i915 0000:00:02.0: GuC firmware version 9.39<br />
i915 0000:00:02.0: GuC submission enabled<br />
i915 0000:00:02.0: HuC enabled<br />
}}<br />
<br />
Alternatively, check using:<br />
<br />
# cat /sys/kernel/debug/dri/0/i915_huc_load_status<br />
# cat /sys/kernel/debug/dri/0/i915_guc_load_status<br />
<br />
== Xorg configuration ==<br />
<br />
There is no need for any configuration to run [[Xorg]].<br />
<br />
However, to take advantage of some driver options, you will need to create a Xorg configuration file similar to the one below:<br />
<br />
{{hc|/etc/X11/xorg.conf.d/20-intel.conf|<br />
Section "Device"<br />
Identifier "Intel Graphics"<br />
Driver "intel"<br />
EndSection}}<br />
<br />
Additional options are added by the user on new lines below {{ic|Driver}}.<br />
For the full list of options, see the {{man|4|intel}} man page.<br />
<br />
{{Note|<br />
*You may need to indicate {{ic|Option "AccelMethod"}} when creating a configuration file, even just to set it to the default method (currently {{ic|"sna"}}); otherwise, X may crash.<br />
*You might need to add more device sections than the one listed above. This will be indicated where necessary.}}<br />
<br />
== Module-based Powersaving Options ==<br />
<br />
The {{ic|i915}} kernel module allows for configuration via [[Kernel modules#Setting module options|module options]]. Some of the module options impact power saving.<br />
<br />
A list of all options along with short descriptions and default values can be generated with the following command:<br />
<br />
$ modinfo -p i915<br />
<br />
To check which options are currently enabled, run<br />
<br />
# systool -m i915 -av<br />
<br />
You will note that many options default to -1, resulting in per-chip powersaving defaults. It is however possible to configure more aggressive powersaving by using [[Kernel modules#Setting module options|module options]].<br />
<br />
{{Warning|1=Diverting from the defaults will mark the kernel as [https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=fc9740cebc3ab7c65f3c5f6ce0caf3e4969013ca tainted] from Linux 3.18 onwards. This basically implies using other options than the per-chip defaults is considered experimental and not supported by the developers. }}<br />
<br />
The following option should be generally safe to enable:<br />
<br />
{{hc|/etc/modprobe.d/i915.conf|<nowiki><br />
options i915 enable_fbc=1<br />
</nowiki>}}<br />
<br />
=== Framebuffer compression (enable_fbc) ===<br />
<br />
Framebuffer compression may be unreliable or unavailable on Intel GPU generations before Sandy Bridge (generation 6). This results in messages logged to the system journal similar to this one:<br />
kernel: drm: not enough stolen space for compressed buffer, disabling.<br />
<br />
Enabling frame buffer compression on pre-Sandy Bridge CPUs results in endless error messages:<br />
<br />
$ dmesg |tail <br />
[ 2360.475430] [drm] not enough stolen space for compressed buffer (need 4325376 bytes), disabling<br />
[ 2360.475437] [drm] hint: you may be able to increase stolen memory size in the BIOS to avoid this<br />
<br />
The solution is to disable frame buffer compression which will imperceptibly increase power consumption (around 0.06 W). In order to disable it add {{ic|i915.enable_fbc&#61;0}} to the kernel line parameters. More information on the results of disabled compression can be found [http://kernel.ubuntu.com/~cking/power-benchmarking/background-colour-and-framebuffer-compression/ here].<br />
<br />
== Tips and tricks ==<br />
<br />
=== Tear-free video ===<br />
<br />
The SNA acceleration method causes tearing for some people. To fix this, enable the {{ic|"TearFree"}} option in the driver by adding the following line to your [[#Xorg configuration|configuration file]]:<br />
Option "TearFree" "true"<br />
<br />
See the [https://bugs.freedesktop.org/show_bug.cgi?id=37686 original bug report] for more info.<br />
<br />
{{Note|1=<nowiki></nowiki><br />
* This option may not work when {{ic|SwapbuffersWait}} is {{ic|false}}.<br />
* This option may increases memory allocation considerably and reduce performance. [https://bugs.freedesktop.org/show_bug.cgi?id=37686#c123]<br />
* This option is problematic for applications that are very picky about vsync timing, like [[Wikipedia:Super Meat Boy|Super Meat Boy]].<br />
* This option does not work with UXA acceleration method, only with SNA.<br />
}}<br />
<br />
=== Disable Vertical Synchronization (VSYNC) ===<br />
Useful when:<br />
* Chomium/Chrome has lags and slow performance due to GPU and runs smoothly with --disable-gpu switch<br />
* glxgears test does not show desired performance<br />
<br />
The intel-driver uses [http://www.intel.com/support/graphics/sb/CS-004527.htm Triple Buffering] for vertical synchronization, this allows for full performance and avoids tearing. To turn vertical synchronization off (e.g. for benchmarking) use this {{ic|.drirc}} in your home directory:<br />
<br />
{{hc|~/.drirc|<br />
<device screen&#61;"0" driver&#61;"dri2"><br />
<application name&#61;"Default"><br />
<option name&#61;"vblank_mode" value&#61;"0"/><br />
</application><br />
</device>}}<br />
<br />
{{Warning|Do not use {{Pkg|driconf}} to create this file. It is buggy and will set the wrong driver.}}<br />
<br />
=== Setting scaling mode ===<br />
<br />
This can be useful for some full screen applications:<br />
<br />
$ xrandr --output LVDS1 --set PANEL_FITTING ''param''<br />
<br />
where {{ic|''param''}} can be:<br />
<br />
* {{ic|center}}: resolution will be kept exactly as defined, no scaling will be made,<br />
* {{ic|full}}: scale the resolution so it uses the entire screen or<br />
* {{ic|full_aspect}}: scale the resolution to the maximum possible but keep the aspect ratio.<br />
<br />
If it does not work, try:<br />
<br />
$ xrandr --output LVDS1 --set "scaling mode" ''param''<br />
<br />
where {{ic|''param''}} is one of {{ic|"Full"}}, {{ic|"Center"}} or {{ic|"Full aspect"}}.<br />
<br />
{{Note|1=This option currently does not work for external displays (e.g. VGA, DVI, HDMI, DP). [https://bugs.freedesktop.org/show_bug.cgi?id=90989]}}<br />
<br />
=== KMS Issue: console is limited to small area ===<br />
<br />
One of the low-resolution video ports may be enabled on boot which is causing the terminal to utilize a small area of the screen. To fix, explicitly disable the port with an i915 module setting with {{ic|1=video=SVIDEO-1:d}} in the kernel command line parameter in the bootloader. See [[Kernel parameters]] for more info.<br />
<br />
If that does not work, try disabling TV1 or VGA1 instead of SVIDEO-1. Video port names can be listed with [[xrandr]].<br />
<br />
=== Hardware accelerated H.264 decoding on GMA 4500 ===<br />
<br />
The {{Pkg|libva-intel-driver}} package only provides hardware accelerated MPEG-2 decoding for GMA 4500 series GPUs. The H.264 decoding support is maintained in a separated g45-h264 branch, which can be used by installing {{AUR|libva-intel-driver-g45-h264}} package. Note however that this support is experimental and its development has been abandoned. Using the VA-API with this driver on a GMA 4500 series GPU will offload the CPU but may not result in as smooth a playback as non-accelerated playback. Tests using mplayer showed that using vaapi to play back an H.264 encoded 1080p video halved the CPU load (compared to the XV overlay) but resulted in very choppy playback, while 720p worked reasonably well [https://bbs.archlinux.org/viewtopic.php?id=150550]. This is echoed by other experiences [http://www.emmolution.org/?p=192&cpage=1#comment-12292].<br />
Setting the preallocated video ram size higher in bios results in much better hardware decoded playback. Even 1080p h264 works well if this is done.<br />
Smooth playback (1080p/720p) works also with {{AUR|mpv-git}} in combination with {{AUR|ffmpeg-git}} and {{AUR|libva-intel-driver-g45-h264}}. With MPV and the Firefox plugin "Watch with MPV"[https://addons.mozilla.org/de/firefox/addon/watch-with-mpv/] it is possible to watch hardware accelerated YouTube videos.<br />
<br />
=== Setting brightness and gamma ===<br />
<br />
See [[Backlight]].<br />
<br />
== Troubleshooting ==<br />
<br />
=== SNA issues ===<br />
<br />
''SNA'' is the default acceleration method in {{Pkg|xf86-video-intel}}. If you experience issues with ''SNA'' (e.g. pixelated graphics, corrupt text, etc.), try using ''UXA'' instead, which can be done by adding the following line to your [[#Xorg configuration|configuration file]]:<br />
Option "AccelMethod" "uxa"<br />
<br />
See {{man|4|intel}} under {{ic|Option "AccelMethod"}}.<br />
<br />
=== DRI3 issues ===<br />
<br />
''DRI3'' is the default DRI version in {{Pkg|xf86-video-intel}}. On some systems this can cause issues such as [https://bugs.chromium.org/p/chromium/issues/detail?id=370022 this]. To switch back to ''DRI2'' add the following line to your [[#Xorg configuration|configuration file]]:<br />
Option "DRI" "2"<br />
<br />
For the {{ic|modesetting}} driver, this method of disabling DRI3 does not work. Instead, one can set the environment variable {{ic|1=LIBGL_DRI3_DISABLE=1}}.<br />
<br />
=== Font and screen corruption in GTK+ applications (missing glyphs after suspend/resume) ===<br />
<br />
Should you experience missing font glyphs in GTK+ applications, the following workaround might help. [[textedit|Edit]] {{ic|/etc/environment}} to add the following line:<br />
<br />
{{hc|/etc/environment|output=<br />
COGL_ATLAS_DEFAULT_BLIT_MODE=framebuffer<br />
}}<br />
<br />
See also [https://bugs.freedesktop.org/show_bug.cgi?id=88584 FreeDesktop bug 88584].<br />
<br />
=== Blank screen during boot, when "Loading modules" ===<br />
<br />
If using "late start" KMS and the screen goes blank when "Loading modules", it may help to add {{ic|i915}} and {{ic|intel_agp}} to the initramfs. See [[Kernel mode setting#Early KMS start]] section.<br />
<br />
Alternatively, appending the following [[kernel parameter]] seems to work as well:<br />
<br />
video=SVIDEO-1:d<br />
<br />
If you need to output to VGA then try this:<br />
<br />
video=VGA-1:1280x800<br />
<br />
=== X freeze/crash with intel driver ===<br />
<br />
Some issues with X crashing, GPU hanging, or problems with X freezing, can be fixed by disabling the GPU usage with the {{ic|NoAccel}} option - add the following lines to your [[#Xorg configuration|configuration file]]:<br />
Option "NoAccel" "True"<br />
<br />
Alternatively, try to disable the 3D acceleration only with the {{ic|DRI}} option:<br />
Option "DRI" "False"<br />
<br />
=== Baytrail complete freeze ===<br />
<br />
If you are using kernel > 3.16 on Baytrail architecture and randomly encounter total system freezes, the following kernel option is a workaround until [https://bugzilla.kernel.org/show_bug.cgi?id=109051 this bug] is fixed in the linux kernel.<br />
<br />
intel_idle.max_cstate=1<br />
<br />
This is originally an Intel CPU bug that can be triggered by certain c-state transitions. It can also happen with Linux kernel 3.16 or Windows, though apparently much more rarely.<br />
The kernel option will prevent the freeze by avoiding c-state transitions but will also increase power consumption.<br />
<br />
=== Adding undetected resolutions ===<br />
<br />
This issue is covered on the [[Xrandr#Adding undetected resolutions|Xrandr page]].<br />
<br />
=== Weathered colors (color range problem) ===<br />
<br />
Kernel 3.9 [http://lists.freedesktop.org/archives/dri-devel/2013-January/033576.html contains] a new default "Automatic" mode for the "Broadcast RGB" property in the Intel driver. It is almost equivalent to "Limited 16:235" (instead of the old default "Full") whenever an HDMI/DP output is in a [http://raspberrypi.stackexchange.com/questions/7332/what-is-the-difference-between-cea-and-dmt CEA mode]. If a monitor does not support signal in limited color range, it will cause weathered colors.<br />
<br />
{{Note|Some monitors/TVs support both color range. In that case an option often known as ''Black Level'' may need to be adjusted to make them handle the signal correctly. Some TVs can handle signal in limited range only. Setting Broadcast RGB to "Full" will cause color clipping. You may need to set it to "Limited 16:235" manually to avoid the clipping.}}<br />
<br />
One can force mode e.g. {{ic|xrandr --output <HDMI> --set "Broadcast RGB" "Full"}} (replace {{ic|<HDMI>}} with the appropriate output device, verify by running {{ic|xrandr}}).<br />
<br />
Unfortunately, the Intel driver does not support setting the color range through an {{ic|xorg.conf.d}} configuration file.<br />
<br />
A [https://bugzilla.kernel.org/show_bug.cgi?id=94921 bug report] is filed and a patch can be found in the attachment.<br />
<br />
Also there are other related problems which can be fixed editing GPU registers. More information can be found [http://lists.freedesktop.org/archives/intel-gfx/2012-April/016217.html] and [http://github.com/OpenELEC/OpenELEC.tv/commit/09109e9259eb051f34f771929b6a02635806404c].<br />
<br />
=== Backlight is not adjustable===<br />
<br />
If after resuming from suspend, the hotkeys for changing the screen brightness do not take effect, check your configuration against the [[Backlight]] article.<br />
<br />
If the problem persists, try one of the following [[kernel parameters]]:<br />
<br />
acpi_osi=Linux<br />
acpi_osi="!Windows 2012"<br />
acpi_osi=<br />
<br />
=== Corruption/Unresponsiveness in Chromium and Firefox ===<br />
<br />
If you experience corruption, unresponsiveness, lags or slow performance in Chromium and/or Firefox: <br />
* [[#SNA issues|Set the AccelMethod to "uxa"]]<br />
* [[#Disable Vertical Synchronization (VSYNC)|Disable VSYNC]]<br />
<br />
=== Kernel crashing w/kernels 4.0+ on Broadwell/Core-M chips ===<br />
<br />
A few seconds after X/Wayland loads the machine will freeze and journalctl will log a kernel crash referencing the Intel graphics as below:<br />
<br />
Jun 16 17:54:03 hostname kernel: BUG: unable to handle kernel NULL pointer dereference at (null)<br />
Jun 16 17:54:03 hostname kernel: IP: [< (null)>] (null)<br />
...<br />
Jun 16 17:54:03 hostname kernel: CPU: 0 PID: 733 Comm: gnome-shell Tainted: G U O 4.0.5-1-ARCH #1<br />
...<br />
Jun 16 17:54:03 hostname kernel: Call Trace:<br />
Jun 16 17:54:03 hostname kernel: [<ffffffffa055cc27>] ? i915_gem_object_sync+0xe7/0x190 [i915]<br />
Jun 16 17:54:03 hostname kernel: [<ffffffffa0579634>] intel_execlists_submission+0x294/0x4c0 [i915]<br />
Jun 16 17:54:03 hostname kernel: [<ffffffffa05539fc>] i915_gem_do_execbuffer.isra.12+0xabc/0x1230 [i915]<br />
Jun 16 17:54:03 hostname kernel: [<ffffffffa055d349>] ? i915_gem_object_set_to_cpu_domain+0xa9/0x1f0 [i915]<br />
Jun 16 17:54:03 hostname kernel: [<ffffffff811ba2ae>] ? __kmalloc+0x2e/0x2a0<br />
Jun 16 17:54:03 hostname kernel: [<ffffffffa0555471>] i915_gem_execbuffer2+0x141/0x2b0 [i915]<br />
Jun 16 17:54:03 hostname kernel: [<ffffffffa042fcab>] drm_ioctl+0x1db/0x640 [drm]<br />
Jun 16 17:54:03 hostname kernel: [<ffffffffa0555330>] ? i915_gem_execbuffer+0x450/0x450 [i915]<br />
Jun 16 17:54:03 hostname kernel: [<ffffffff8122339b>] ? eventfd_ctx_read+0x16b/0x200<br />
Jun 16 17:54:03 hostname kernel: [<ffffffff811ebc36>] do_vfs_ioctl+0x2c6/0x4d0<br />
Jun 16 17:54:03 hostname kernel: [<ffffffff811f6452>] ? __fget+0x72/0xb0<br />
Jun 16 17:54:03 hostname kernel: [<ffffffff811ebec1>] SyS_ioctl+0x81/0xa0<br />
Jun 16 17:54:03 hostname kernel: [<ffffffff8157a589>] system_call_fastpath+0x12/0x17<br />
Jun 16 17:54:03 hostname kernel: Code: Bad RIP value.<br />
Jun 16 17:54:03 hostname kernel: RIP [< (null)>] (null)<br />
<br />
This can be fixed by disabling execlist support which was changed to default on with kernel 4.0. Add the following [[kernel parameter]]:<br />
i915.enable_execlists=0<br />
<br />
This is known to be broken to at least kernel 4.0.5.<br />
<br />
=== Lag in Windows guests ===<br />
<br />
The video output of a Windows guest in VirtualBox sometimes hangs until the host forces a screen update (e.g. by moving the mouse cursor). Removing the {{ic|1=enable_fbc=1}} option fixes this issue.<br />
<br />
=== Screen flickering ===<br />
<br />
Panel Self Refresh (PSR), a power saving feature used by Intel iGPUs is known to cause flickering in some instances {{Bug|49628}} {{Bug|49371}} {{Bug|50605}}. A temporary solution is to disable this feature using the [[kernel parameter]] {{ic|1=i915.enable_psr=0}}.<br />
<br />
=== OpenGL 2.1 with i915 driver ===<br />
<br />
The update of {{Pkg|mesa}} from version 13.x to 17 may break support for OpenGL 2.1 on third gen Intel GPUs (GMA3100, see [[wikipedia:List_of_Intel_graphics_processing_units#Third_generation|here]]), as described in this [http://www.phoronix.com/scan.php?page=news_item&px=Mesa-i915-OpenGL-2-Drop article], reverting it back to OpenGL 1.4. However this could be restored manually by setting {{ic|/etc/drirc}} or {{ic|~/.drirc}} options like:<br />
{{hc|/etc/drirc|output=<br />
<driconf><br />
...<br />
<device driver="i915"><br />
<application name="Default"><br />
<option name="'''stub_occlusion_query'''" value="'''true'''" /><br />
<option name="'''fragment_shader'''" value="'''true'''" /><br />
</application><br />
</device><br />
...<br />
</driconf><br />
}}<br />
{{Note|the reason of this step back was Chromium and other apps bad experience. If needed, you might edit the drirc file in a "app-specific" style, see [https://dri.freedesktop.org/wiki/ConfigurationInfrastructure/ here], to disable gl2.1 on executable chromium for instance.}}<br />
<br />
== See also ==<br />
<br />
* https://01.org/linuxgraphics/documentation (includes a list of supported hardware)</div>Malcontent