Linux for the arm processor

4 Fine Linux ARM Distros

The ARM platform is exploding like a mad wet cat out of the bath. Here are four good distros cram-full of ARM fun.

Linux has had ARM support since forever, but it’s been bumpy. There are hundreds of vendors of ARM devices (see Tiny Pluggable Linux ARM Computers Are Red-Hot for a sampling), all shoving their own personal hacked code out the door as fast as possible. This made Linux support complicated and unwieldy, to the point that Linus Torvalds threatened to stop accepting ARM changes in the mainline Linux kernel.

So, in classic Linux fashion, vendors and developers banded together and coordinated and consolidated their efforts, formed the Linaro non-profit engineering organization, and performed a sizable cleanup of redundant and bad code. Jonathan Corbet, editor of Linux Weekly News, predicts that “ARM will take its place as one of the primary Linux architectures” in 2012. This seems a safe prediction as ARM-based mobile devices are going to continue to sell like ice water in hell.

Android is also expected to harmonize, over time, with the mainline Linux kernel. So this confluence of ARM events means that we who like to play with stuff will have a little easier time of it. Me, I dream of embedded and mobile devices being as friendly to experimentation as the x86 platform. Don’t laugh, it could happen. So which Linux is best for ARM? Why, lots of them.

There are a lot of different ARM processors, so this guide should help you sort them out. Wikipedia has an invaluable table that lists all the ARM microprocessor cores, so when you see terms like ARMv5TE or ARM9TDMI or Cortex-something, consult this table to know what the heck these are.

BeagleBoard

Arch Linux ARM

Arch Linux ARM is based on the excellent Arch Linux distribution. It’s an active, fast-moving rolling release that is compatible with Arch, and in fine Arch fashion has good documentation. It’s a complete Linux distribution with thousands of packages. This is the one I recommend to ARM noobs; it’s lightweight, efficient, and the community support is quite good.

Arch Linux ARM runs on any processor that supports ARMv5TE or higher, which includes fun cheap boards and gadgets like Pogoplug, SheevaPlug, TonidoPlug, Raspberry Pi, BeagleBoard, CuBox, PandaBoard, and TrimSlice. Adventurous users have installed it on various smartphones.

Ubuntu ARM

Ubuntu is everywhere, including ARM devices. Like Arch ARM, Ubuntu ARM is a complete distribution with thousands of packages, both desktop and server. For example, you can install a complete LAMP stack and Drupal on a PandaBoard.

Читайте также:  Android screen share linux

UNR, the Ubuntu Netbook Remix made an early attempt at an Ubuntu ARM netbook spin. One of its most promising features, in my un-humble opinion, was using the Enlightenment Foundation Libraries to power a beautiful 2D user interface with similar features to its 3D desktop. This made it possible to have a rich environment on ARM, which is plagued with licensing hassles for graphics hardware.

But UNR went away with Ubuntu 11.04. Or rather, it was “unified” with Ubuntu Desktop, and the UNR ARM port went away. The current Ubuntu ARM port supports ARMv7 and up, and targets the Thumb-2 instruction set, which is the modern 32-bit ARM instruction set. So this targets the newer higher-powered devices that support good video, audio, networking, and decent processing power for running applications.

Debian ARM

Debian has always supported more hardware architectures than any other Linux distribution, including ARM. The nomenclature is a bit confusing until you understand that it’s specific to each ARM version. The first Debian ARM port was arm-linux-gnu, which supported ARMv3. arm-linux-gnu packages are in the arm section. The last arm packages appeared in Lenny. These were replaced with arm-linux-gnueabi in Lenny in the armel section, supporting ARMv4t and up. armel has been replaced by the arm-linux-gnueabihf port, armhf in Wheezy. armhf is ARMv7 and up, with the Thumb-2 instruction set.

The Debian documentation is rather shy of installation and hacking how-to’s. This page in the Bodhi Linux forums, Debian ARM on Android tablets is a good starting point.

Fedora ARM

Fedora’s ARM port has lagged behind Debian, Ubuntu, and Arch ARM, though it found new energy for Fedora 17, and it should be pretty solid for Fedora 18.

The interesting bit is a proposal to promote it to a primary Fedora architecture, from its current secondary status. Just as the names imply, a secondary architecture (SA) doesn’t have to meet the same standards as a primary architecture (PA). All of the packages in a PA must build and work correctly, while an SA can sit on the back burner and not get a lot of attention. The proposal is looking to a future of 64-bit enterprise ARM servers, and ARM becoming the dominant hardware architecture over x86_64.

Fedora needs to get moving, because Canonical has already been grooming their original design manufacturers (ODMs) to make Ubuntu the first operating system ready to run ARMv8. There are two interesting PDFs to read on Index of /uhs/2011: Ubuntu-ARM-knowledge.pdf and Ubuntu ARM Roadmap.pdf. These have a lot of useful information on ARM and Canonical’s roadmap.

Читайте также:  Система инициализации для linux

The trusty old x86_64 platform has served us well for many years now, but its dominance is being challenged by ARM. As always there will be hurdles to openness, such as patents and loony experiments like Windows locking down the ARM bootloader. Maybe someday technological progress will be limited only by our ingenuity, rather than by lockin and lockdown.

Источник

Заводим GNU/Linux на ARM-плате с нуля (на примере Kali и iMX.6)

tl;dr: собираю образ Kali Linux для ARM-компьютера, в программе debootstrap , linux и u-boot .

Если вы покупали какой-нибудь не очень популярный одноплатник, то могли столкнуться с отсутствием для него образа любимого дистрибутива. Приблизительно то же самое случилось с планируемым Flipper One. Kali Linux под IMX6 просто нету (я готовлю), поэтому собирать приходится самостоятельно.

Процесс загрузки достаточно простой:

  1. Инициализируется железо.
  2. Из некоторой области на запоминающем устройства (SD-карта/eMMC/etc) считывается и выполняется загрузчик.
  3. Загрузчик ищет ядро операционной системы и загружает его в некоторую область памяти и выполняет.
  4. Ядро загружает всю остальную ОС.

Сборка корневой файловой системы

Для начала нужно подготовить разделы. Das U-Boot поддерживает разные ФС, я выбрал FAT32 для /boot и ext3 для корня, это стандартная разметка образов для Kali под ARM. Я воспользуюсь GNU Parted, но вы можете сделать то же самое более привычным fdisk . Также понадобятся dosfstools и e2fsprogs для создания ФС: apt install parted dosfstools e2fsprogs .

  1. Отмечаем SD-карту как использующую MBR-разметку: parted -s /dev/mmcblk0 mklabel msdos
  2. Создаём раздел под /boot на 128 мегабайт: parted -s /dev/mmcblk0 mkpart primary fat32 1MiB 128MiB . Первый пропущенный мегабайт необходимо оставить под саму разметку и под загрузчик.
  3. Создаём корневую ФС на всю оставшуюся ёмкость: parted -s /dev/mmcblk0 mkpart primary ext4 128MiB 100%
  4. Если вдруг у вас не создались или не изменились файлы разделов, надо выполнить `partprobe`, тогда таблица разделов будет перечитана.
  5. Создаём файловую систему загрузочного раздела с меткой BOOT : mkfs.vfat -n BOOT -F 32 -v /dev/mmcblk0p1
  6. Создаём корневую ФС с меткой ROOTFS : mkfs.ext3 -L ROOTFS /dev/mmcblk0p2
  1. Монтируем раздел в /mnt/ (используйте более удобную для себя точку монтирования): mount /dev/mmcblk0p2 /mnt
  2. Собственно заполняем файловую систему: debootstrap —foreign —include=qemu-user-static —arch armhf kali-rolling /mnt/ http://http.kali.org/kali . Параметр —include указывает дополнительно установить некоторые пакеты, я указал статически собранный эмулятор QEMU. Он позволяет выполнять chroot в ARM-окружение. Смысл остальных опций можно посмотреть в man debootstrap . Не забудьте, что не любая ARM-плата поддерживает архитектуру armhf .
  3. Из-за разницы архитектур debootstrap выполняется в два этапа, второй выполняется так: chroot /mnt/ /debootstrap/debootstrap —second-stage
  4. Теперь нужно зачрутиться: chroot /mnt /bin/bash
  5. Заполняем /etc/hosts и /etc/hostname целевой ФС. Заполните по аналогии с содержимым на вашем локальном компьютере, не забудьте только заменить имя хоста.
  6. Можно донастроить всё остальное. В частности я доустанавливаю locales (ключи репозитория), перенастраиваю локали и часовой пояс ( dpkg-reconfigure locales tzdata ). Не забудьте задать пароль командой passwd .
  7. Задаём пароль для root командой passwd .
  8. Приготовления образа для меня завершаются заполнением /etc/fstab внутри /mnt/ .
Читайте также:  Linux mint cinnamon x32

Наконец, можно примонтировать загрузочный раздел, он нам понадобится для ядра: `mount /dev/mmcblk0p1 /mnt/boot/`

Сборка Linux

Для сборки ядра (и загрузчика потом) на Debian Testing надо установить стандартный набор из GCC, GNU Make и заголовочных файлов GNU C Library для целевой архитектуры (у меня armhf ), а также заголовки OpenSSL, консольный калькулятор bc , bison и flex : apt install crossbuild-essential-armhf bison flex libssl-dev bc . Так как загрузчик по умолчанию ищет файл zImage на файловой системе загрузочного раздела, пора разбивать флешку.

  1. Клонировать ядро слишком долго, поэтому просто скачаю: wget https://cdn.kernel.org/pub/linux/kernel/v5.x/linux-5.9.1.tar.xz . Распакуем и перейдём в директорию с исходниками: tar -xf linux-5.9.1.tar.xz && cd linux-5.9.1
  2. Конфигурируем перед компиляцией: make ARCH=arm KBUILD_DEFCONFIG=imx_v6_v7_defconfig defconfig . Конфиг находится в директории arch/arm/configs/ . Если такового нет, вы можете попробовать найти и скачать готовый и передать название файла в этой директории в параметр KBUILD_DEFCONFIG . В крайнем случае сразу переходите к следующему пункту.
  3. Опционально можно докрутить настройки: make ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- menuconfig
  4. И кроскомпилируем образ: make ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf-
  5. Теперь можно скопировать файлик с ядром: cp arch/arm/boot/zImage /mnt/boot/
  6. И файлы с DeviceTree (описание имеющегося на плате железа): cp arch/arm/boot/dts/*.dtb /mnt/boot/
  7. И доустановить собранные в виде отдельных файлов модули: make ARCH=arm CROSS_COMPILE=arm-linux-gnueabi- INSTALL_MOD_PATH=/mnt/ modules_install

Das U-Boot

Так как загрузчик интерактивный, для проверки его работы достаточно самой платы, запоминающего устройства и опционально устройства USB-to-UART. То есть, можно ядро и ОС отложить на потом.

Абсолютное большинство производителей предлагают использовать Das U-Boot для первичной загрузки. Полноценная поддержка обычно обеспечивается в собственном форке, но и в апстрим контрибьютить не забывают. В моём случае плата поддерживается в мейнлайне, поэтому форк я проигнорировал.

  1. Клонируем стабильную ветку репозитория: git clone https://gitlab.denx.de/u-boot/u-boot.git -b v2020.10
  2. Переходим в саму директорию: cd u-boot
  3. Готовим конфигурацию сборки: make mx6ull_14x14_evk_defconfig . Это работает только если конфигурация есть в самом Das U-Boot, в ином случае вам потребуется найти конфиг производителя и положить его в корень репозитория в файл .config , или собрать иным рекомендованным производителем образом.
  4. Собираем сам образ загрузчика кросс-компилятором armhf : make CROSS_COMPILE=arm-linux-gnueabihf- u-boot.imx

Готово, можно загрузиться. Загрузчик должен сообщить собственную версию, некоторую информацию о плате и попытаться найти образ ядра на разделе. В случае неудачи будет пытаться загрузиться по сети. В целом вывод довольно подробный, можно найти ошибку в случае проблемы.

Вместо заключения

А вы знали, что лоб у дельфина не костистый? Это буквально третий глаз, жировая линза для эхолокации!

Источник

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