Linux qemu raspberry pi

Raspbian и QEMU


Всем здравствуйте! Подарили мне недавно raspberry pi, и решил я его поиспользовать. Но, как это обычно бывает, дома времени для этого очень мало, а на работе подключить его не к чему. Поэтому решил поставить себе raspbian на виртуальную машину, для того чтобы использовать на работе. Кому интересно как я это делал прошу присоединиться
Для достижения своей цели я использовал множества статей и сообщений на форумах в различных уголках интернета, ссылки на те статьи, которые вспомню приведу в конце своего повествования. Так же, прошу не пинать за ошибки и стиль повествования, а указывать все недочеты в комментариях, т.к. это первая моя публикация на хабре в частности, и где-либо в общем.

Итак начнём! Чтобы заставить работать raspbian на QEMU нам для начала понадобится ядро линукса под arm-платформу. Существуют уже готовые ядра, но для общего развития я решил попробовать собрать сам.
Для этого на понадобится машина с операционной системой из семейства Linux (на самом деле я просто не знаю можно ли это сделать на других операционках). Я использовал одну из разновидностей Debian, а именно Kali Linux, т.к. он был в тот момент под рукой.
1. С начала скачаем пакеты, которые нам понадобятся для сборки ядра, выполнив следующую команду:

Если вы используете 32х разрядную систему, то нужно будет еще установить х86 библиотеки:

2. Так же нужно установить кросс-компилятор, для этого нужно добавить репозиторий:
deb www.emdebian.org/debian unstable main
И выполнить следующие комманды:

И для совместимости создать символьную метку на компилятор:

3. Следующим шагом нужно выкачать исходники ядра и патч для поддержки ядром архитектуры ARM11 и применить этот патч к исходникам. Для этого выполним следующие команды:

4. Дальше нам нужно будет сконфигурировать ядро под нужды Raspbian.
Для этого выполним следующие комманды:

И в появившемся меню выбираем следующие настройки.
ВАЖНО. При выборе опции, если у Вас напротив опции появилась , нажмите еще раз пробел, чтобы появилась .
а) Указываем кросс-компилятор:
General Setup -> Cross-compiler tool prefix
arm-linux-gnueabihf-
ВАЖНО!Не забудьте указать ‘-‘ в конце

б)Настрйки CPU:
System Type->
[*] Support ARMV6 processor
[*] ARM errata: Invalidation of the Instruction Cache Operation fail
[*] ARM errata: Possible cache data corruption with hit-under-miss enabled

в) Включение поддержки для hard-float бинарников:
Floating point emulation ->
[*] VFP-format floating point maths

г) Включение EABI для ARM:
Kernel Features ->
[*] Use the ARM EABI to compile the kernel
[*] Allow old ABI binaries to run with this kernel

д) Включение поддержки дисков QEMU:
Bus Support->
[*] PCI Support
Device Drivers ->
SCSI Device Support
[*] SCSI Device Support
[*] SCSI Disk Support
[*] SCSI CDROM Support
[*] SCSI low-level drivers ->
[*] SYM53C8XX Version 2 SCSI support

е) Включение devtmpfs:
Device Drivers ->
Generic Driver Options ->
[*] Maintain a devtmpfs filesystem to mount at /dev
[*] Automount devtmpfs at /dev, after the kernel mounted the root

Читайте также:  Пароль администратора имя mac os

ё) Включение важных файловых систем:
File Systems ->
Ext3 journaling file system support
The Extended 4 (ext4) filesystem
DOS/FAT/NT Filesystems ->
VFAT (Windows-95) fs support

ж) Включение tmpfs:
File Systems ->
Pseudo filesystems->
[*] Tmpfs Virtual Memory file system support (former shm fs)

з) Включение интерфейса сообщений:
Device Drivers ->
Input device support ->
[*] Event interface

и)(по желанию) Включение /proc/config.gz
General Setup ->
[*] Kernel .config support
[*] Enable access to .config through /proc/config.gz

к)(по желанию) Использовать более крупных шрифтов и включение логотипа:
Device Drivers ->
Graphics Support ->
[*] Bootup logo
Console display driver support ->
[*] Select compiled-in fonts
[*] VGA 8×16 font

Сохраняем и выходим.

Далее перходим к самой компиляции ядра. Для этого выполним следующие команды:

Ну и я сразу его копирую в корень, т.к. потом буду прописывать параметры от корня.

На этом сборка ядра для QEMU закончена. Если Вам не хочется повторять всё это, то в конце я выложу ссылки на все файлы.

Следующий этап — это установка QEMU.
Для пользователей ОС Windows всё очень просто. Идем на QEMU ON WINDOWS и качаем архив с последней версией QEMU.
ВАЖНО. Версия QEMU должна быть не ниже 1.5.0, т.к. в ней исправлен критичный баг для эмуляции Raspbian
Для пользователей Windows подробно описывать процесс запуска Raspbian не буду, т.к. он очень похож с процессом запуска на ОС семейства Linux. Если будут вопросы, встретимся в коментариях.

Итак, для начала копируем себе исходники QEMU:

Так же установим зависимости:

Переходим к настройке и установке:

Если у вас появиться сообщение Error: DTC not present, то выполните следующую команду:

Теперь у Вас есть QEMU и ядро, осталось скачать образ Raspbian и провести «настроечную» загрузку.

Для первого запуска Raspbian нужно выполнить следующую комманду:

После загрузки вы увидите приглашение bash:

Закоментируйте строку, нажмите [Ctrl]+[x], сохраните и выйдете

Так же выполните:

И введите:
KERNEL==»sda»,SYMLINK+=»mmcblk0″
KERNEL==»sda?»,SYMLINK+=»mmcblk0p%n»,

Сохраните, закройте и выключите виртуалку:

Теперь всё готово для запуска виртуального Raspbian. Выполните команду:

И если всё прошло удачно, то вы увидите стандартное приглашение Raspbian:

Так же может быть полезным изменение размера диска. Для этого на хосте выполните:

Затем загрузите Raspbian и выполните следующее:

Нажмите [p] и запомните значение Start для sda2.
Затем нажмите [d] и удалите 2 раздел.
Затем нажмите [n] — для создания нового раздела.
Нажмите [p], чтобы указать что он будет primary.
Укажите, что он будет вторым, нажав [2].
Укажите First sector, равный Start.
Для Last Sector просто нажмите [Enter], чтобы использовалось всё свободное место.
Нажмите [w], чтобы выйти, сохранив изменения в таблицу разделов.
Перезагрузитесь, выполнив комманду:

После перезагрузки выполните комманду:

На этом всё. Выполнив комманду

Вы увидите новый размер вашего диска.

На этом, наверное всё что я хотел сказать. Пожалуйста, сильно не пинайте за стиль изложения, а лучше указываёте на конкретные ошибки в комментариях.

Источник

Using QEMU to emulate a Raspberry Pi

If you’re building software for the Raspberry Pi (like I sometimes do), it can be a pain to have to constantly keep Pi hardware around and spotting Pi-specific problems can be difficult until too late.

One option (and the one I most like) is to emulate a Raspberry Pi locally before ever hitting the device. Why?

  • Works anywhere you can install QEMU
  • No hardware setup needed (no more scratching around for a power supply)
  • Faster feedback cycle compared to hardware
  • I can use Pi software (like Raspbian) in a virtual context
  • I can prep my «virtual Pi» with all the tools I need regardless of my physical Pi’s use case
Читайте также:  Gigabyte raid driver windows

Given I’m next-to-useless at Python, that last one is pretty important as it allows me to install every Python debugging and testing tool known to man on my virtual Pi while my end-product hardware stays comparatively pristine.

Getting started

First, you’ll need a few prerequisites:

QEMU (more specifically qemu-system-arm )

You can find all the packages for your chosen platform on the QEMU website and is installable across Linux, macOS and even Windows.

Raspbian

Simply download the copy of Raspbian you need from the official site. Personally, I used the 2017-08-16 version of Raspbian Lite, since I don’t need an X server.

Kernel

Since the standard RPi kernel can’t be booted out of the box on QEMU, we’ll need a custom kernel. We’ll cover that in the next step.

Preparing

Get your kernel

First, you’ll need to download a kernel. Personally, I (along with most people) use the dhruvvyas90/qemu-rpi-kernel repository’s kernels. Either clone the repo:

or download a kernel directly:

For the rest of these steps I’m going to be using the kernel-qemu-4.4.34-jessie kernel, so update the commands as needed if you’re using another version.

Filesystem image

This step is optional, but recommended

When you download the Raspbian image it will be in the raw format, a plain disk image (generally with an .img extension).

A more efficient option is to convert this to a qcow2 image first. Use the qemu-img command to do this:

Now we can also easily expand the image:

You can check on your image using the qemu-img info command

Starting

You’ve got everything you need now: a kernel, a disk image, and QEMU!

Actually running the virtual Pi is done using the qemu-system-arm command and it can be quite complicated. The full command is this (don’t worry it’s explained below):

  • sudo qemu-system-arm : you need to run QEMU as root
  • -kernel : this is the path to the QEMU kernel we downloaded in the previous step
  • -append : here we are providing the boot args direct to the kernel, telling it where to find it’s root filesytem and what type it is
  • -hda : here we’re attaching the disk image itself
  • -cpu / -m : this sets the CPU type and RAM limit to match a Raspberry Pi
  • -M : this sets the machine we are emulating. versatilepb is the ‘ARM Versatile/PB’ machine
  • -no-reboot : just tells QEMU to exit rather than rebooting the machine
  • -serial : redirects the machine’s virtual serial port to our host’s stdio
  • -net : this configures the machine’s network stack to attach a NIC, use the user-mode stack, connect the host’s vnet0 TAP device to the new NIC and don’t use config scripts.

If it’s all gone well, you should now have a QEMU window pop up and you should see the familiar Raspberry Pi boot screen show up.

Now, go get yourself a drink to celebrate, because it might take a little while.

Networking

Now, that’s all well and good, but without networking, we may as well be back on hardware. When the machine started, it will have attached a NIC and connected it to the host’s vnet0 TAP device. If we configure that device with an IP and add it to a bridge on our host, you should be able to reliably access it like any other virtual machine.

Читайте также:  Local bridge windows 10 что это

(on host) Find a bridge and address

This will vary by host, but on my Fedora machine, for example, there is a pre-configured virbr0 bridge interface with an address in the 192.168.122.0/24 space:

I’m going to use this bridge and just pick a static address for my Pi: 192.168.122.200

Reusing an existing (pre-configured) bridge means you won’t need to sort your own routing

(in guest) Configure interface

NOTE: I’m assuming Stretch here.

Open /etc/dhcpcd.conf in your new virtual Pi and configure the eth0 interface with a static address in your bridge’s subnet. For example, for my bridge:

You may need to reboot for this to take effect

(in host) Add TAP to bridge

Finally, add the machine’s TAP interface to your chosen bridge with the brctl command:

Now, on your host, you should be able to ping 192.168.122.200 (or your Pi’s address).

Set up SSH

Now, in your machine, you can run sudo raspi-config and enable the SSH server (in the «Interfacing Options» menu at time of writing).

Make sure you change the password from default while you’re there!

Finally, on your host, run ssh-copy-id [email protected] to copy your SSH key into the Pi’s pi user and you can now SSH directly into your Pi without a password prompt.

Источник

stefanozanella / cnxsoft.md

Booting with CNXSoft image

Running with custom Raspbian installation

Prepare installer image

VM doesn’t boot for lack of init script.

Running with offical Raspberry Pi Raspbian image

Install guest machine

Installation options: (copy params from post and adapt) /dev/vda1 500 /boot /dev/vda2 19979 os root 17960 /root ext4 swap 2016 — swap (copy default tasks from post)

Expand official image and convert to qcow

Launch Raspberry Pi Emulation

  • change_locale -> en_GB.UTF-8
  • change_timezone -> Europe/Rome
  • ssh -> Enable
  • boot_behaviour -> Boot straight to desktop? Yes

Setup bridge on host VM:

Add raspberry interface to bridge:

Configure address on RPi interface:

Update packages and install puppet:

Resize RPi Root Partition

Reboot. (I needed to do so, even after running partprobe ).

Booting with UBoot for Raspberry

Same failure as with installer.

This comment has been minimized.

Copy link Quote reply

Darkn3ssF4lls commented Feb 19, 2020

This is a great writeup you have here, I am just wondering does it not just work with virsh-install and defining the .iso file from the Rasberry Pi Foundation ?

This comment has been minimized.

Copy link Quote reply

hydrian commented Jul 16, 2020 •

@Darkn3ssF4lls I agree. Downloading a binary tarball on dropbox with a date that goes back to 2012 doesn’t promote trust.

This comment has been minimized.

Copy link Quote reply

Marietto2008 commented Jun 5, 2021

I don’t like these parameters :

m 256 -M versatilepb

I tried to do something like this :

virt-install
—name pi
—machine raspi3
—cpu arm1176
—memory 1024
—import \ —disk /root/Desktop/zi/Work/Android/Raspy/Debian/2019-09-26-raspbian-buster-lite.img,format=raw,bus=virtio
—network user,model=virtio
—video vga
—graphics spice
—rng device=/dev/urandom,model=virtio
—boot ‘uefi=RPI_EFI.fd,dtb=bcm2710-rpi-3-b-plus.dtb,kernel=kernel8.img,kernel_args=root=/dev/vda2 rootwait panic=1 dwc_otg.fiq_fsm_enable=0’
—events on_reboot=destroy

But I get this error :

ERROR internal error: Unexpected enum value 0 for virDomainDeviceAddressType

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

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