Apple m1 virtualbox linux

Developing on Apple M1 Silicon with Virtual Environments

Docker containers all the way down

In my article Creating Repeatable Development Environments, I showed how I use Vagrant as an orchestrator and VirtualBox as a provider of virtual machines for creating consistent development environments for my students and development teams. That worked really well until Apple released their new 2020 Macs with Apple M1 Silicon chips based on the ARM architecture. I had selected VirtualBox because it was free and supports Mac, Linux, and Windows, but it only runs on Intel computers (x86_64 architecture) and Apple Silicon is ARM base (aarch64 architecture). As it turns out, 8 of my students showed up for the 2021 spring semester with Apple M1 Macs which meant that all of my labs based on VirtualBox were not going to work for them. I need another solution and I needed it fast.

Docker on Apple Silicon

I had heard that Docker had released a tech preview of Docker Desktop for Mac that runs on Apple Silicon. I also remembered that Vagrant supports Docker as a provider. This means that Vagrant can control the provisioning of Docker containers just like it controls VirtualBox for provisioning virtual machines. This is somewhat of a unique use case for Docker because the intent of Docker is to provide a consistent, immutable runtime environment; not to be treated like a virtual machine. As with all technology, there are always use cases beyond the original intent and I was about to learn if this use case was viable.

The concept of using Docker as a development environment is not new. In fact, if you use Visual Studio Code, there is an extension called Remote Containers that allows you to develop in containers. I plan to cover that in a future article. The difference here is that normally you would use the docker exec command to establish a shell inside the container but I needed these containers to behave exactly like a virtual machine (VM) because I didn’t want students or developers with Apple M1 Macs to have a different experience than those on an Intel Mac or Windows computer. That means I had to get ssh to work with my container because that is how vagrant expects to establish a shell inside of the VM.

Coercing a Container to behave like a VM

Everyone will tell you to never install an ssh daemon ( sshd ) inside of a Docker container. In fact, I am one of those people. Normally, you should not do this when using containers for their intended purpose of providing immutable runtimes. To do so would make them mutable and less secure. But this is different. These are development containers.

There was also another problem to overcome. Docker containers don’t normally run a linux init system like a virtual machines does because containers are intended to only run one process, but many of the tools I needed to install expected an init system. Since I was using Ubuntu, I need to get systemd (Ubuntu’s init system) running as the first process (PID 1) in order to get the containers to truly act like a virtual machine. Easier said than done.

Docker makes it very hard to use systemd inside a container but lucky fo me, Matthew Warman had already figured this part out for CentOS and was extremely helpful in getting this to work for me with Ubuntu. With his guidance, I was able to build an Ubuntu 20.04 Docker image that was tailored for my purposes. You can use this image as a vagrant provider to start your own Ubuntu Docker containers that behave like virtual machines for doing development work, compete with an init system.

Building a Multi-Architecture Docker Image

The last hurtle was to build a Docker image that would run on both Intel and ARM based computers so that my students and development teams could use it on either platform. It was surprisingly easier than I thought. I was even able to build a Docker image on my Intel Mac that would run on both Intel and an Apple Silicon Mac by using an experimental Docker feature called buildx .

These are the commands I used to build my vagrant provider Docker image for both amd64 and arm64 architecture.

First you must prepare a buildx builder to use:

Читайте также:  What is the iphone 6s battery

This creates a buildx container to do the work for you. Then when you build your image, you must specify the platforms that you want build and push them to docker hub (or other registry) to get an image:

The command above uses QEMU to build a multi-platform image that will work on both Intel ( amd64 ) and ARM ( arm64 ), and push it to my docker hub account. If you need to support more platforms you can just add them to the —platform parameter separated by a comma.

Final Solution

You can find the final Docker image here on Docker Hub: rofrano/vagrant-provider. If you plan to use it with Vagrant, there is no need to pull it down from Docker Hub because that will happen automatically when vagrant processes your Vagrantfile .

Here is a sample multi-provider Vagrantfile that can use either VirtualBox or Docker as a provider with vagrant:

To use vagrant with Docker instead of VirtualBox, just specify the —provider parameter with docker as the provider:

This will bring up a container that behaves like a virtual machine on Intel or ARM computers. You might have noticed that I’ve added a provision block for Docker in the Vagrantfile . Yes that’s right, we are running Docker inside of our Docker container so that students and developers can work with Docker while inside the virtual environment just like we do with real VMs. In this example we are running PostgreSQL in a Docker container for development work.

To get inside of this development environment you use the same vagrant command as when developing with a VM:

This will ssh into the Docker contain just as if it were a virtual machine.

Conclusion

Using Docker as a provider for Vagrant has allowed me to create consistent developer environments for my students and development teams regardless of whether they have an Intel computer or an ARM based computer like the new Apple M1 Silicon Macs. Getting a base Docker image to use systemd as its entry point allows the container to behave much like a virtual machine. We even have Docker running inside the container so that we can leverage it for databases and other software during development. Other solutions allow for developing in containers without vagrant, but we’ll leave that for future article.

Источник

Question: Q: Virtualbox Mac m1

I bought a m1 macbook pro, but im trying to install virtual box, but im getting an error about system:aceleration.

I have searched about it and m1 was not compatible with virtualbox but that forum i saw talked about that a year ago.

I really wanna know if there is any update about that theme.

MacBook Pro 13″, macOS 11.6

Posted on Oct 25, 2021 2:27 AM

Currently, Oracle VM VirtualBox runs on the following host OSes:

  • Windows hosts (64-bit):
    • Windows 8.1
    • Windows 10 RTM (1507 / 2015 LTSB) build 10240
    • Windows 10 Anniversary Update (1607 / 2016 LTSB) build 14393
    • Windows 10 Fall Creators Update (1709) build 16299
    • Windows 10 April 2018 Update (1803) build 17134
    • Windows 10 October 2018 Update (1809 / 2019 LTSC) build 17763
    • Windows 10 May 2019 Update (19H1 / 1903) build 18362
    • Windows 10 November 2019 Update (19H2 / 1909) build 18363
    • Windows Server 2012
    • Windows Server 2012 R2
    • Windows Server 2016
    • Windows Server 2019
  • Mac OS X hosts (64-bit):
    • 10.13 (High Sierra)
    • 10.14 (Mojave)
    • 10.15 (Catalina)

Plus >> VirtualBox is a general-purpose full virtualizer for x86 hardware, which the M1 or M1X are not part of this

Posted on Oct 25, 2021 2:34 AM

All replies

Loading page content

Page content loaded

Currently, Oracle VM VirtualBox runs on the following host OSes:

  • Windows hosts (64-bit):
    • Windows 8.1
    • Windows 10 RTM (1507 / 2015 LTSB) build 10240
    • Windows 10 Anniversary Update (1607 / 2016 LTSB) build 14393
    • Windows 10 Fall Creators Update (1709) build 16299
    • Windows 10 April 2018 Update (1803) build 17134
    • Windows 10 October 2018 Update (1809 / 2019 LTSC) build 17763
    • Windows 10 May 2019 Update (19H1 / 1903) build 18362
    • Windows 10 November 2019 Update (19H2 / 1909) build 18363
    • Windows Server 2012
    • Windows Server 2012 R2
    • Windows Server 2016
    • Windows Server 2019
  • Mac OS X hosts (64-bit):
    • 10.13 (High Sierra)
    • 10.14 (Mojave)
    • 10.15 (Catalina)

Plus >> VirtualBox is a general-purpose full virtualizer for x86 hardware, which the M1 or M1X are not part of this

Oct 25, 2021 2:34 AM

Oh ok thanks! but is there any information for when it will be realesed to big sur?

Oct 25, 2021 2:33 AM

Oracle has not released a version of VirtualBox compatible with M1 devices. Parallels Desktop 17 (subscription) is compatible with Big Sur on M1 devices, but the guest operating system must be compiled for Apple Silicon ARM, as X86_64 operating systems are not supported.

Читайте также:  Как восстановить аккаунт айфона если нет доступа

Oct 25, 2021 2:34 AM

That Question is best asked to the Developer of this software.

After all it is their Software.

Use wrote » I have searched about it and m1 was not compatible with virtualbox » . It really should be mentioned — virtualbox is not compatible with M1 or M1X CPU equipped Apple Computer.

It is the Developers responsibility to make their Software adhere to Apple Computers , CPU and Operating Systems

Oct 25, 2021 2:39 AM

also if it’s windows you wish to install in virtualbox then you can’t run the intel (x86) version even if virtualbox support m1(arm) cpus

Oct 25, 2021 4:07 AM

So tired of being «upgraded» out of a functioning machine.

Apple won’t provide OS upgrades for our older x86 iMacs (which still run great) and the replacement iMacs won’t run several key applications for development like VirtualBox and Vagrant. I thought «Rosetta» was supposed provide x86 emulation to bridge the gap between x86 apps and Apple Silicon but apparently not. Also they got rid of bootcamp and you can’t boot from a USB stick either. So I can’t boot into an ARM based Linux Distro either.

We have Parallels on a couple of Macs, but it’s soooo bloated that you can’t get decent performance while it’s running so I don’t see it as a viable option.

These new Macs also won’t talk to our Apple Server to do network user authentication when Filevault is turned on. So lovely.

Sorry for the rant. Maybe I’m alone in my thinking that when you stop supporting product X and replace it with an improved product Y, one would expect that the new version will still do all the things the previous version did AND MORE.

And it would have been nice for the folks at Apple to have told me about these issues when I asked them BEFORE we decided to purchase 15 of these not-quite-ready-for-prime-time M1 iMacs. But all they could say is «we don’t know». So I did a demo and VirtualBox installed on the new M1 and it ran just fine, no grayed out icon with a slash through it, so I thought it would work. I just didn’t have a virtual machine to start at the time. It wasn’t until we got the first shipment of iMacs that I actually tried to start a VM and got a kernel error that I realized I was hosed.

My bad for not specifically Googling «SoftwareX won’t run on Apple Silicon» for each piece of software we use.

Источник

Как установить Ubuntu на Apple M1 и ничего не сломать

Corellium ранее работала над проектом Project Sandcastle, который позволяет установить ОС Android на iPhone 7 благодаря уязвимости checkm8. Установкой Android на iPhone не занимались со времени iDroid Project и iPhone 3G. Как и iDroid Project, Project Sandcastle не предоставляет ОС для повседневного использования, это скорее масштабный Proof-of-Concept с открытым исходным кодом.

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

В чем сложность

Наиболее подробно — в соответствующей статье в блоге Corellium.

Ни для кого не секрет, что Apple отступается от принятых стандартов и часто использует собственные решения. Для начала отметим, что macOS загружается несколько иначе, чем операционные системы семейств Windows и *nix. В качестве загрузчика в «яблочных» устройствах используется iBoot. Он загружает ядро в формате Mach-O, которое может быть сжато, подписано и лежать в контейнере IMG4.

Более сложные вещи начинаются, когда появляется необходимость запустить остальные ядра процессора. В обычных ARM64-процессорах это производится через интерфейс Power State Coordination Interface (PSCI). Но в M1 другие ядра запускаются со смещения, которое указано в соответствующем Memory-mapped I/O (MMIO) регистре.

Но даже это еще не все. Apple создали свой собственный контроллер прерываний, который не соответствует ни одному стандарту ARM Generic Interrupt Controller (GIC). Также прерывания, генерируемые таймером, используют специальный тип запросов FIQ (Fast Interrupt Request) вместо IRQ, что пока не поддерживается ядром Linux.

Для взаимодействия процессорных ядер между собой используются специальные прерывания — Inter-Processor Interrupt (IPI), которые в M1 формируются также с помощью FIQ. Таким образом, поддержка FIQ — один из наиболее важных моментов в этом порте.

Ядро Linux на M1 (источник twitter.com)

Сотрудникам Corellium пришлось разработать собственный драйвер для обработки прерываний через FIQ, написать «обертку», которая позволила бы запустить все ядра, и решить еще несколько аппаратных проблем. Только после этого они смогли запустить ядро Ubuntu.

Читайте также:  Конвертер pdf для айфона

Впрочем, запуск ядра — это только начало. Для успешной эксплуатации необходимо подключить устройства ввода, такие как клавиатура и мышь. Есть три способа: использовать USB-хост в чипе M1 (для ThunderBolt/USB Type-C), использовать xHСI-хост (для USB Type-A) или воспользоваться Bluetooth.

Bluetooth работает на нестандартном PCIe-подобном протоколе, поэтому разработка собственного модуля ядра для неизвестного протокола могла затянуться. В Corellium приняли решение настроить USB, и через пару дней работы им удалось подключить устройства ввода.

На момент написания статьи уже доступен Proof-of-Concept, который можно попробовать самостоятельно. Учтите, что все дальнейшие действия вы можете делать исключительно на свой страх и риск.

Установка Ubuntu

Для начала использования Ubuntu нам потребуется следующее:

  • Mac с процессором Apple M1 (поддерживаются Mac Mini, Macbook Pro и Macbook Air);
  • флешка с разъемом USB Type-C объемом от 16 ГБ;
  • USB-клавиатура и USB-мышь.

В качестве флешки я использовал Kingston DataTraveler microDuo 3C объемом 32 ГБ, поддерживающую USB Type-A и USB Type-C. Инструкция Corellium настаивает на использовании Type-C флешки, так как загрузка с Type-A не поддерживается на момент написания данной статьи. Мышь и клавиатуру я подключал по USB Type-A.

Есть и менее очевидные требования. Во-первых, на Mac Mini должна быть установлена macOS 11.2 или выше. В старых версиях ОС в утилите kmutil отсутствует команда configure-boot, необходимая для корректной «подмены» ядра.

Также необходимо «отвязать» Mac от Find My Mac. Наличие «привязки» не позволяет отключить системы безопасности в полной мере и выполнить все необходимые команды.

В первую очередь подготовим образ для флешки. Скачиваем, а затем распаковываем архив. Подготовку следует выполнять в терминале Mac, на котором планируем запустить Ubuntu.

Далее разворачиваем образ на флешку:

Обратите внимание, что необходимо указать именно флешку, а не раздел на ней. Например, /dev/rdisk6. Далее копируем драйвера на Wi-Fi:

Если вы используете проводное подключение к Интернету, то флешку можно подготовить на компьютере под управлением ОС Linux.

Далее подключаем флешку в USB Type-C порт и перезагружаемся в Recovery OS, известную как 1TR (the One True Recovery), и открываем терминал. На новых Mac это происходит следующим образом:

  1. Выключаем Mac;
  2. Удерживаем кнопку включения до появления текста «Загрузка параметров запуска»;
  3. Выбираем опцию «Параметры» и нажимаем «Продолжить»;
  4. В верхнем меню открываем «Утилиты» — «Терминал».

Обратите внимание, что Recovery при запуске не должен просить ввести пароль от ОС или от Apple ID. Если он все же просит, то необходимо отключить Find My Mac в настройках macOS.

Устанавливаем ядро Ubuntu:

Данный скрипт проверяет политики загрузки (BootPolicy) и отключает системы проверки целостности macOS, если это необходимо. После этого скрипт загружает ядро Linux в формате Mach-O в корень системного диска и настраивает iBoot на ядро Linux.

В процессе выполнения скрипта будет запрос пароля для получения прав суперпользователя macOS. Выполняемые команды также предупредят вас о том, что выполняемые действия значительно снижают безопасность Mac. Но если вы хотите запустить Ubuntu, то придется принять это как должное.

После завершения скрипта можно перезагрузить Mac, далее начнется загрузка Ubuntu 20.04.

Опыт использования

Первый запуск Ubuntu будет не очень быстрым. В логах загрузки «упадет» четыре-пять сервисов и еще шесть «подвиснут». Ubuntu загружается относительно долго: несколько минут. Более того, первое время отзывчивость ОС будет очень низкой. Запуск новых приложений, даже без графической оболочки, может занимать минуты. Эта проблема самоустраняется вскоре после загрузки.

Нетрудно заметить, что образ сделан на основе Ubuntu для Raspberry Pi. Поэтому в системе пользователи root и pi имеют пароль raspberry. К сожалению, сделать красивый и показательный скриншот с выводом screenfetch не получается. ОС не определяет модель процессора, поэтому в выводе лишь безликое Unknown.

То, что это образ ОС для RPi, будет заметно при попытке установить ПО из пакетного менеджера. Он попытается установить не только требуемый администратором софт, но и обновление ОС с созданием initramfs для «малинки». Подобные действия приведут к появлению ошибок в логах, несмотря на успешность установки запрошенного ПО.

Как и ожидалось, в ОС присутствует минимально необходимый набор драйверов. Звуковая карта, модуль Bluetooth и графический ускоритель не поддерживаются. Большинство системных утилит, таких как lspci, lsusb и lshw, выдают очень скудную информацию о железе.

Несмотря на множество ограничений, я решил провести тест sysbench.

Устройство Количество вычислений в секунду
Mac Mini (Ubuntu 20.10) 838
Lenovo ThinkPad E14 (Ubuntu 20.04) 483

Хотя данный тест нельзя считать идеальным и показательным, восьмиядерный Apple M1 в два раза превосходит восьмиядерный Intel Core i5-1045U. К сожалению, мне не удалось запустить sysbench на macOS.

Заключение

Установка альтернативных операционных систем на Mac — это всегда увлекательный с технической точки зрения процесс. Новые процессоры Apple M1 стали отличным вызовом для энтузиастов.

А вам приходилось использовать Windows или Linux на Mac?

Источник

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