Linux kvm mac os

Mac OS X в эмуляторе QEMU под Linux

Здравствуйте хабровчане. Недавно понадобилось писать на Objective C под Mac OS X. Железо у меня не самое подходящее для всяких сборок, да и сидеть полностью в этой ОС религия не позволяет. Решил поставить Mac OS X в на виртуальную машину Qemu в Linux.

Вот список всего, что я использовал:

Gentoo Linux 64 bit
Qemu 0.10.5
KVM (Kernel-based Virtual Machine) 88-r1
Поддержка KVM в ядре Linux
Процессор с поддержкой Intel Virtualization Technology (в моем случае это Core2Duo E6400)
Linux kernel>=2.6.20
-Сборка Mac OS X iATKOS v7 (Leopard 10.5.7)

Переходим к настройке, в ядре необходимо добавить KVM. Качаем исходники, распаковываем, запускаем make menuconfig:
Processor type and features->Paravirtualized guest support
Отмечаем:
KVM paravirtualized clock
KVM Guest support
Paravirtualization layer for spinlocks

Далее в корне настройки ядра появляется новая опция Virtualization
Переходим туда и отмечаем:
Kernel-based Virtual Machine (KVM) support
KVM for Intel processors support
KVM trace support
PCI driver for virtio devices
Virtio balloon driver

Собираем, устанавливаем, и перезагружаемся с новым ядром.
Теперь устанавливаем Qemu с поддержкой KVM, и сам KVM
USE=«kvm» emerge qemu
emerge kvm

Теперь переходим к шаманствам с виртуальной машиной.
Создаем виртуальный жесткий диск:
qemu-img create -f raw macos.disk 30G

Если собираемся запускать Qemu не от рута, необходимо дать прав другим пользователям на чтение/запись на устройство /dev/kvm:
chmod 0666 /dev/kvm

Запускаем:
kvm -boot d -hda macos.disk -m 900 -net nic,model=rtl8139 -net tap -usb -no-reboot -no-shutdown -vga std -cpu core2duo -cdrom 10.5.7.iso
-hda путь к нашему виртуальному жесткому диску
-cdrom пусть к образу
-no-shutdown -no-reboot необходимы для того чтобы в случае ошибки окно эмулятора «замораживалось» и можно было прочитать ошибку
-net nic,model=rtl8139 эмулируем сетевую карту Realtek 8139
-net tap чтобы гостевая система видела по сети хостящую необходим TAP девайс

-m 900 количество памяти отдаваемое гостевой системе
-boot d грузимся с сидирома
-usb поддержка USB
-cpu core2duo эмуляция процессора Core2Duo

Грузим диск. Размечаем жесктий диск при помощи Disk Utility (выбираем из меню сверху).

Настройка драйверов.
Перед тем как нажать кнопку Install обратите вниманине на кнопку Customize

Вещи которые нам необходимо выбрать:
x86 ACPI
Disabler
OHR
Remove TyMCE
CardBus
USB
Intel SATA/IDE
Kernels
Apple PS/2

Можно устанавливать. Ждем примерно 30 минут.
Mac OS X установлена, настраиваем.
Теперь в строке для запуска меняем -boot d на -boot c чтобы грузится с жесткого диска.
Загружаемся. Теперь надо придумать чтонибудь с сетью.
Ищем в интернете PCGenRTL8139Ethernet.kext, устанавливаем его, очень легко установить с помощью программы kextinstaller. Пока нету сети необходимые файлы передавать в систему можно через флешку например, добавляем -hdb /dev/sdb (путь к устройству флешки)
Перезагржаем гостевую ОС.
Теперь чтобы сеть в Mac OS X заработала необходимо зайти в управление сетью, выбрать Ethernet девайс, выключить его (Off), а затем включить и настроить нужный IP (например 192.168.1.1), а в хостящей системе настроить девайс tap0:
ifconfig tap0 192.168.1.2

Вот вообщем то и все.

UPD. Автор поста появился на хабре vinnishtein

Источник

Как установить macOS на виртуальной машине в Linux с помощью Sosumi

Sosumi – snap пакет, основанный на проекте macOS-Simple-KVM, который позволяет легко загрузить и установить операционную систему macOS на виртуальной машине (поставляется в комплекте с qemu-virgil, virtio-vga, паравиртуальным драйвером 3D-графики). Образ операционной системы macOS не входит в комплект, но будет загружен во время установки. Будет загружена и установлена версия – macOS Catalina.

После использования Sosumi в течение нескольких часов на ноутбуке с операционной системой Ubuntu 20.04 я могу сказать, что установка занимает много времени (почти два часа в моем случае), и работа системы macOS была немного медленной, но достаточной для использования. Таким образом проект может не подойти для тяжелых задач, но идеально подойдет для тестирования.

Snap пакет Sosumi, созданный Аланом Поупом из Canonical / Ubuntu, упрощает установку и запуск macOS на виртуальной машине в Debian / Ubuntu, Fedora и других дистрибутивах Linux (при установленном snapd – api для работы snap пакетов), поставляя практически все инструменты, которые необходимы. Исходный код пакета Sosumi доступен на GitHub . Если вы не хотите использовать snap пакет, то у вас есть альтернатива – macOS-Simple-KVM, набор инструментов для настройки виртуальной машины MacOS в QEMU (KVM).

Перед началом установки стоит отметить несколько важных вещей:

    После установки macOS на виртуальную машину общий размер папки Sosumi (

/snap/sosumi) в моей системе составляет около 31,5 ГБ, но она может увеличиться при установке дополнительных приложений на виртуальной машине macOS.

  • Процессор вашего компьютера должен поддерживать аппаратную виртуализацию. Посмотреть краткую инструкцию по поддержке KVM можно по ссылке.
  • Поддерживаются как процессоры Intel, так и AMD, но в качестве рекомендаций советуют процессоры Ivy Bridge (или более поздние) Core и Xeon или процессоры Ryzen и Threadripper (из часто задаваемых вопросов macOS-Simple-KVM )
  • Вы можете заставить виртуальную машину QEMU освободить фокус мыши, нажав CTRL+Alt+G.
  • Сценарий запуска, который содержит различные параметры (например, доступную память виртуальной машины, количество процессоров и т. д.), которые можно настроить, расположены в

    Читайте также:  Что такое windows desktop search

    Как установить macOS на виртуальную машину (QEMU) в Linux с помощью пакета Sosumi snap

    Чтобы установить Sosumi, операционная система должна иметь возможность устанавливать пакеты Snap. Snapd по умолчанию доступен в Ubuntu, а для других дистрибутивов Linux следуйте инструкциии из документации Snapcraft.

    1. Установка snap пакета Sosumi:

    2. Запустите Sosumi, набрав sosumi в терминале

    Запуск из терминала требуется только один раз; затем будет создан ярлык приложения.

    Если вы столкнулись с ошибкой, в которой сообщается, что не удалось запустить Sosumi / qemu, поскольку невозможно запустить X11, то для решения проблемы нужно добавить пользователя в группу kvm:

    3. После установки виртуальной машины и её запуска нажмите Enter для начала процесса установки macOS

    Освободить фокус мыши можно с помощью комбинации клавиш CTRL+Alt+G.

    4. Форматирование жесткого диска виртуальной машины с macOS

    Дальше в ходе запуска виртуальной машины, откроется окно macOS Utilities, в котором доступны различные инструменты.

    Открываем инструмент Disk Utility.

    В диалоговом окне «Disk Utility» на панели с левой стороны, выберите жесткий диск Apple Inc. Virtio (тот, что имеет емкость 68,72 ГБ), затем нажмите Erase, введите имя для жесткого диска (например, macOS) и оставьте остальные параметры без изменений.

    Теперь нажмите кнопку Erase, чтобы отформатировать раздел.

    5. Установка macOS на виртуальную машину

    После того как вы закроете инструмент Disk Utility, вы снова попадете в диалоговое окно macOS Utility. В окне из списка инструментов выберите Reinstall macOS. Нажмите Continue несколько раз, и далее отобразится окно, на котором вы должны выбрать жесткий диск, отформатированный в предыдущем шаге.

    Выберите жесткий диск и нажмите на Install.

    Во время установки виртуальная машина автоматически несколько перезагрузится.

    6. Запуск операционной системы macOS

    После завершения установки виртуальная машина macOS перезагрузится, в меню загрузки Clover вы увидите несколько дополнительных параметров. Используйте клавиши со стрелками влево / вправо для выбора опции Boot macOS from. например, так ( Boot macOS from macOS , где второе название macOS это имя жесткого диска, настроенного на 4 шаге).

    Для каждого запуска операционной системы macOS нужно выбирать данную опцию для загрузки.При первой загрузке в macOS вам необходимо выполнить первоначальную настройку, выбрать свое местоположение, предпочитаемый язык, при желании войти в систему с помощью Apple ID, принять условия и т. д., а также создать учетную запись компьютера (имя пользователя и пароль).

    Так как у меня отсутствует Apple ID, то я выбрал – Set Up Later.

    По окончанию настройки загрузится рабочий стол macOS Catalina.

    Видимо во время настройки допустил ошибку и не выбрал русский язык в качестве основного. Поэтому система установилась на английском языке.

    Для установки русского языка в macOS Catalina нужно открыть настройки System Preferences – Language & Region и перетянуть (либо сначала добавить нажав на плюсик и выбрав язык из выпадающего меню) выше английского языка. При выходе из настроек появится диалоговое окно с предложением перезагрузить систему для применения настроек.

    Источник

    Linux kvm mac os

    Documentation to set up a simple macOS VM in QEMU, accelerated by KVM.

    By @FoxletFox, and the help of many others. Find this useful? You can donate on Coinbase or Paypal!.

    New to macOS and KVM? Check the FAQs.

    You’ll need a Linux system with qemu (3.1 or later), python3 , pip and the KVM modules enabled. A Mac is not required. Some examples for different distributions:

    Run jumpstart.sh to download installation media for macOS (internet required). The default installation uses Catalina, but you can choose which version to get by adding either —high-sierra , —mojave , or —catalina . For example:

    Note: You can skip this if you already have BaseSystem.img downloaded. If you have BaseSystem.dmg , you will need to convert it with the dmg2img tool.

    Create an empty hard disk using qemu-img , changing the name and size to preference:

    and add it to the end of basic.sh :

    Note: If you’re running on a headless system (such as on Cloud providers), you will need -nographic and -vnc :0 -k en-us for VNC support.

    Then run basic.sh to start the machine and install macOS. Remember to partition in Disk Utility first!

    Step 2a (Virtual Machine Manager)

    1. If instead of QEMU, you’d like to import the setup into Virt-Manager for further configuration, just run sudo ./make.sh —add .
    2. After running the above command, add MyDisk.qcow2 as storage in the properties of the newly added entry for VM.

    Step 2b (Headless Systems)

    If you’re using a cloud-based/headless system, you can use headless.sh to set up a quick VNC instance. Settings are defined through variables as seen in the following example. VNC will start on port 5900 by default.

    To fine-tune the system and improve performance, look in the docs folder for more information on adding memory, setting up bridged networking, adding passthrough hardware (for GPUs), tweaking screen resolution, and enabling sound features.

    About

    Tools to set up a quick macOS VM in QEMU, accelerated by KVM.

    Источник

    Linux kvm mac os

    Copy raw contents

    App Store problems

    Do you see the «Your device or computer could not be verified» message when you try to login to the App Store? If yes, here are the steps to fix it.

    Читайте также:  Вечная подготовка автоматического восстановления windows

    Make sure that your wired ethernet connection is called «en0» (and not «en1» or something else). Use «ifconfig» command to verify this.

    If the wired ethernet connection is not called «en0», then then go to Network in System Preferences and delete all the devices, and apply the changes. Next, go to the console and type in sudo rm /Library/Preferences/SystemConfiguration/NetworkInterfaces.plist . Finally reboot, and then use the App Store without problems.

    This fix was found by Glnk2012 of https://www.tonymacx86.com/ site.

    Also tweaking the smbios.plist file can help (?).

    Change resolution in OpenCore

    Ensure that the OVMF resolution is set equal to resolution set in your OpenCore qcow2 file (default is 1024×768). This can be done via the OVMF menu, which you can reach with a press of the ESC button during the OVMF boot logo (before OpenCore boot screen appears). In the OVMF menu settings, set Device Manager -> OVMF Platform Configuration -> Change Preferred Resolution for Next Boot to the desired value (default is 1024×768). Commit changes and exit the OVMF menu.

    Note: The macOS VM’s resolution can be changed via Settings -> Displays option easily.

    GPU passthrough notes

    These steps will need to be adapted for your particular setup. A host machine with IOMMU support is required. Consult this Arch Wiki article for general-purpose guidance and details.

    I am running Ubuntu 20.04.2 LTS on Intel i5-6500 + ASUS Z170-AR motherboard + AMD RX 570 GPU (May 2021).

    Blacklist the required kernel modules.

    Find details of the PCIe devices to passthrough.

    Enable IOMMU support and configure VFIO.

    Append the given line to GRUB_CMDLINE_LINUX_DEFAULT in /etc/default/grub .

    Intel CPU Systems

    iommu=pt intel_iommu=on vfio-pci.ids=1002:67df,1002:aaf0 kvm.ignore_msrs=1 video=vesafb:off,efifb:off

    AMD CPU Systems

    Tweak module configuration a bit according to the following output (thanks to Mathias Hueber).

    Update GRUB, initramfs, and then reboot.

    In the BIOS setup, set the Primary Display to IGFX (onboard graphics).

    Verify that the IOMMU is enabled, and vfio-pci is working as expected. Verify that the expected devices are using vfio-pci as their kernel driver

    Fix permisions for the /dev/vfio/1 device (modify as needed):

    Open /etc/security/limits.conf file and add the following lines:

    Thanks to Heiko Sieger for this solution.

    Confirm the contents of boot-passthrough.sh and run it to boot macOS with GPU passthrough.

    To reuse the keyboard and mouse devices from the host, setup «Automatic login» in System Preferences in macOS and configure Synergy software.

    USB passthrough notes

    These steps will need to be adapted for your particular setup.

    Isolate the passthrough PCIe devices with vfio-pci, with the help of lspci -nnk command.

    Add 1b21:1242 to GRUB_CMDLINE_LINUX_DEFAULT in /etc/default/grub file in the required format. See GPU passthrough notes (above) for details.

    Update initramfs, and then reboot.

    Use the helper scripts to isolate the USB controller.

    Add -device vfio-pci,host=03:00.0,bus=pcie.0 \ line to boot-passthrough.sh .

    Boot the VM, and devices attached to the ASMedia USB controller should just work under macOS.

    I installed «synergy-v1.8.8-stable-MacOSX-x86_64.dmg» on the macOS guest and configured it as a client.

    For automatically starting Synergy on macOS, add Synergy to «Login Items», System Preferences -> Users & Groups -> Select your user account -> Login Items -> Add a login item

    On the Linux host machine, install «synergy-v1.8.8-stable-Linux-x86_64.deb» or newer, configure

    /.synergy.conf and run synergys command.

    The included .synergy.conf will need to be adapted according to your setup.

    Virtual Sound Device

    Warning: The OpenCore distribution that comes with OSX-KVM already has VoodooHDA OC . Do NOT mix VoodooHDA with AppleALC. You may want to consider HDA passthrough if it is practical or use HDMI audio instead

    Note: The emulated sound output can be choppy, and distorted. Use Sound Card / USB Sound Card passthrough instead.

    Note: It seems that playback of Flash videos requires an audio device to be present.

    Building QEMU from source

    Connect iPhone / iPad to macOS guest

    iDevices can be passed through in two ways: USB or USB OTA.

    VFIO USB Passthrough:

    Exposing AES-NI instructions to macOS

    Add +aes argument to the -cpu option in boot-macOS.sh file.

    Other host CPU features can be similarly exposed to the macOS guest.

    The following command can be used on macOS to verify that AES-NI instructions are exposed,

    On machines with OpenSSL installed, the following two commands can be used to check AES-NI performance,

    Exposing AVX and AVX2 instructions to macOS

    Exposing AVX and AVX2 instructions to macOS requires support for these instructions on the host CPU.

    The boot-clover.sh script already exposes AVX and AVX2 instructions to the macOS guest by default. Modify or comment out the MY_OPTIONS line in boot-clover.sh file in case you are having problems.

    To enable AVX2, do the following change,

    Clover boot menu -> Options -> Binaries patching -> Fake CPUID -> 0x0306C0 # for Haswell

    For details, see this wiki page.

    Once enabled, the following commands can be used to confirm the presence of AVX and AVX2 instructions on the macOS guest.

    Enabling Hypervisor.Framework (Nested Virtualization / Docker for Mac / Android Emulator / etc)

    Docker for Mac, the Android Emulator and other virtualization products require nested virtualization in the form of the Hypervisor Framework to work on macOS.

    Use the sysctl kern.hv_support (output 1 is good) command to check if Hypervisor is enabled within the macOS VM.

    Читайте также:  Как провести оценку системы windows 10

    If Hypervisor is not enabled, check that you have the required CPU features. Run the sysctl -a | grep machdep.cpu.features command and look for the presence of VMX flag.

    If the VMX flag is missing, use the following steps to enable it:

    Make sure that kvm_intel module is loaded properly. This is documented in our main documentation.

    Make sure the VM is booted with VMX support passed through using one of the two below strategies:

    You may add vmx,rdtscp arguments to the -cpu option in boot-macOS.sh file (easier option).

    You may add +vmx, to the front of MY_OPTIONS in the boot script while changing -cpu Penryn to -cpu Skylake-Client or any other suitable supported CPU.

    Note: Host CPU passthrough is troublesome and not generally recommended.

    Note: You may need to Reset NVRAM on the next reboot, but after that you should see a 1 when you re-check sysctl kern.hv_support .

    Using virtio-blk-pci with macOS

    Newer macOS (namely Mojave+) have support for some virtio drivers.

    This can be enabled by applying the following change to boot-macOS-NG.sh to get some performance gain.

    Permission problems with libvirt / qemu?

    Extract .pkg files

    http://mackyle.github.io/xar/ is unmaintained and may fail for many .pkg files.

    Use a modern version of 7-Zip instead.

    QEMU quits with gtk initialization failed

    Append the display=none argument to your QEMU execution script (this has already been done for boot-passthrough.sh )

    ISO/DMG ( createinstallmedia generated) install medium not detected

    Attach physical drive to QEMU VM

    Note: If using NVMe, passing the controller may be a better option then passing it as a block device

    Run ls -la /dev/disk/by-id/ to get the unique mapping for the device you want to attach to the VM (like sda , sdb , nvme0n1 , while you can attach only a partition like sda1 , this is not recommended)

    Then edit your QEMU launch script and add these lines (adapt to it your hardware), then launch the script using sudo (because you cannot write to a block device without root permissions)

    Run the Virtual Machine on Boot

    Edit your QEMU launch script and set the absolute path of OSX-KVM as the value of REPO_PATH

    Edit /etc/rc.local and add the absolute path of the script (with or without sudo depending on your needs) to the bottom of the script.

    Setup SSH for internal remote access

    Presuming your network interface has a statically defined internal IP (on Ubuntu).

    Consider using CMMChris’s RadeonBoost.kext for the RX480, RX580, RX590 and Radeon VII GPUs.

    USB passthrough notes

    USB 3.0 flash drive

    The following USB configuration works for usb passthrough of a USB 3.0 flash drive to Fedora 25 guest.

    The following USB configuration works for usb passthrough of a Moto G3 phone to Fedora 25 guest.

    The following USB configuration works for usb passthrough of a CoolerMaster keyboard to macOS Sierra guest!

    Virtual USB disk

    The following USB configuration works for attaching a virtual USB disk to macOS Sierra guest. Use «qemu-img» to create «disk.raw» virtual disk.

    However USB passthrough of EHCI, and XHCI (USB 3.0) devices does not work with macOS Sierra. See https://bugs.launchpad.net/qemu/+bug/1509336 for confirmation. According to this bug report, USB passthrough does not work with versions >= Mac OS X El Capitan guests.

    It seems that this problem can be fixed by using OVMF + Clover.

    Update: OVMF + Clover doesn’t help. It seems that macOS is missing the required drivers for the EHCI, and XHCI controllers that are exposed by QEMU.

    Generate macOS Mojave / Catalina installation ISO.

    This step currently needs to be run on an existing macOS system.

    Tweaks for macOS

    Disable Energy Saver in System Preferences .

    Disable Screen Saver in System Preferences -> Desktop & Screen Saver .

    Turn off indexing using the following command.

    Enable Remote Login (aka SSH) via System Preferences -> Sharing .

    Snapshot Debugging Tips

    Get savevm to work:

    Ensure that you have plenty of free space in /var/tmp and / .

    To use a separate storage location for storing snapshots, use the following trick (from zimbatm ):

    ‘Fix’ weird boot problems

    ‘Fix’ time drift problems

    Run the following command periodically from root’s crontab:

    Pass through all CPU cores / threads

    macOS requires a core count that is a power of 2, but some modern CPUs have odd counts — like 6 cores and 12 threads.

    So how can we harness the entire CPU in the VM?

    There are strategies that mix smp/sockets/cores/threads/maxcpu arguments and use odd socket counts to arrive at even core counts, and even let you specify that some of the cores are hyperthreaded.

    Specifically for the case of an Intel i7 processor with 6 cores and 12 total threads, altering the boot script to contain these variables and the following modified SMP line results in a full CPU core/thread pass through:

    The -smp line should read something like the following:

    Trouble with iMessage?

    Enable rc.local functionality on moden Ubuntu versions

    Create /etc/rc.local file with the following content, if it doesn’t exist:

    Make this file executable, if required:

    Create /etc/systemd/system/rc-local.service with the following content, if it doesn’t exist:

    Enable rc.local systemd service:

    These notes are borrowed from various multiple internet resources.

    Источник

  • Оцените статью