- Supported Linux and FreeBSD virtual machines for Hyper-V on Windows
- Best Practices for running Linux on Hyper-V
- Tuning Linux File Systems on Dynamic VHDX Files
- Grub Menu Timeout on Generation 2 Virtual Machines
- PxE Boot on Generation 2 Virtual Machines
- Use static MAC addresses with failover clustering
- Use Hyper-V-specific network adapters, not the legacy network adapter
- Use I/O scheduler noop/none for better disk I/O performance
- Reserve more memory for kdump
- Shrinking VHDX or expanding VHD and VHDX files can result in erroneous GPT partition tables
- Поддерживаемые виртуальные машины Linux и FreeBSD для Hyper-V на Windows
- Рекомендации по запуску Linux в Hyper-V
- Настройка файловых систем Linux в динамических VHDX-файлах
- Время ожидания меню GRUB на виртуальных машинах поколения 2
- Загрузка PxE на виртуальных машинах поколения 2
- Использование статических MAC-адресов с отказоустойчивой кластеризацией
- Использование сетевых адаптеров, относящихся к Hyper-V, а не устаревших сетевых адаптеров
- Для повышения производительности дискового ввода-вывода используйте планировщик заданий (NOOP/None)
- Зарезервируйте больше памяти для кдумп
- Сжатие VHDX-файлов или расширения VHD и VHDX может привести к ошибочным таблицам разделов GPT
Supported Linux and FreeBSD virtual machines for Hyper-V on Windows
Applies to: Windows Server 2022, Azure Stack HCI, version 20H2; Windows Server 2019, Windows Server 2016, Hyper-V Server 2016, Windows Server 2012 R2, Hyper-V Server 2012 R2, Windows Server 2012, Hyper-V Server 2012, Windows Server 2008 R2, Windows 10, Windows 8.1, Windows 8, Windows 7.1, Windows 7
Hyper-V supports both emulated and Hyper-V-specific devices for Linux and FreeBSD virtual machines. When running with emulated devices, no additional software is required to be installed. However emulated devices do not provide high performance and cannot leverage the rich virtual machine management infrastructure that the Hyper-V technology offers. In order to make full use of all benefits that Hyper-V provides, it is best to use Hyper-V-specific devices for Linux and FreeBSD. The collection of drivers that are required to run Hyper-V-specific devices are known as Linux Integration Services (LIS) or FreeBSD Integration Services (BIS).
LIS has been added to the Linux kernel and is updated for new releases. But Linux distributions based on older kernels may not have the latest enhancements or fixes. Microsoft provides a download containing installable LIS drivers for some Linux installations based on these older kernels. Because distribution vendors include versions of Linux Integration Services, it is best to install the latest downloadable version of LIS, if applicable, for your installation.
For other Linux distributions LIS changes are regularly integrated into the operating system kernel and applications so no separate download or installation is required.
For older FreeBSD releases (before 10.0), Microsoft provides ports that contain the installable BIS drivers and corresponding daemons for FreeBSD virtual machines. For newer FreeBSD releases, BIS is built in to the FreeBSD operating system, and no separate download or installation is required except for a KVP ports download that is needed for FreeBSD 10.0.
The goal of this content is to provide information that helps facilitate your Linux or FreeBSD deployment on Hyper-V. Specific details include:
Linux distributions or FreeBSD releases that require the download and installation of LIS or BIS drivers.
Linux distributions or FreeBSD releases that contain built-in LIS or BIS drivers.
Feature distribution maps that indicate the features in major Linux distributions or FreeBSD releases.
Known issues and workarounds for each distribution or release.
Feature description for each LIS or BIS feature.
Want to make a suggestion about features and functionality? Is there something we could do better? You can use the Windows Server User Voice site to suggest new features and capabilities for Linux and FreeBSD Virtual Machines on Hyper-V, and to see what other people are saying.
Источник
Best Practices for running Linux on Hyper-V
Applies to: Windows Server 2022, Azure Stack HCI, version 20H2; Windows Server 2019, Windows Server 2016, Hyper-V Server 2016, Windows Server 2012 R2, Hyper-V Server 2012 R2, Windows Server 2012, Hyper-V Server 2012, Windows Server 2008 R2, Windows 10, Windows 8.1, Windows 8, Windows 7.1, Windows 7
This topic contains a list of recommendations for running Linux virtual machine on Hyper-V.
Tuning Linux File Systems on Dynamic VHDX Files
Some Linux file systems may consume significant amounts of real disk space even when the file system is mostly empty. To reduce the amount of real disk space usage of dynamic VHDX files, consider the following recommendations:
- When creating the VHDX, use 1MB BlockSizeBytes (from the default 32MB) in PowerShell, for example:
- При создании VHDX используйте 1 МБ Блокксизебитес (из 32 МБ по умолчанию) в PowerShell, например:
The ext4 format is preferred to ext3 because ext4 is more space efficient than ext3 when used with dynamic VHDX files.
When creating the filesystem specify the number of groups to be 4096, for example:
Grub Menu Timeout on Generation 2 Virtual Machines
Because of legacy hardware being removed from emulation in Generation 2 virtual machines, the grub menu countdown timer counts down too quickly for the grub menu to be displayed, immediately loading the default entry. Until grub is fixed to use the EFI-supported timer, modify /boot/grub/grub.conf, /etc/default/grub, or equivalent to have «timeout=100000» instead of the default «timeout=5».
PxE Boot on Generation 2 Virtual Machines
Because the PIT timer is not present in Generation 2 Virtual Machines, network connections to the PxE TFTP server can be prematurely terminated and prevent the bootloader from reading Grub configuration and loading a kernel from the server.
On Linux distributions other than RHEL 6.x, similar steps can be followed to configure grub v0.97 to load Linux kernels from a PxE server.
Additionally, on RHEL/CentOS 6.6 keyboard and mouse input will not work with the pre-install kernel which prevents specifying installation options in the menu. A serial console must be configured to allow choosing installation options.
In the efidefault file on the PxE server, add the following kernel parameter «console=ttyS1»
On the VM in Hyper-V, set up a COM port using this PowerShell cmdlet:
Specifying a kickstart file to the pre-install kernel would also avoid the need for keyboard and mouse input during installation.
Use static MAC addresses with failover clustering
Linux virtual machines that will be deployed using failover clustering should be configured with a static media access control (MAC) address for each virtual network adapter. In some versions of Linux, the networking configuration may be lost after failover because a new MAC address is assigned to the virtual network adapter. To avoid losing the network configuration, ensure that each virtual network adapter has a static MAC address. You can configure the MAC address by editing the settings of the virtual machine in Hyper-V Manager or Failover Cluster Manager.
Use Hyper-V-specific network adapters, not the legacy network adapter
Configure and use the virtual Ethernet adapter, which is a Hyper-V-specific network card with enhanced performance. If both legacy and Hyper-V-specific network adapters are attached to a virtual machine, the network names in the output of ifconfig -a might show random values such as _tmp12000801310. To avoid this issue, remove all legacy network adapters when using Hyper-V-specific network adapters in a Linux virtual machine.
Use I/O scheduler noop/none for better disk I/O performance
The Linux kernel offers two sets of disk I/O schedulers to reorder requests. One set is for the older вЂblk’ subsystem and one set is for the newer вЂblk-mq’ subsystem. In either case, with today’s solid state disks it is recommended to use a scheduler that passes the scheduling decisions to the underlying Hyper-V hypervisor. For Linux kernels using the вЂblk’ subsystem, this is the “noop” scheduler. For Linux kernels using the вЂblk-mq’ subsystem, this is the “none” scheduler.
For a particular disk, the available schedulers can be seen at this file system location: /sys/class/block/ /queue/scheduler, with the currently selected scheduler in square brackets. You can change the scheduler by writing to this file system location. The change must be added to an initialization script in order to persist across reboots. Consult your Linux distro documentation for details.
Linux kernel versions earlier than 2.6.37 don’t support NUMA on Hyper-V with larger VM sizes. This issue primarily impacts older distributions using the upstream Red Hat 2.6.32 kernel, and was fixed in Red Hat Enterprise Linux (RHEL) 6.6 (kernel-2.6.32-504). Systems running custom kernels older than 2.6.37, or RHEL-based kernels older than 2.6.32-504 must set the boot parameter numa=off on the kernel command line in grub.conf. For more information, see Red Hat KB 436883.
Reserve more memory for kdump
In case the dump capture kernel ends up with a panic on boot, reserve more memory for the kernel. For example, change the parameter crashkernel=384M-:128M to crashkernel=384M-:256M in the Ubuntu grub configuration file.
Shrinking VHDX or expanding VHD and VHDX files can result in erroneous GPT partition tables
Hyper-V allows shrinking virtual disk (VHDX) files without regard for any partition, volume, or file system data structures that may exist on the disk. If the VHDX is shrunk to where the end of the VHDX comes before the end of a partition, data can be lost, that partition can become corrupted, or invalid data can be returned when the partition is read.
After resizing a VHD or VHDX, administrators should use a utility like fdisk or parted to update the partition, volume, and file system structures to reflect the change in the size of the disk. Shrinking or expanding the size of a VHD or VHDX that has a GUID Partition Table (GPT) will cause a warning when a partition management tool is used to check the partition layout, and the administrator will be warned to fix the first and secondary GPT headers. This manual step is safe to perform without data loss.
Источник
Поддерживаемые виртуальные машины Linux и FreeBSD для Hyper-V на Windows
область применения: Windows Server 2022, Azure Stack хЦи, версия 20H2; Windows сервер 2019, Windows Server 2016, Hyper-V Server 2016, Windows Server 2012 r2, Hyper-V Server 2012 R2, Windows Server 2012, Hyper-V Server 2012, Windows Server 2008 R2, Windows 10, Windows 8.1, Windows 8, Windows 7,1, Windows 7
Hyper-V поддерживает как эмулированные, так и устройства Hyper-V для виртуальных машин Linux и FreeBSD. При работе с имитируемыми устройствами не требуется устанавливать дополнительное программное обеспечение. Однако эмулированные устройства не обеспечивают высокую производительность и не могут использовать обширную инфраструктуру управления виртуальными машинами, предлагаемую технологией Hyper-V. Чтобы полностью использовать все преимущества, предоставляемые Hyper-V, лучше всего использовать устройства, относящиеся к Hyper-V, для Linux и FreeBSD. Коллекция драйверов, необходимых для запуска устройств, связанных с Hyper-V, известна как Linux Integration Services (LIS) или FreeBSD Integration Services (BIS).
LIS был добавлен в ядро Linux и обновлен для новых выпусков. Однако дистрибутивы Linux, основанные на старых ядрах, могут не иметь последних улучшений или исправлений. Корпорация Майкрософт предоставляет загружаемый пакет, содержащий устанавливаемые драйверы LIS для некоторых установок Linux на основе этих старых ядер. Поскольку поставщики распространения включают версии Linux Integration Services, лучше установить последнюю загружаемую версию LIS, если это применимо, для установки.
Для других дистрибутивов Linux изменения LIS регулярно интегрируются в ядро операционной системы и приложения, поэтому отдельное скачивание или установка не требуются.
Для старых выпусков FreeBSD (до 10,0) корпорация Майкрософт предоставляет порты, которые содержат устанавливаемые драйверы BIS и соответствующие управляющие программы для виртуальных машин FreeBSD. Для новых выпусков FreeBSD номер BIS встроен в операционную систему FreeBSD, и отдельное скачивание или установка не требуются, за исключением загрузки KVP портов, необходимой для FreeBSD 10,0.
Целью этого содержимого является предоставление информации, помогающей упростить развертывание Linux или FreeBSD в Hyper-V. Ниже приведены конкретные сведения.
Дистрибутивы Linux или выпуски FreeBSD, требующие загрузки и установки драйверов LIS или BIS.
Дистрибутивы Linux или выпуски FreeBSD, содержащие встроенные драйверы LIS или BIS.
Карты распределения компонентов, которые указывают на функции в основных дистрибутивах Linux или в выпусках FreeBSD.
Известные проблемы и способы их решения для каждого распространения или выпуска.
Описание функции для каждого компонента LIS или BIS.
Хотите принять предложение о функциях и функциях? Что мы можем сделать лучше? вы можете использовать сайт пользователя Windows Server , чтобы предложить новые функции и возможности для виртуальных машин Linux и FreeBSD в Hyper-V, а также узнать, какие другие люди говорят.
Источник
Рекомендации по запуску Linux в Hyper-V
область применения: Windows Server 2022, Azure Stack хЦи, версия 20H2; Windows сервер 2019, Windows Server 2016, Hyper-V Server 2016, Windows Server 2012 r2, Hyper-V Server 2012 R2, Windows Server 2012, Hyper-V Server 2012, Windows Server 2008 R2, Windows 10, Windows 8.1, Windows 8, Windows 7,1, Windows 7
Этот раздел содержит список рекомендаций по запуску виртуальной машины Linux в Hyper-V.
Настройка файловых систем Linux в динамических VHDX-файлах
Некоторые файловые системы Linux могут потреблять значительный объем свободного места на диске, даже если файловая система в основном пуста. Чтобы уменьшить объем используемого дискового пространства в динамических VHDX-файлах, учитывайте следующие рекомендации.
Формат ext4 является предпочтительным для ext3, так как ext4 больше пространства, чем ext3 при использовании с динамическими VHDX-файлами.
При создании файловой системы укажите число групп 4096, например:
Время ожидания меню GRUB на виртуальных машинах поколения 2
Из-за того, что устаревшее оборудование удаляется из эмуляции на виртуальных машинах поколения 2, для отображения меню GRUB слишком быстро вычисляется таймер обратного отсчета, и сразу же загружается запись по умолчанию. Пока GRUB не будет использоваться для использования таймера, поддерживаемого EFI, измените /Бут/груб/груб.конф,/т.п./default/grub или эквивалентным параметром «Timeout = 100000» вместо значения по умолчанию «timeout = 5».
Загрузка PxE на виртуальных машинах поколения 2
Так как в виртуальных машинах поколения 2 отсутствует таймер «СМОЛой», сетевые подключения к PxE-серверу TFTP можно преждевременно завершить и предотвратить считывание конфигурации GRUB и загрузку ядра с сервера.
В дистрибутивах Linux, отличных от RHEL 6. x, можно выполнить аналогичные действия, чтобы настроить GRUB v 0.97 для загрузки ядер Linux с PxE-сервера.
Кроме того, при вводе с помощью клавиатуры и мыши RHEL/CentOS 6,6 не будет работать с предварительно установленным ядром, что не позволит указать параметры установки в меню. Чтобы разрешить выбор параметров установки, должна быть настроена последовательная консоль.
В файле ефидефаулт на PxE-сервере добавьте следующий параметр ядра «console = ttyS1» .
На виртуальной машине в Hyper-V настройте COM-порт с помощью этого командлета PowerShell:
Указание файла Kickstart для предварительно установленного ядра также позволит избежать необходимости ввода с клавиатуры и мыши во время установки.
Использование статических MAC-адресов с отказоустойчивой кластеризацией
Виртуальные машины Linux, которые будут развернуты с помощью отказоустойчивой кластеризации, должны быть настроены со статическим MAC-адресом для каждого виртуального сетевого адаптера. В некоторых версиях Linux сетевая конфигурация может быть потеряна после отработки отказа, поскольку виртуальному сетевому адаптеру назначается новый MAC-адрес. Чтобы избежать потери конфигурации сети, убедитесь, что у каждого виртуального сетевого адаптера есть статический MAC-адрес. Вы можете настроить MAC-адрес, изменив параметры виртуальной машины в диспетчере Hyper-V или диспетчер отказоустойчивости кластеров.
Использование сетевых адаптеров, относящихся к Hyper-V, а не устаревших сетевых адаптеров
Настройте и используйте виртуальный адаптер Ethernet, который является сетевой картой Hyper-V с повышенной производительностью. Если к виртуальной машине подключены как устаревшие, так и сетевые адаптеры, относящиеся к Hyper-V, сетевые имена в выходных данных команды ifconfig-a могут показывать случайные значения, такие как _tmp12000801310. Чтобы избежать этой проблемы, удалите все устаревшие сетевые адаптеры при использовании сетевых адаптеров, связанных с Hyper-V, в виртуальной машине Linux.
Для повышения производительности дискового ввода-вывода используйте планировщик заданий (NOOP/None)
Ядро Linux предлагает два набора планировщиков дискового ввода-вывода для переупорядочивания запросов. Один набор предназначен для более старой подсистемы «BLK», а один — для новой подсистемы «BLK-MQ». В любом случае с современными твердотельными дисками рекомендуется использовать планировщик, который передает решения о планировании в базовый гипервизор Hyper-V. Для ядер Linux, использующих подсистему «BLK», это планировщик «NOOP». Для ядер Linux, использующих подсистему «BLK-MQ», это планировщик «None».
Для конкретного диска доступные планировщики могут отображаться в этой папке файловой системы:/СИС/класс/блокк/ /куеуе/счедулер с выбранным планировщиком в квадратных скобках. Планировщик можно изменить, записав в это расположение файловой системы. Чтобы сохранить изменения между перезагрузками, необходимо добавить это изменение в скрипт инициализации. Дополнительные сведения см. в документации по дистрибутив Linux.
Версии ядра Linux ниже 2.6.37 не поддерживают NUMA в Hyper-V с виртуальными машинами большего размера. Эта проблема влияет в основном на дистрибутивы более ранних версий, в которых используется исходное ядро Red Hat 2.6.32, и была исправлена в Red Hat Enterprise Linux (RHEL) 6.6 (kernel-2.6.32-504). В системах под управлением модифицированных ядер старше версии 2.6.37 или ядер RHEL старше 2.6.32-504 в командной строке ядра необходимо задать параметр загрузки numa=off в файле grub.conf. Дополнительные сведения см. в статье базы знаний Red Hat 436883.
Зарезервируйте больше памяти для кдумп
Если ядро записи дампа завершается с тревогой при загрузке, зарезервируйте больше памяти для ядра. Например, измените параметр crashkernel = 384M-: 128M на crashkernel = 384M-: 256M в файле конфигурации Ubuntu GRUB.
Сжатие VHDX-файлов или расширения VHD и VHDX может привести к ошибочным таблицам разделов GPT
Hyper-V позволяет сжимать файлы виртуального диска (VHDX) без учета разделов, томов или структур данных файловой системы, которые могут существовать на диске. Если VHDX-файл сжимается до конца раздела, то данные могут быть потеряны, при этом Секция может быть повреждена, а при чтении секции могут возвращаться недопустимые данные.
После изменения размера VHD или VHDX администраторы должны использовать служебную программу, например fdisk, или частично обновить структуру разделов, томов и файловой системы, чтобы отразить изменение размера диска. Сжатие или увеличение размера VHD или VHDX с таблицей разделов GUID (GPT) вызовет предупреждение, если для проверки макета раздела используется средство управления секциями, и администратору будет выведено предупреждение об исправлении первого и дополнительного заголовков GPT. Этот ручной этап можно выполнить без потери данных.
Источник