Linux boot no initrd

Исследуем процесс загрузки Linux

(C) В.А.Костромин, 2007
(версия файла от 5.10.2007 г.)

Этап 3: Загрузчик 2 этапа операционной системы

3.2. Файл /boot/initrd и его назначение

Как было сказано в предыдущем разделе, в процессе начальной загрузки вначале монтируется временный виртуальный диск, содержащий корневую файловую систему (очевидно, тоже временную), с помощью которой осуществляется запуск на выполнение ядра операционной системы. Образ этой корневой системы хранится на загрузочном устройстве в каталоге /boot и обычно носит имя initrd-2.x.yy-zzzz (точное наименование файла смотрите в вашей системе, далее он будет именоваться просто initrd). Загрузчик переносит образ корневой файловой системы из файла initrd в оперативную пямять одновременно с образом ядра, ядро преобразует initrd в «нормальный» RAM диск, монтирует временную корневую файловую систему, извлекает из нее нужные драйверы и другие служебные файлы, с помощью которых инициализирует все необходимые устройства. После этого происходит перемонтирование корневой файловой системы, временная ФС заменяется на постоянную, размещающуюся уже на долговременном носителе и процесс загрузки системы продолжается.

После того, как будет смонтирована корневая файловая система с жесткого диска, файл initrd уже никак не используется и место, занимаемое им в памяти, тоже освобождается. А теперь давайте подробнее рассмотрим как устроен этот файл. При этом надо сразу сказать, что внутреннее устройство initrd и его применение в ядрах версий 2.6 было изменено по сравнению с ядрами версий 2.4, так что придется рассмотреть эти случаи по отдельности.

3.2.1. Внутреннее устройство initrd

Как сказано в статье [10] в дистрибутиве Fedora Core 3 (и его предшественниках) файл initrd создавался с использованием виртуального loop-устройства. В этом случае сделать содержимое файла initrd доступным для просмотра можно с помощью следующих команд (напомню, что имя вашего образа initrd может отличаться):

В таких дистрибутивах, как Fedora Core 4, SUSE 10, . файл initrd представляет собой cpio-архив, сжатый упаковщиком gzip. Чтобы просмотреть его содержимое, надо выполнить команды, приведенные в листинге 3

/tmp вы найдете каталоговую структуру, аналогичную структуре каталогов обычной Linux-системы. В ней вы обнаружите обычные для корневого каталога подкаталоги, а также файл linuxrc. Могут там оказаться и другие файлы, например, файл bootsplash (судя по названию он содержит картинку, которая отображается при запуске).

Познакомившись с внутренним содержанием файла initrd можно вернуться к рассмотрению его роли в процессе загрузки.

3.2.2. Загрузка системы в случае использования initrd (ядра версий 2.4.х)

Приводимое ниже описание последовательности операций на этапе загрузки я позаимствовал из [11,12].

1. Загрузчик загружает ядро и содержимое initrd в память (очевидно, по вполне определенным адресам . ), после чего передает управление ядру.

2. Ядро содержит в себе небольшую несжатую часть, которая вначале разархивирует само ядро. Видимо как раз на этом этапе на экране монитора отображается сообщение «Uncompressing Linux. Ok, booting the kernel.»

3. Ядро инициализирует устройства, создает файловую систему устройств /dev, разархивирует initrd и копирует его содержимое на устройство /dev/ram0, а затем освобождает память, занятую initrd.

4. Ядро монтирует устройство /dev/ram0 для чтения и записи в качестве начальной корневой файловой системы.

5. Если в начальной корневой файловой системе находится исполняемый файл /linuxrc, он исполняется с uid 0. Этот файл должен иметь разрешения на исполнение, он может быть как обычным исполняемым файлом, так и просто скриптом оболочки, но в последнем случае должен быть и интерпретатор скриптов.

6. Cкрипт /linuxrc монтирует нормальную корневую файловую систему.

7. Корневая файловая система помещается в корневую директорию. Смена корневого устройства выполняется системным вызовом pivot_root, который также доступен через утилиту pivot_root (см. pivot_root(8); pivot_root распространяется в составе util-linux версии не ниже 2.10h ). Смена корневой директории не включает её демонтирование. Следовательно, при выполнении данной процедуры можно сохранить процессы, запущенные с файловой системы initrd.

8. Если нормальная корневая файловая система имеет каталог /initrd, то устройство /dev/ram0 перемещается из / в /initrd. Иначе, если каталог /initrd не существует, устройство /dev/ram0 размонтируется.

9. На нормальной корневой файловой системе следует обычная процедура загрузки (например, вызов /sbin/init).

10. Теперь можно демонтировать /dev/ram0 и освободить память, занятую RAM диском.

3.2.3. Initramfs — новая модель инициализации (ядра версий 2.6.х)

Во-первых, виртуальный диск, как и все блочные устройства, требует драйвер файловой системы для интерпретации данных во время выполнения. Этот драйвер приходилось включать в ядро.

Во-вторых, неэфективно используется оперативная память, так как размер виртуального диска фиксирован и не может изменяться во время работы без его переформатирования (даже если диск не заполнен, невозможно отдать эту память под другие нужды).

В третьих, в Linux осуществляется кэширование всех файлов и записей каталогов, прочитанных или записанных на блочное устройство. Виртуальный диск тоже кешируется, как и обычные диски, то есть часть данных будет храниться не только на RAM диске, но и в страничном кэше «page cache» (для файловых данных) и в кэше для записей каталогов «dentry cache», что еще больше снижает эффективность использования памяти.

Читайте также:  Как сделать запуск windows быстрее

Для устраненеия этих недостатков Линус Торвальдс предложил монтировать кэш ядра Линукс как особую файловую систему, работающую полностью в кэше ядра. При этом нет лишнего дублирования информации между блочным устройством и кэшем, так как блочного устройства попросту нет. Файловая система, реализующая эти идеи, была разработана и получила название initramfs. Ее использование имеет следующие преимущества:

  • Система, использующая initramfs в качестве корневой файловой системы, более не нуждается в соответствующем драйвере файловой системы, встроенном в ядро, так как нет блочных устройств для интерпретации файловых систем.
  • Размер этой файловой системы автоматически изменяется в соответствии с обьёмом данных, которые она содержит. При добавлении новых файлов (как и при расширении существующих) автоматически выделяется память, при удалении или уменьшении файла происходит высвобождение памяти.
  • Достоинством initramfs является также то, что это не новый код, а новое применение уже существующего кода кэширования ядра Линукс, что практически не влечёт увеличение размера ядра, выполнение будет очень простым и основано на чрезвычайно хорошо протестированной инфраструктуре.
  • Исчезают некоторые проблемы загрузки с SATA-дисков.
  • Initramfs загружается немного быстрее, чем initrd.

Формат initramfs используется по умолчанию для всех ядер, начиная с версии 2.6.15.

В каталоге /boot такая файловая система хранится, по-прежнему, в файле в виде сжатого cpio-архива. Только имя включаемого в этот архив скрипта изменилось с linuxrc на init. Например, в системе ASP Linux 11 после разархивирования файла initrd-2.6.14-1.1653.1asp.img по приведенному в листинге 3 алгоритму я увидел скрипт init и следующую структуру каталогов:

В подкаталоге /bin обнаружилось всего 4 исполняемых файла и две ссылки, в подкаталоге /dev — 8 файлов устройств, в /etc — конфигурационный файл udev/udev.conf, в каталоге lib — два файла: ext3.ko и jbd.ko. Остальные подкаталоги — пустые. Файл init оказался скриптом оболочки следующего вида:

Листинг 4. Содержимое файла init в дистрибутиве ASP Linux версии 11. Обратите внимание на первую строку этого файла: это скрипт для оболочки nash, которая является сильно урезанной версией командного процессора и тоже включена в состав initramfs. Другие, более мощные оболочки на этом этапе еще недоступны.

Как видно из листинга 4, скрипт init монтирует файловые системы /sys и /dev, инициализирует несколько устройств, загружает модули из подкаталога /lib и монтирует корневую файловую систему. Сколько я ни вглядывался в экран при перезагрузках системы, я не увидел сообщений, которые вроде бы должны выдаваться командами echo, включенными в этот скрипт.

Образ виртуальной файловой системы initramfs хранится на диске по-прежнему в файле /boot/initrd-version и создается такой файл как и ранее командой mkinitrd. Прочитать о том, как создать такой файл, можно в статье [10]. Перечень модулей (иначе говоря, драйверов), которые будут включены в эту файловую систему, приведен в переменой INITRD_MODULES в файле /etc/sysconfig/kernel. Если вам требуется включить в /boot/initrd-version какие-то дополнительные модули (например, в случае изменения состава оборудования), вы можете скорректировать соответствующим образом список модулей в файле /etc/sysconfig/kernel, после чего заново создать файл /boot/initrd-version.

Источник

Using the initial RAM disk (initrd)В¶

initrd provides the capability to load a RAM disk by the boot loader. This RAM disk can then be mounted as the root file system and programs can be run from it. Afterwards, a new root file system can be mounted from a different device. The previous root (from initrd) is then moved to a directory and can be subsequently unmounted.

initrd is mainly designed to allow system startup to occur in two phases, where the kernel comes up with a minimum set of compiled-in drivers, and where additional modules are loaded from initrd.

This document gives a brief overview of the use of initrd. A more detailed discussion of the boot process can be found in 1.

Operation¶

When using initrd, the system typically boots as follows:

the boot loader loads the kernel and the initial RAM disk

the kernel converts initrd into a “normal” RAM disk and frees the memory used by initrd

if the root device is not /dev/ram0 , the old (deprecated) change_root procedure is followed. see the “Obsolete root change mechanism” section below.

root device is mounted. if it is /dev/ram0 , the initrd image is then mounted as root

/sbin/init is executed (this can be any valid executable, including shell scripts; it is run with uid 0 and can do basically everything init can do).

init mounts the “real” root file system

init places the root file system at the root directory using the pivot_root system call

init execs the /sbin/init on the new root filesystem, performing the usual boot sequence

the initrd file system is removed

Note that changing the root directory does not involve unmounting it. It is therefore possible to leave processes running on initrd during that procedure. Also note that file systems mounted under initrd continue to be accessible.

Boot command-line options¶

initrd adds the following new options:

Compressed cpio images¶

Recent kernels have support for populating a ramdisk from a compressed cpio archive. On such systems, the creation of a ramdisk image doesn’t need to involve special block devices or loopbacks; you merely create a directory on disk with the desired initrd content, cd to that directory, and run (as an example):

Читайте также:  Язык программирования под linux

Examining the contents of an existing image file is just as simple:

Installation¶

First, a directory for the initrd file system has to be created on the “normal” root file system, e.g.:

The name is not relevant. More details can be found on the pivot_root(2) man page.

If the root file system is created during the boot procedure (i.e. if you’re building an install floppy), the root file system creation procedure should create the /initrd directory.

If initrd will not be mounted in some cases, its content is still accessible if the following device has been created:

Second, the kernel has to be compiled with RAM disk support and with support for the initial RAM disk enabled. Also, at least all components needed to execute programs from initrd (e.g. executable format and file system) must be compiled into the kernel.

Third, you have to create the RAM disk image. This is done by creating a file system on a block device, copying files to it as needed, and then copying the content of the block device to the initrd file. With recent kernels, at least three types of devices are suitable for that:

a floppy disk (works everywhere but it’s painfully slow)

a RAM disk (fast, but allocates physical memory)

a loopback device (the most elegant solution)

We’ll describe the loopback device method:

make sure loopback block devices are configured into the kernel

create an empty file system of the appropriate size, e.g.:

(if space is critical, you may want to use the Minix FS instead of Ext2)

mount the file system, e.g.:

create the console device:

copy all the files that are needed to properly use the initrd environment. Don’t forget the most important file, /sbin/init

/sbin/init permissions must include “x” (execute).

correct operation the initrd environment can frequently be tested even without rebooting with the command:

This is of course limited to initrds that do not interfere with the general system state (e.g. by reconfiguring network interfaces, overwriting mounted devices, trying to start already running demons, etc. Note however that it is usually possible to use pivot_root in such a chroot’ed initrd environment.)

unmount the file system:

the initrd is now in the file “initrd”. Optionally, it can now be compressed:

For experimenting with initrd, you may want to take a rescue floppy and only add a symbolic link from /sbin/init to /bin/sh . Alternatively, you can try the experimental newlib environment 2 to create a small initrd.

Finally, you have to boot the kernel and load initrd. Almost all Linux boot loaders support initrd. Since the boot process is still compatible with an older mechanism, the following boot command line parameters have to be given:

(rw is only necessary if writing to the initrd file system.)

With LOADLIN, you simply execute:

With LILO, you add the option INITRD=

to either the global section or to the section of the respective kernel in /etc/lilo.conf , and pass the options using APPEND, e.g.:

and run /sbin/lilo

For other boot loaders, please refer to the respective documentation.

Now you can boot and enjoy using initrd.

Changing the root device¶

When finished with its duties, init typically changes the root device and proceeds with starting the Linux system on the “real” root device.

The procedure involves the following steps:

mounting the new root file system

turning it into the root file system

removing all accesses to the old (initrd) root file system

unmounting the initrd file system and de-allocating the RAM disk

Mounting the new root file system is easy: it just needs to be mounted on a directory under the current root. Example:

The root change is accomplished with the pivot_root system call, which is also available via the pivot_root utility (see pivot_root(8) man page; pivot_root is distributed with util-linux version 2.10h or higher 3). pivot_root moves the current root to a directory under the new root, and puts the new root at its place. The directory for the old root must exist before calling pivot_root . Example:

Now, the init process may still access the old root via its executable, shared libraries, standard input/output/error, and its current root directory. All these references are dropped by the following command:

Where what-follows is a program under the new root, e.g. /sbin/init If the new root file system will be used with udev and has no valid /dev directory, udev must be initialized before invoking chroot in order to provide /dev/console .

Note: implementation details of pivot_root may change with time. In order to ensure compatibility, the following points should be observed:

Читайте также:  Exeq neonlight eq pcu 02010 драйвер windows 10

before calling pivot_root, the current directory of the invoking process should point to the new root directory

use . as the first argument, and the _relative_ path of the directory for the old root as the second argument

a chroot program must be available under the old and the new root

chroot to the new root afterwards

use relative paths for dev/console in the exec command

Now, the initrd can be unmounted and the memory allocated by the RAM disk can be freed:

It is also possible to use initrd with an NFS-mounted root, see the pivot_root(8) man page for details.

Usage scenarios¶

The main motivation for implementing initrd was to allow for modular kernel configuration at system installation. The procedure would work as follows:

system boots from floppy or other media with a minimal kernel (e.g. support for RAM disks, initrd, a.out, and the Ext2 FS) and loads initrd

/sbin/init determines what is needed to (1) mount the “real” root FS (i.e. device type, device drivers, file system) and (2) the distribution media (e.g. CD-ROM, network, tape, …). This can be done by asking the user, by auto-probing, or by using a hybrid approach.

/sbin/init loads the necessary kernel modules

/sbin/init creates and populates the root file system (this doesn’t have to be a very usable system yet)

/sbin/init invokes pivot_root to change the root file system and execs — via chroot — a program that continues the installation

the boot loader is installed

the boot loader is configured to load an initrd with the set of modules that was used to bring up the system (e.g. /initrd can be modified, then unmounted, and finally, the image is written from /dev/ram0 or /dev/rd/0 to a file)

now the system is bootable and additional installation tasks can be performed

The key role of initrd here is to re-use the configuration data during normal system operation without requiring the use of a bloated “generic” kernel or re-compiling or re-linking the kernel.

A second scenario is for installations where Linux runs on systems with different hardware configurations in a single administrative domain. In such cases, it is desirable to generate only a small set of kernels (ideally only one) and to keep the system-specific part of configuration information as small as possible. In this case, a common initrd could be generated with all the necessary modules. Then, only /sbin/init or a file read by it would have to be different.

A third scenario is more convenient recovery disks, because information like the location of the root FS partition doesn’t have to be provided at boot time, but the system loaded from initrd can invoke a user-friendly dialog and it can also perform some sanity checks (or even some form of auto-detection).

Last not least, CD-ROM distributors may use it for better installation from CD, e.g. by using a boot floppy and bootstrapping a bigger RAM disk via initrd from CD; or by booting via a loader like LOADLIN or directly from the CD-ROM, and loading the RAM disk from CD without need of floppies.

Obsolete root change mechanism¶

The following mechanism was used before the introduction of pivot_root. Current kernels still support it, but you should _not_ rely on its continued availability.

It works by mounting the “real” root device (i.e. the one set with rdev in the kernel image or with root=… at the boot command line) as the root file system when linuxrc exits. The initrd file system is then unmounted, or, if it is still busy, moved to a directory /initrd , if such a directory exists on the new root file system.

In order to use this mechanism, you do not have to specify the boot command options root, init, or rw. (If specified, they will affect the real root file system, not the initrd environment.)

If /proc is mounted, the “real” root device can be changed from within linuxrc by writing the number of the new root FS device to the special file /proc/sys/kernel/real-root-dev, e.g.:

Note that the mechanism is incompatible with NFS and similar file systems.

This old, deprecated mechanism is commonly called change_root , while the new, supported mechanism is called pivot_root .

Mixed change_root and pivot_root mechanism¶

In case you did not want to use root=/dev/ram0 to trigger the pivot_root mechanism, you may create both /linuxrc and /sbin/init in your initrd image.

/linuxrc would contain only the following:

Once linuxrc exited, the kernel would mount again your initrd as root, this time executing /sbin/init . Again, it would be the duty of this init to build the right environment (maybe using the root= device passed on the cmdline) before the final execution of the real /sbin/init .

Resources¶

Almesberger, Werner; “Booting Linux: The History and the Future” https://www.almesberger.net/cv/papers/ols2k-9.ps.gz

newlib package (experimental), with initrd example https://www.sourceware.org/newlib/

© Copyright The kernel development community.

Источник

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