Linux kernel + busybox自制arm64架构Linux系统


如需转载请标明出处:http://blog.csdn.net/itas109
QQ技术交流群:129518033

相关阅读:
1.linux内核之源码编译
2.Linux kernel + busybox自制x86_64架构Linux系统

相关问题:
1.自制操作系统
2.制作简单的Linux系统
3.Linux系统制作流程
4.qemu模拟运行arm64
5.qemu模拟运行aarch64
6.x86_64交叉编译arm64 linux内核

环境:
OS:Ubuntu 20.04
aarch64-linux-gnu-gcc: gcc version 9.3.0 (Ubuntu 9.3.0-10ubuntu1)
Linux Kernel: linux-5.4.50(2020-07-01 08:50)
busybox: busybox-1.32.0(2020-06-26 19:30)
qemu: qemu-system-aarch64 4.2.0

前言

自制arm64架构的Linux系统

1.下载和编译Linux kernel

1.1 下载Linux内核

Linux内核官网:https://www.kernel.org/

wget https://cdn.kernel.org/pub/linux/kernel/v5.x/linux-5.4.50.tar.xz

wget https://mirror.bjtu.edu.cn/kernel/linux/kernel/v5.x/linux-5.4.50.tar.xz

1.2 安装所需前置软件

sudo apt-get install gcc-aarch64-linux-gnu libncurses5-dev build-essential flex bison bc  

查找aarch64相关安装包:

apt-cache search aarch64

1.3 设置CPU架构(★)

这里以arm64架构为例。常用的架构还有x86_64、mips(龙芯)、alpha(申威)

# 设置CPU架构
$ export ARCH=arm64

# 设置交叉编译工具链前缀
$ export CROSS_COMPILE=aarch64-linux-gnu-

1.4 设置系统选项

# 生成arm64的默认.config(根据ARCH生成,arch/arm64/configs/defconfig)
$ make defconfig

# 设置系统选项
$ make menuconfig
 .config - Linux/arm64 5.4.50 Kernel Configuration
 ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
  ┌────────────────────────────────────────────── Linux/arm64 5.4.50 Kernel Configuration ───────────────────────────────────────────────┐
  │  Arrow keys navigate the menu.  <Enter> selects submenus ---> (or empty submenus ----).  Highlighted letters are hotkeys.  Pressing  │  
  │  <Y> includes, <N> excludes, <M> modularizes features.  Press <Esc><Esc> to exit, <?> for Help, </> for Search.  Legend: [*]         │  
  │  built-in  [ ] excluded  <M> module  < > module capable                                                                              │  
  │                                                                                                                                      │  
  │ ┌──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ │  
  │ │                                  *** Compiler: aarch64-linux-gnu-gcc (Ubuntu 9.3.0-10ubuntu1) 9.3.0 ***                          │ │  
  │ │                                  General setup  --->                                                                             │ │  
  │ │                                  Platform selection  --->                                                                        │ │  
  │ │                                  Kernel Features  --->                                                                           │ │  
  │ │                                  Boot options  --->                                                                              │ │  
  │ │                                  Power management options  --->                                                                  │ │  
  │ │                                  CPU Power Management  --->                                                                      │ │  
  │ │                                  Firmware Drivers  --->                                                                          │ │  
  │ │                              [*] ACPI (Advanced Configuration and Power Interface) Support  --->                                 │ │  
  │ │                              [*] Virtualization  --->                                                                            │ │  
  │ │                              [*] ARM64 Accelerated Cryptographic Algorithms  --->                                                │ │  
  │ │                                  General architecture-dependent options  --->                                                    │ │  
  │ │                              [*] Enable loadable module support  --->                                                            │ │  
  │ │                              -*- Enable the block layer  --->                                                                    │ │  
  │ │                                  IO Schedulers  --->                                                                             │ │  
  │ │                                  Executable file formats  --->                                                                   │ │  
  │ │                                  Memory Management options  --->                                                                 │ │  
  │ │                              [*] Networking support  --->                                                                        │ │  
  │ │                                  Device Drivers  --->                                                                            │ │  
  │ │                                  File systems  --->                                                                              │ │  
  │ │                                  Security options  --->                                                                          │ │  
  │ │                              -*- Cryptographic API  --->                                                                         │ │  
  │ │                                  Library routines  --->                                                                          │ │  
  │ │                                  Kernel hacking  --->                                                                            │ │  
  │ └──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ │  
  ├──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤  
  │                                       <Select>    < Exit >    < Help >    < Save >    < Load >                                       │  
  └──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘  

Linux kernel make详细帮助:

$ make help
Cleaning targets:
...

Configuration targets:
  config	  - Update current config utilising a line-oriented program
  nconfig         - Update current config utilising a ncurses menu based program
  menuconfig	  - Update current config utilising a menu based program
  xconfig	  - Update current config utilising a Qt based front-end
  gconfig	  - Update current config utilising a GTK+ based front-end
  oldconfig	  - Update current config utilising a provided .config as base
  localmodconfig  - Update current config disabling modules not loaded
  localyesconfig  - Update current config converting local mods to core
  defconfig	  - New config with default from ARCH supplied defconfig
  savedefconfig   - Save current config as ./defconfig (minimal config)
  allnoconfig	  - New config where all options are answered with no
  allyesconfig	  - New config where all options are accepted with yes
  allmodconfig	  - New config selecting modules when possible
  alldefconfig    - New config with all symbols set to default
  randconfig	  - New config with random answer to all options
  listnewconfig   - List new options
  olddefconfig	  - Same as oldconfig but sets new symbols to their
                    default value without prompting
  kvmconfig	  - Enable additional options for kvm guest kernel support
  xenconfig       - Enable additional options for xen dom0 and guest kernel support
  tinyconfig	  - Configure the tiniest possible kernel
  testconfig	  - Run Kconfig unit tests (requires python3 and pytest)

Other generic targets:
  all		  - Build all targets marked with [*]
* vmlinux	  - Build the bare kernel
* modules	  - Build all modules
  modules_install - Install all modules to INSTALL_MOD_PATH (default: /)
  dir/            - Build all files in dir and below
  dir/file.[ois]  - Build specified target only
  dir/file.ll     - Build the LLVM assembly file
                    (requires compiler support for LLVM assembly generation)
  dir/file.lst    - Build specified mixed source/assembly target only
                    (requires a recent binutils and recent build (System.map))
  dir/file.ko     - Build module including final link
  modules_prepare - Set up for building external modules
  tags/TAGS	  - Generate tags file for editors
  cscope	  - Generate cscope index
  gtags           - Generate GNU GLOBAL index
  kernelrelease	  - Output the release version string (use with make -s)
  kernelversion	  - Output the version stored in Makefile (use with make -s)
  image_name	  - Output the image name (use with make -s)
  headers_install - Install sanitised kernel headers to INSTALL_HDR_PATH
                    (default: ./usr)

Static analysers:
  checkstack      - Generate a list of stack hogs
  namespacecheck  - Name space analysis on compiled kernel
  versioncheck    - Sanity check on version.h usage
  includecheck    - Check for duplicate included header files
  export_report   - List the usages of all exported symbols
  headerdep       - Detect inclusion cycles in headers
  coccicheck      - Check with Coccinelle

Tools:
  nsdeps          - Generate missing symbol namespace dependencies

Kernel selftest:
  kselftest       - Build and run kernel selftest (run as root)
                    Build, install, and boot kernel before
                    running kselftest on it
  kselftest-clean - Remove all generated kselftest files
  kselftest-merge - Merge all the config dependencies of kselftest to existing
                    .config.

Devicetree:
* dtbs             - Build device tree blobs for enabled boards
  dtbs_install     - Install dtbs to /boot/dtbs/
  dt_binding_check - Validate device tree binding documents
  dtbs_check       - Validate device tree source files

Userspace tools targets:
  use "make tools/help"
  or  "cd tools; make help"

Kernel packaging:
...

Documentation targets:
...

Architecture specific targets (arm64):
* Image.gz      - Compressed kernel image (arch/arm64/boot/Image.gz)
  Image         - Uncompressed kernel image (arch/arm64/boot/Image)
  install       - Install uncompressed kernel
  zinstall      - Install compressed kernel
                  Install using (your) ~/bin/installkernel or
                  (distribution) /sbin/installkernel or
                  install to $(INSTALL_PATH) and run lilo

  make V=0|1 [targets] 0 => quiet build (default), 1 => verbose build
  make V=2   [targets] 2 => give reason for rebuild of target
  make O=dir [targets] Locate all output files in "dir", including .config
  make C=1   [targets] Check re-compiled c source with $CHECK (sparse by default)
  make C=2   [targets] Force check of all c source with $CHECK
  make RECORDMCOUNT_WARN=1 [targets] Warn about ignored mcount sections
  make W=n   [targets] Enable extra build checks, n=1,2,3 where
		1: warnings which may be relevant and do not occur too often
		2: warnings which occur quite often but may still be relevant
		3: more obscure warnings, can most likely be ignored
		Multiple levels can be combined with W=12 or W=123

Execute "make" or "make all" to build all targets marked with [*] 
For further info see the ./README file

1.5 编译

AMD 4800H CPU 8G内存16线程大约需要5分钟编译

# 根据CPU线程数设置
$ make -j 16

最后编译完成的内核位于arch/x86/boot/bzImage

$ ls -l arch/arm64/boot/Image
-rw-rw-r-- 1 dev dev 26092032 8月  12 21:16 arch/arm64/boot/Image

至此,Linux kernel编译完成


linux-5.4.50文件夹编译完的磁盘占用情况

$ du -lh --max-depth=1
208K	./LICENSES
48M	./Documentation
44M	./lib
121M	./sound
35M	./tools
2.3M	./init
30M	./crypto
13M	./virt
42M	./mm
50M	./include
75M	./kernel
5.9M	./scripts
204K	./certs
266M	./fs
224M	./arch
1.6M	./samples
8.9M	./security
432M	./net
128K	./usr
17M	./block
4.3M	./ipc
2.9G	./drivers
5.4G	.

2.下载和编译busybox

busybox 将许多具有共性的小版本的UNIX工具结合到一个单一的可执行文件。这样的集合可以替代大部分常用工具比如的GNU fileutils,shellutils等工具,busybox提供了一个比较完善的环境,可以适用于任何小的嵌入式系统。

2.1 下载busybox

下载地址:https://busybox.net/downloads/

wget https://busybox.net/downloads/busybox-1.32.0.tar.bz2

2.2 设置CPU架构(★)

这里以arm64架构为例。

# 设置CPU架构
$ export ARCH=arm64

# 设置交叉编译工具链前缀
$ export CROSS_COMPILE=aarch64-linux-gnu-

2.3 设置系统选项

# 生成默认.config
$ make  defconfig

# 设置busybox选项
$ make menuconfig

修改选项

    ...
    Settings  ---> 
        ...
        # 静态编译busybox
        --- Build Options  
        [*] Build static binary (no shared libs) 
        ...
    ...

bosybox make详细帮助:

$ make help
...

Configuration:
  allnoconfig		- disable all symbols in .config
  allyesconfig		- enable all symbols in .config (see defconfig)
  config		- text based configurator (of last resort)
  defconfig		- set .config to largest generic configuration
  menuconfig		- interactive curses-based configurator
  oldconfig		- resolve any unresolved symbols in .config
  android2_defconfig    - Build for android2
  cygwin_defconfig      - Build for cygwin
  TEST_nommu_defconfig  - Build for TEST_nommu
  android_defconfig     - Build for android
  TEST_noprintf_defconfig - Build for TEST_noprintf
  android_ndk_defconfig - Build for android_ndk
  android_502_defconfig - Build for android_502
  TEST_rh9_defconfig    - Build for TEST_rh9
  freebsd_defconfig     - Build for freebsd


Installation:
  install		- install busybox into CONFIG_PREFIX
  uninstall
...

2.4 编译

# 根据CPU线程数设置
$ make -j 16

安装busybox,默认路径为当期目录的_install文件夹

make install
$ file _install/bin/busybox 
_install/bin/busybox: ELF 64-bit LSB executable, ARM aarch64, version 1 (GNU/Linux), statically linked, BuildID[sha1]=15c3d931be02d441c975fd054f694b620fe5b87c, for GNU/Linux 3.7.0, stripped

至此,busybox静态编译完成


busybox-1.32.0文件夹编译完的磁盘占用情况

$ du -lh --max-depth=1
636K	./examples
276K	./mailutils
276K	./findutils
2.5M	./archival
256K	./init
524K	./console-tools
5.5M	./networking
248K	./e2fsprogs
7.4M	./include
1016K	./procps
1.4M	./docs
232K	./sysklogd
4.0K	./.tmp_versions
1.7M	./scripts
524K	./applets
108K	./selinux
368K	./modutils
540K	./loginutils
196K	./debianutils
3.9M	./util-linux
28K	./arch
952K	./editors
7.0M	./shell
2.3M	./miscutils
3.3M	./coreutils
36K	./qemu_multiarch_testing
128K	./printutils
12K	./applets_sh
5.0M	./libbb
116K	./klibc-utils
124K	./libpwdgrp
252K	./configs
1.7M	./testsuite
436K	./runit
55M	.

3.制作根文件系统rootfs

基于busybox的文件系统启动过程:

/sbin/init => /etc/inittab => /etc/init.d/rdS => /etc/fstab ...

3.1 创建根目录所需的目录

$ cd busybox-1.32.0/_install

$ ls
bin  linuxrc  sbin  usr

$ mkdir -p dev etc home lib mnt proc root sys tmp var

$ ls
bin  dev  etc  home  lib  linuxrc  mnt  proc  root  sbin  sys  tmp  usr  var

根文件系统目录说明

/bin: 系统管理员和用户均可使用的命令
/sbin: 系统管理员使用的系统命令
/dev: 存储特殊文件或设备文件;设备两种类型:字符设备、块设备
/etc: 系统配置文件
/home: 普通用户目录
/root:root用户目录
/lib: 为系统启动或根文件上的应用程序(/bin,/sbin等)提供共享库,以及为内核提供内核模块
/mnt:临时挂载点
/tmp: 临时文件存储目录
/usr:usr hierarchy,全局共享的只读数据路径
/var:存储常发生变化的数据目录:cache、log等
/proc: 基于内存的虚拟文件系统,用于为内核及进程存储其相关信息
/sys:sysfs虚拟文件系统提供了一种比proc更为理想的访问内核数据的途径:其主要作用在于为管理linux设备提供一种统一模型的接口;


3.2 创建根目录所需的必要文件

  • etc/inittab
$ cd busybox-1.32.0/_install
$ vim etc/inittab
$ chmod 755 etc/inittab

etc/inittab内容:

::sysinit:/etc/init.d/rcS
::respawn:-/bin/sh
::askfirst:-/bin/sh
::cttlaltdel:/bin/umount -a -r

inittab语法:

<id>:<runlevels>:<action>:<process>

id : /dev/id
runlevels : 忽略
action : 何时执行,有以下选项 sysinit, respawn, askfirst, wait, once,restart, ctrlaltdel, and shutdown
process : 应用程序或脚本
  • etc/init.d/rcS
$ cd busybox-1.32.0/_install
$ mkdir -p etc/init.d/
$ vim etc/init.d/rcS
$ chmod 755 etc/init.d/rcS

etc/init.d/rcS内容:

echo "----------mount all in fstab----------------"
/bin/mount -a #读取/etc/fstab,加载文件系统
mkdir -p /dev/pts
mount -t devpts devpts /dev/pts
echo /sbin/mdev > /proc/sys/kernel/hotplug
mdev -s
echo "****************Hello itas109******************"
echo "Kernel Version:linux-5.4.50"
echo "***********************************************"
  • etc/fstab
$ cd busybox-1.32.0/_install
vim etc/fstab

etc/fstab内容:

#device mount-point type option dump fsck
proc  /proc proc  defaults 0 0
temps /tmp  rpoc  defaults 0 0
none  /tmp  ramfs defaults 0 0
sysfs /sys  sysfs defaults 0 0
mdev  /dev  ramfs defaults 0 0
  • 添加设备文件
$ cd busybox-1.32.0/_install
$ cd dev
$ sudo mknod console c 5 1
$ sudo mknod null c 1 3

制作根文件系统镜像文件rootfs.cpio.gz

$ cd busybox-1.32.0/_install
$ find . | cpio -o -H newc > rootfs.cpio 
$ gzip -c rootfs.cpio > rootfs.cpio.gz

4.Linux系统运行

cd ~
$ qemu-system-aarch64 \
  -cpu cortex-a57 \
  -m 512M \
  -machine type=virt \
  -nographic \
  -smp 1 \
  -kernel ./Image  \
  -initrd ./rootfs.cpio.gz   \
  -append "rdinit=/linuxrc console=ttyAMA0" \
  -device virtio-scsi-device

启动结果:

[    0.000000] Booting Linux on physical CPU 0x0000000000 [0x411fd070]
[    0.000000] Linux version 5.4.50 (dev@dev) (gcc version 9.3.0 (Ubuntu 9.3.0-10ubuntu1)) #1 SMP PREEMPT Wed Aug 12 21:09:35 CST 2020
...

----------mount all in fstab----------------
mount: mounting temps on /tmp failed: No such device
/etc/init.d/rcS: line 5: can't create /proc/sys/kernel/hotplug: nonexistent directory
****************Hello itas109******************
Kernel Version:linux-5.4.50
***********************************************

Please press Enter to activate this console. 
/ # uname -a
Linux (none) 5.4.50 #1 SMP PREEMPT Wed Aug 12 21:09:35 CST 2020 aarch64 GNU/Linux

Reference:
NULL

Logo

更多推荐