Linux boot sequence will

Последовательность загрузки Linux

категория
Администрирование
дата 15.07.2009
автор analizer
голосов 12

[Disclaimer: Данная статья была переведена в рамках «Конкурса на лучший перевод статьи» на сервисе Quizful. Ссылка на оригинал находится внизу страницы.]

Последовательность загрузки Linux системы состоит из следующих этапов:

BIOS — это интерфейс самого низкого уровня между компьютером и периферией, который ищет и исполняет загрузочный сектор на каком-либо устройстве хранения данных подключённых к компьютеру.

Как правило это:

  • Привод CD-ROM
  • Жёсткий диск
  • Дисковод (используются всё реже)

Список зависит от возможностей конкретного BIOS’а, а также вашего оборудования.

Приоритет загрузки может быть изменён в BIOS’е. Войти в меню настройки BIOS’а, как правило, можно нажав Del, F1, F2 или F10 во время загрузки компьютера.

Первый сектор загружаемого устройства хранения данных зарезервирован под главную загрузочную запись. Когда происходит загрузка с устройства, BIOS загружает и исполняет загрузчик операционной системы (boot loader), находящийся в MBR.

В большинстве случаев загрузчик достаточно сложен и не может вместиться в 512 байт отведённые MBR. В этом случае в MBR находится так называемый stage1, программа которая просто загружает программу второго этапа загрузки операционной системы — stage2 (иногда в качестве stage2 загружается загрузочный сектор активного раздела, boot manager или программа авторизации и защиты доступа).

В частности, stage2 загрузчика GRUB считывает данные из файла /boot/grub/grub.conf (или /boot/grub/menu.lst, в зависимости от версии), который содержит список всех доступных операционных систем и их параметры загрузки. После этого на экран выводится список операционных систем из которого пользователь выбирает ОС для загрузки.

В некоторых случаях stage1 загрузчика GRUB (GRand Unified Bootloader) производит загрузку stage1.5 код которого находится в первых тридцати килобайтах устройства хранения данных следующих сразу за MBR, и уже stage1.5 производит загрузку stage2.

Когда stage2 получает управление, на экран выводится (псевдо)графическое меню для выбора пользователем ОС для загрузки. Стоит отметить, что параметры загрузки могут быть изменены из этого же меню, что позволяет восстановить систему после того как menu.lst или grub.conf были случайно испорчены.

Как только параметры загрузки были выбраны, GRUB загружает выбранное ядро в память и передаёт управление ядру, которое уже само продолжает загрузку системы. Также GRUB может передать управление не ядру, а другому загрузчику, используя так называемую цепную загрузку (chain loading), например загрузчику ОС не поддерживающей стандарт Multiboot.

В свою очередь, ядро проверяет конфигурацию оборудования, инициализирует устройства и запускает initrd (опционально), после чего монтирует с устройство указанное в параметрах загрузки как «root» как корневую файловую систему.

Файловая система устройства определяется автоматически. Если по каким либо причинам монтирование не удаётся, система выдаёт kernel panic и загрузка останавливается.

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

init — это последний шаг в последовательности загрузки системы. init является родителем (или же более далёким предком) для всех процессов исполняемых в системе. Этот процесс запускается первым в системе и его запуск производится непосредственно ядром. Он же запускает все системные процессы так как это указано в /etc/inittab.

Покуда система работает, init не будет завершён. Стоит отметить что init — пользовательский процесс, а не системный, не смотря на то что он запущен от root’а.

Каждая запись в /etc/inittab содержит так называемый «уровень запуска» для процесса, т.е. информацию о том на каком уровне запуска системы данный процесс должен быть запущен.

В Linux системах существует семь возможных значений для уровня запуска: от 0 до 6 включительно:

  1. Останов системы
  2. Однопользовательский режим
  3. Определяется пользователем, как правило это многопользовательский режим без поддержки сети и графической оболочки
  4. Многопользовательский режим без графической оболочки
  5. Определяется пользователем, как правило, не используется
  6. Многопользовательский режим с графической оболочкой
  7. Перезагрузка

Основываясь на текущем уровне запуска, init запускает скрипты находящиеся в поддиректориях /etc/rc.d/, для каждого уровня запуска существует своя поддиректория, от /etc/rc.d/rc0.d до /etc/rc.d/rc6.d.

В действительности же запуск скриптов каждого уровня запуска выполняется скриптом /etc/rc который вызывается на каждом уровне запуска с параметром равным текущему уровню. Вызов же /etc/rc параметром прописан в /etc/inittab, для каждого из возможных уровней запуска.

Уровень запуска по умолчанию определяется записью в /etc/inittab:

Текущий уровень запуска может быть изменён путём вызова:

Где # — желаемый уровень запуска. Т.е. вызов «/sbin/telinit 6» приведёт к перезагрузке системы.

Если Вам понравилась статья, проголосуйте за нее

Голосов: 12 Голосовать

Источник

Linux boot sequence overview

1 Load the BIOS hardware information, and get the code name of the first boot device;
2 Read the startup information of the boot loader of the MBR of the first startup device;
3 Load the core information of the core operating system, the core starts to decompress, and try to drive all hardware devices;
4 The core executes the init program and obtains operating information;
5 init executes the script of /etc/init.d;
6 Start the script in the core plug-in module /etc/modeprobe.d/;
7 init executes each batch script;
8 init executes the /etc/init.d/rc.local file;
9 Execute the /bin/login program and wait for the user to log in;
10 After logging in, start to control the host with a shell.

BIOS: basic input output system basic input output system

BIOS is very important. It records the relevant settings of the motherboard chip, such as the communication frequency of the CPU and the interface device, the search order of the boot device, the size and type of the hard disk, the system time, whether the external bus is enabled or not (Plug and Play, PnP) , The I/O address of each interface device, and the IRQ interrupt communication with the CPU and other information.

After obtaining the BIOS settings, start the Power on self test (POST), initialize the hardware detection, set the PnP device, and determine the bootable device.
After the BIOS finds the first sector of the hard disk, it searches for the location of the MBR. This is the most basic boot loader. Once this program is started, the BIOS’s task is considered complete.

MBR: master boot record master boot record.

Master bootloader

The MBR master boot record is mainly to install the loader. This boot loader is used to identify the format of the disk so that the kernel of the operating system can be loaded. At this time, the user can operate the boot options, such as the mainstream The grub boot loader can not only support linux, but also support windows.
Generally, the boot loader of Linux can recognize the core files of the window, but the boot loader of Windows cannot recognize linux, which is why it is necessary to set grub boot extra when installing dual systems. s reason.

After reading the core files of the Linux operating system through the boot loader, the core files will be decompressed into the main memory to start testing and driving various external devices, including storage, CPU, network card, sound card, etc. These core files are usually in /boot Inside, named vmlinuz.

The process of loading the core is more exciting than this. Normally, the system will only load the root directory in a read-only manner. Sometimes it can be read in files for certain functions. In some systems, a virtual In other words, the system will use the initrd command to create a virtual disk and use the linuxrc program to load the module image file (/boot/initrd-xxx.img).

When the core drive external hardware work is completed, the virtual disk will be deleted. It is worth noting that initrd is not necessary. The purpose of this is to ensure the smooth startup.

to sum up

To sum up, the boot loader finds the core file of Linux, loads it into the main memory, then uses initrd to create a virtual disk to assist the boot process, and finally the hardware information data in the BIOS is handed over to the Linux core for detection, and then the hardware driver is loaded.

Load BIOS -> MBR basic boot program (user boot option) -> Load and start the system core

The first program: init

The current mainstream Linux distros have two init methods: one is the widely circulated System V initialization, which is derived from Unix and is still used by various Linux distros; the other is the Upstart method proposed in recent years. Based on the event mechanism, all services and tasks of the system are driven by events. As far as I know, Ubuntu (6.10 and later), Fedora (9.10 and later), Debian (optional) currently adopt the latter method. Although there are not many releases using Upstart, it aims to replace the old-style System V initialization.

Run level

Init will first read the runlevel settings, so what is a runlevel?

grade Operating mode
0-halt System shutdown directly
1-single user mode Single user maintenance mode, used to maintain the system when problems occur
2-multiuser mode, without NFS Multi-user mode, but no NFS service
3-Full multiuser mode Multi-user, plain text mode with complete network functions
4-unused System reserved function
5-X11 Multi-user, use X window
6-reboot Restart mode

System V initialization method

This method is the init startup method introduced in Niaoge’s linux private kitchen. After the core is loaded, the first program executed by the system is /sbin/init. The init program will read the setting file «/etc/inittab» to get it running grade.

The inittab file is responsible for initializing the system, setting the system runlevel and entering each runlevel corresponding to the command to be executed. Assuming that the default runlevle set in the current inittab is 5, init will run the /etc/init.d/rc 5 command, which will traverse and execute the scripts/programs in /etc/rc5.d according to the dependencies of the system services. Enter the /etc/rc5.d directory and you can find that the files inside are all soft links to the corresponding scripts/programs under /etc/init.d/. Those beginning with S mean start, and those beginning with K mean stop. And the two-digit number after S/K represents the startup sequence of the service (determined by the service dependency).

Upstart way

Upstart job is event-driven. The start and stop of system services are all determined by events. Conversely, the start and stop of system services can also be used as event sources to trigger other services. And the event does not necessarily have to be generated internally in the system, the user can manually type start/stop [Service] to generate an event to start/stop the service. Man upstart-evnets view the events defined by the upstart job, you can find that the runlevel is also treated as an event (events caused by the change of the runlevel), and there are others such as startup, started, filesystem, etc. So how does the system service know when it should start and when it should terminate? The answer lies in /etc/init (some distros may be in /etc/event.d). When you enter the /etc/init directory, you can see that they are all system service configuration files, or job definition files.

Not only at the initial stage of system startup, but at any period of system operation, you can start or terminate services by sending events. This is one of the advantages of Upstart job. In addition to being used for system initialization, it can also play a role in system operation.

In contrast, the configuration file in the System V initialization mode is generally only used in the system initialization phase. Of course, we can operate the service through /etc/init.d/Service start/stop/otherCommand in the system operation phase, but it is obviously not as good as the Upstart mode Concise and clear.

Ubuntu automatic startup program instructions

What is the initialization process of the Ubuntu init system? In fact, Ubuntu uses a compatibility mode, that is: there are services started by System V-style and services started by Upstart in the system. Enter the /etc folder, you can see:

How is it compatible? In fact, ubuntu calls the script in /etc/rc$(runlevel).d/ through some configuration files under /etc/init to start the service using the old System V-style.

Specifically, first enter the /etc/init directory (Upstart init will read the configuration files in this directory), and you will find several configuration files related to rc

These files are the key to Upstart init processing System V-style services. rc-sysinit is started when a startup event occurs, that is, Upstart init will first read rc-sysinit.conf and execute related configurations and scripts. The main job of rc-sysinit.conf is to set the system default runlevel, check whether there is /etc/inittab or the kernel command line, if it exists, set the system runlevel in the order of kernel command line>/etc/inittab>default runlevel. Finally, call telinit to enter the set runlevel.

Since telinit is called to enter the set runlevel, the event of the runlevel change occurs, and the rc service is started (of course, other services will also). So, it is necessary for us to see what is in rc.conf. Open rc.conf and notice the last line:

It is clear, /etc/init.d/rc It is called, and the system runlevel set earlier is passed in as a parameter. and /etc/init.d/rc Will be called according to the runlevel parameter passed in /etc/rc$.d/ The following script (beginning with S) starts the service and terminates the service that was started in the previous runlevel and needs to be terminated in the current runlevel.

Each file in the rc (1-6).d folder is actually a soft link (similar to the shortcut in windows) of the file in the /etc/init.d folder, that is, in /etc/init.d There are all service programs in the folder, and each rc(1-6).d only links to the corresponding service programs that it needs to start.

Specifically, different run levels apply to different situations: 0-4-6 shutdown, reserve, restart, 1-2-3-5 user mode.

/etc/rc$.d/ Script under path:

To summarize, first of all, under Ubuntu’s /etc path

When init, it will first read rc-sysinit.conf, set the system default run level, trigger the rc service, read rc.conf, execute the initialization script of the default run level to start the system service. Usually the run level is 5, also It is to automatically start the script in /etc/rc5.d.
In this way, ubuntu invokes /etc/init.d/rc indirectly through rc-sysinit and rc to start the System V-style service. The new Upstart init takes care of the old System V init.

User-defined bootloader

The commands that the user wants to start with the boot can be written as a shell script and added to /etc/rc.d/rc.local in.

Change run level

Use the init command to add the rank number, for example init 3

Источник

Читайте также:  Команда линукс сетевые настройки
Оцените статью