Linux system startup process details-What happened after power-on-linux Kernel Analysis (0)
This article references the following articles:
A deep understanding of the linux Startup Process
Mbr (Master Boot Record ))
The process from powering on the computer to executing the main function of the Operating System
Detailed description of the linux system startup process and system initialization
Linux Startup Process
The linux Startup Process can be divided into the following steps:
BIOS
POST self-check BIOS (Boot Sequence) Boot Operating System
Load the corresponding boot MBR (bootloader) Main boot settings to load its BootLoader load the operating system boot BIOS, prepare the real-mode interrupt vector table and interrupt service program
After the computer is started, the CPU logic circuit is designed to run only programs in the memory, and cannot directly run the operating system in the floppy disk or hard disk, it must be loaded into the memory (RAM.
How does the BIOS start? The CPU hardware logic is designed to forcibly set the CS value to 0XF000 and the IP address to 0XFFF0 during power-on. In this way, CS: IP points to 0XFFFF0, this location is the entry address of the BIOS program.
The BIOS program is solidified into a very small ROM chip on the computer motherboard. Now CS: the IP address has been directed to the 0XFFFF0 position, which means that the BIOS starts to start.
POST self-check
The first step of BIOS isPower-on self-check (POST)
The job of POST is to check the hardware device. As the BIOS program is executed, the screen displays the information about the video card and memory,
Device Initialization
The second step of BIOS isEnumerate and initialize local devices
There is a task that is vital to starting the operating system, that isBIOS establishes a medium disconnection table and interrupt service programs in the memory
The BIOS program uses 1 kb of memory space (0x00000 ~ 0x003FF) Build the interrupt vector table, and build the BIOS data zone (0x00400 ~ 0x004FF), and some interrupt service programs corresponding to the interrupt vector table about 8 KB are loaded after about 57KB (0x0e05b.
The interrupt vector table has 256 interrupt vectors, each of which occupies 4 bytes, two of which are CS values and two of which are IP values. Each interrupt vector points to a specific interrupt service program.
The BIOS-runtime service searches for devices in the boot sequence to find BBR instances.
Different BIOS functions make up two parts: POST and runtime services. After the POST is completed, it will be cleared from the memory, but the BIOS runtime service will be retained for the target operating system.
To start the operating system, the BIOS runtime service searches for the activated or boot-able devices, the search sequence is determined by the CMOS settings (that is, the boot sequence we usually call in BIOS ). A soft drive, an optical drive, a partition on a hard disk, a network device, or even a usb flash drive, can be used as a boot device.
Of course, linux is usually started from a hard disk. The MBR (Master boot Record) on the hard disk contains a basic boot loader, which is a 512-byte sector located in the first sector of the disk (0 head, 0 track, 1 sector ). When the MBR is loaded into RAM, the BIOS transfers the control to the MBR.
Boot the operating system kernel and prepare for the protection mode
Located in MBRMain boot loaderIs a 512-byte image, which not only containsBootload program codeAnd contains a smallPartition Table.
The first 446 bytes are the main boot loader, which contains executable code and error message text. The next 64 bytes is a partition table, which contains records of the four partitions (each partition occupies 16 bytes ). MBR uses a special number 0xAA55 (note: in the electronics industry, AA55 is indeed a legend. Do you want to know why? Expand it into a binary form to see what is the rule) as the end sign of two bytes. 0x55AA is also an effective validation for MBR.
First, an int 0x19 interrupt is sent to the CPU so that the CPU runs the int 0x19 interrupt service program, this service interruption program is used to load the program in the first sector of the floppy disk to the specified memory location.
The main work of the boot loader is to find and LoadNext boot loader (kernel loader)
It analyzes the partition table and finds the active partition to complete this task. When it finds an active partition, it continues to scan the partitions in the remaining partition table to confirm that they are not activated.
After confirmation, the boot loader of the active partition is read from the device RAM and executed.
The loading process must be completed by using the interrupt service program pointed to by the int 0x13 interrupt vector provided by the BIOS. This program loads the Program setup. s to the SETUPSEG (0x90200) of the memory for the four sectors starting from the second sector of the floppy disk.
Combine the boot loaders of the first and second phases, that is, linux loader (LILO) or GRand uniied Bootloader (GRUB) on the x86 PC ). GRUB fixes some LILO defects, so let's take a look at GRUB (if you want to get more resources about GRUB, LILO, and related topics, see references below)
For GRUB, a better aspect is that it contains the knowledge of linux file systems. Unlike LILO's bare sector, GRUB can load the Linux kernel from the ext2 or ext3 file system. It converts a two-stage boot loader to a three-stage boot loader. In Stage 1 (MBR), boot loader of stage1.5 will be started to understand the special file system formats in Linux kernel images, for example, reiserfs_stage1-5 (for loading from reiserf log file systems) or e2fs + stage1_5 (used for loading from wxt2 or ext3 File System ). When the boot loader of stage1.5 is loaded and running, the boot loader of stage2 can be loaded. When stage2 is loaded, GRUB can display a list of optional kernels (in/etc/grub. conf, and several soft symbolic links/etc/grub/menu. lst and/etc/grub. conf ). You can select a kernel and modify its additional kernel parameters. At the same time, you can use the shell of the command line to perform more in-depth manual control over the startup process.
After the next boot loader exists and the memory is in place, you can query the file system and load the default kernel image and the initialized memory disk image into the memory.
After all preparations are completed, the next boot loader will call the kernel image to load the operating system.
Load the kernel and convert it from the real mode to the protection mode
When the kernel image is loaded into the memory (the loading process still uses the int 0x13 interrupt vector) and the next Boot Loader releases control, the kernel phase begins.
Load the kernel Image
The kernel image is not an executable kernel, but a compressed kernel image. Generally, it is a zImage (compressed image, smaller than KB) or a bzImage (larger compressed image, larger than KB). It is compressed using zlib in advance. In front of this kernel image is a routine that implements a small amount of hardware settings, decompress the kernel contained in the kernel image, and then put it into the high-end memory, if an initial RAM disk image exists, it will be moved to the memory and marked for future use. The routine then calls the kernel and starts the kernel boot process.
When bzImage (for i386 image) is called, we start execution from the start assembly routine of./arch/i386/boot/head. S.
This routine will execute some basic hardware settings and call. /arch/i386/boot/compressed/head. startup_32 in S, set a basic environment (stack, etc.), and clear Block Started by Symbol (BSS ). Call a C function called decompress_kernel (in./arch/i386/boot/compressed/misc. c) to decompress the kernel. After the kernel is decompressed to the memory, you can call it. This is another startup_32 function, but this function is in./arch/i386/kernel/head. S.
Enter protection mode and initialize
Enter protection mode
Set the interrupt description table and Global Descriptor Table
Memory paging mechanism created
Start the kernel
Start_kernel start the kernel
Create an init process
BIOS stage-Prepare the interrupt vector table and interrupt service programs in real mode BIOS background What is BIOS?
In the early 1970s S, the read-only memory (read-only memory) was invented, and the boot program was flushed into the ROM chip. After the computer was powered on, the first thing is to read it.
The program in this chip is called "Basic Input/Output System" (BIOS.
It is a set of programs solidified on a ROM chip on the motherboard of a computer. It stores the most important basic input and output programs of the computer, self-check programs after startup, and system self-start programs, it can read and write the specific information set by the system from CMOS. Its main function is to provide computers with the most underlying and direct hardware settings and control.
BIOS storage Information
BIOS chips are mainly stored:
Self-diagnosis program: Read the content in CMOSRAM to Identify hardware configurations and perform self-check and initialization;
CMOS setup program: starts the program with a special hotkey during the boot process, sets it, and stores it in cmos ram;
System bootstrap loader: After the self-check is successful, the boot program on the disk relative to 0 sectors and 0 sectors are loaded into the memory, so that the boot program runs to load the dossystem;
Drivers and interrupt services for major I/O devices: Because BIOS directly deals with system hardware resources, it is always targeted at a certain type of hardware system, and various hardware systems are different, there are various BIOS types. With the development of hardware technology, different versions of the same BIOS have emerged. The new version of BIOS is more powerful than the old version.
BIOS: After the computer power-on self-check is completed, the first read point is BIOS (Basic Input Output System, Basic Input Output System). The BIOS records the chip set and related settings of the motherboard, such as the communication frequency between the CPU and the interface device, the search sequence of the Startup Device, hard disk information, system time, memory information, clock information, PnP features, external bus, and I/ O address, IRQ interrupt information that has been communicated with the CPU, therefore, to enable the system smoothly, read the BIOS settings first.
The computer first loads the BIOS information, which is so important that the computer must find it at the very beginning.
After the computer is started, the CPU logic circuit is designed to run only programs in the memory, and cannot directly run the operating system in the floppy disk or hard disk, it must be loaded into the memory (RAM.
How does BIOS start?
The hardware logic of the CPU is designed to forcibly set the CS value to 0XF000 and the IP address to 0XFFF0 during power-on. In this way, CS: IP points to 0XFFFF0, which is the entry address of the BIOS program.
BIOS needs to load the interrupt vector table and interrupt service program in memory
The BIOS program is solidified into a very small ROM chip on the computer motherboard. Now CS: the IP address has been directed to the 0XFFFF0 position, which means that the BIOS starts to start. With the execution of the BIOS program, the screen will display the video card information, memory information, indicating that the BIOS program is detecting the video card, memory, this isPOST power-on self-check period, There is a task that is vital to starting the operating system, that isBIOS establishes a medium disconnection table and interrupt service programs in the memory
The BIOS program uses 1 kb of memory space (0x00000 ~ 0x003FF) Build the interrupt vector table, and build the BIOS data zone (0x00400 ~ 0x004FF), and some interrupt service programs corresponding to the interrupt vector table about 8 KB are loaded after about 57KB (0x0e05b.
The interrupt vector table has 256 interrupt vectors, each of which occupies 4 bytes, two of which are CS values and two of which are IP values. Each interrupt vector points to a specific interrupt service program.
BIOS phase work POST boot self-check
The BIOS program first checks whether the computer hardware meets the basic operating conditions. This is called "Hardware Self-Test" (POST.
If there is a hardware problem, the motherboard will beep with different meanings and start to stop. If no problem occurs, the screen displays information such as CPU, memory, and hard disk.
When the computer host is powered on, a drop will be heard, and the system starts the POST-power on self test self-check)
In this process, it mainly checks whether the computer hardware devices such as CPU, memory, motherboard, video card, and CMOS are faulty.
If there is a hardware fault, there will be two reasons:
Serious Faults (fatal faults) are shut down. At this time, no prompt or signal is given because various initialization operations have not been completed;
For non-serious faults, a prompt or sound alarm signal is provided, waiting for the user to handle). If there is no fault, POST the complete relay task and hand over the tail work to the BIOS for processing.
Load BIOS
The BIOS transfers control to the Startup Program of the next stage.
In this case, the BIOS needs to know which device the next phase of the Startup Program is stored in. That is to say, the BIOS needs to sort an external storage device. The device that comes first is the device that gives priority to control. This sort is called Boot Sequence ).
Open the BIOS operation interface, which contains "set startup sequence ".
After that, the computer will be aware of which hardware device should be read.
Boot Operating System
After the hardware self-check is completed, we hope to enable the operating system. But the problem arises.
* Where is the operating system stored?
* How does the BIOS find the operating system?
* How does the BIOS load the operating system?
Background Startup sequence for multiple operating systems
In order to find the operating system, the BIOS forwards control to the first storage device in the "Startup order.
In this case, the computer reads the first sector of the device, that is, the first 512 bytes.
If the last two bytes of the 512 bytes are 0x55 and 0xAA, the device can be used for startup;
If not, it indicates that the device cannot be used for startup, and the control is transferred to the next device in the startup sequence.
The first 512 bytes are calledMaster boot record)
Master Boot Record MBR
The Main boot loader in MBR is a 512-byte image, which not only contains program code, but also contains a small partition table.
The first 446 bytes are the main boot loader, which contains executable code and error message text. The next 64 bytes is a partition table, which contains records of the four partitions (each partition occupies 16 bytes ). MBR uses a special number 0xAA55 (note: in the electronics industry, AA55 is indeed a legend. Do you want to know why? Expand it into a binary form to see what is the rule) as the end sign of two bytes. 0x55AA is also an effective validation for MBR.
The work of the Main boot loader is to find and load the boot loader. It analyzes the partition table and finds the active partition to complete this task. When it finds an active partition, it continues to scan the partitions in the remaining partition table to confirm that they are not activated. After confirmation, the activation record of the active partition is read from the device RAM and executed.
The "primary Boot Record" contains only 512 bytes, which cannot be put too much. It is mainly used to tell the computer where to find the operating system from the hard disk.
The Master Boot Record consists of three parts:
Bytes 1-446: The machine code that calls the operating system.
Bytes 447-510: Partition table ).
511-512 Bytes: Signature of the Master Boot Record (0x55 and 0xAA ).
The second part "partition table" is used to divide the hard disk into Several partitions.
Partition Table
Hard Disk partitioning has many advantages. Considering that different operating systems can be installed in each zone, the "Master Boot Record" must know which zone the control is transferred. The partition table is only 64 bytes in length and is divided into four items, each of which is 16 bytes. Therefore, a hard disk can be divided into up to four primary partitions, also known as "primary partition ".
The 16 bytes of each primary partition are composed of six parts:
1st Bytes: If it is 0x80, it indicates that the primary partition is an active partition, and the control is transferred to the partition. Only one of the four primary partitions can be activated.
2-4 Bytes: the physical location of the first slice in the primary partition (cylindrical, Head, sector number, and so on ).
5th Bytes: Primary partition type.
6-8 Bytes: the physical location of the last slice of the primary partition.
9-12 Bytes: The Logical Address of the first sector of the primary partition.
13-16 bytes: Total number of sectors in the primary partition.
The last four bytes ("the total number of sectors in the primary partition") determine the length of the primary partition. That is to say, the total number of sectors in a primary partition cannot exceed 2 to the power of 32.
If each slice is 512 bytes, it means that a single partition cannot exceed 2 TB. Considering that the logical address of the slice is also 32 bits, the maximum available space of a single hard disk cannot exceed 2 TB.
To use a larger hard disk, there are only two methods:
First, increase the number of bytes for each slice,
Second, increase the total number of sectors.
MBR: The primary boot partition in the first sector of the device that can be started. It contains a boot loader.
Boot loader: a software that can read kernel files for execution.
Kernel File: Start the Operating System Function
Operating System Boot Process
When a hard disk is started, the BIOS is usually the first sector of the first hard disk, that is, the Master Boot Record (MBR ).
The process of loading GRUB and the operating system includes the following steps:
Load records
The only thing the basic bootstrap loader does is load the second bootstrap loader.
Load Grub
This second bootstrap loader actually introduces more advanced features to allow users to load a specific operating system.
Loading System
Such as Linux kernel. GRUB transfers control of the machine to the operating system.
The difference is that the Microsoft operating system uses a bootstrap method called chain loading to start. The primary Bootstrap record simply points to the first sector of the partition where the operating system is located.
Load the Main Boot Loader-Basic Loader
As we all know, the first sector of the 0th track on the hard disk is called MBR, that is, Master Boot Record, that is, the Master Boot Record. Its size is 512 bytes, you can store the pre-start information and partition table information.
Start the program on the first device according to the system Boot process set by the BIOS. If the detection succeeds, start the program according to the Boot Sequence, our boot devices mainly include hard disks, USB, SD, etc. We usually use hard disks, and then read the first device as hard disks, the first one to read is the Master Boot Record MBR (Master Boot Record) of the hard disk. Then, the system can follow the Boot Loader installed in the Boot zone) start to perform core recognition.
The MBR program only finds the Boot Loader with the first 446 bytes in the hard disk partition, and then finds the relevant configurations and definitions.
Then, the control is handed over to the Master Guide code. The tasks of the main Bootstrap Code include:
Scan the partition table and find an active (bootable) partition;
Locate the start sector of the active partition;
Load the Boot Sector of the active partition to the memory at 7C00;
Give control to the Boot Sector Code;
Loader-advanced loader bootload such as GRUB
The System reads grub configuration information (generally menu. lst or grub. lst) in the memory and starts different operating systems according to the configuration information.
At this time, the control of the computer will be transferred to a partition of the hard disk, which is divided into three situations.
Case A: volume boot records
As mentioned in the previous section, only one of the four primary partitions is active. The computer reads the first sector of the active partition, which is called the Volume boot record (VBR ).
The main function of volume Boot Record is to tell the computer where the operating system is located in this partition. Then, the computer will load the operating system.
Case B: Extended partitions and logical partitions
As the hard disk grows, four primary partitions are insufficient and more partitions are needed. However, there are only four partition tables, so there is a rule that only one partition can be defined as an Extended partition ). The so-called "extended partition" means that the partition is divided into multiple zones. The partition in this type of partition is called "logical partition ).
The computer first reads the first sector of the Extended partition, called Extended boot record (EBR ). It also contains a 64-byte partition table, but there are only two items at most (that is, two logical partitions ).
The computer then reads the first sector of the second logical partition, finds the location of the third logical partition from the partition table, and so on, until the partition table of a logical partition only contains itself (that is, there is only one partition item ). Therefore, extended partitions can contain countless logical partitions.
However, it seems that the operating system is rarely started in this way. If the operating system is indeed installed in the extended partition, it is generally started in one of the following ways.
Case C: Start the manager
In this case, after the computer reads the machine code of the first 446 bytes of the "Master Boot Record", it no longer transfers control to a partition, instead, run the pre-installed boot loader. The user selects which operating system to start.
In Linux, Grub is the most popular startup manager.
Boot Loader is a small program that runs before the operating system kernel runs. Through this small program, we can initialize hardware devices and build a map of memory space to bring the system's hardware and software environment to a suitable state, in order to make all preparations for the final call to the operating system kernel.
There are several Boot loaders, among which Grub, Lilo, and spfdisk are common loaders.
Let's take Grub as an example. After all, there are not many people using lilo and spfdisk.
Why is it so complicated?
The early operating systems were not that complex, and of course bootload was not that versatile, but now our operating systems are becoming more and more complex and bootload is also growing, and now it is so common to install multiple systems on a computer, so simple bootload can no longer meet these features.
Both BIOS and MBR are functions supported by hardware. As for Boot Loader, the operating system is a set of software installed on MBR. Since MBR only has 446bytes, this boot loader is very small and perfect. The main tasks of this BootLoader are as follows:
Menu provided: users can choose different boot options, which is also an important feature of Multi-boot.
Load the Kernel File: directly point to the boot program segment to start the operating system.
Transfer another Loader: transfers the bootstrap load function to another loader.
The first two points above are easy to understand, but the third point is very interesting! That means you can have more than two boot loader programs in your computer system. Is it possible? Isn't our hard disk just an MBR? However, in addition to MBR, the boot loader can also be installed in the boot sector of each partition.
For example, assume that your PC has only one hard disk, which is divided into four partitions. First, Windows and Linux are installed in the binary zone. How do you choose to start Windows or Linux at startup? Assuming that the MBR is installed with boot loader that can recognize both Windows and Linux operating systems, the entire process is as follows:
The summary is as follows:
Each partition has its own startup sector.
The system partition is the first and second partitions.
The actual boot kernel files are placed in each partition.
Loader only recognizes the boot kernel files in its system partition and other loaders.
Loader can direct or indirectly hand the management right to another Management Program
Now, why do people often say, "If you want to install multiple boot methods, you 'd better install Windows before installing Linux"?
This is because during Linux installation, you can choose to install the boot Loader in MBR or the startup sector of individual partitions, And the Linux Loader can manually set the menu, therefore, you can add the Windows Boot option to the Linux Boot Loader.
During Windows installation, his installer will take the initiative to overwrite the MBR and the startup sector of the partition where he is located. You have no chance to choose, and he has not asked us to choose the menu function.
Load operating system kernel
After you select the kernel to be loaded, the next boot Loader (GRUB) will be based on/boot/grub. the information set in the conf configuration file reads the Linux kernel image from the/boot/partition, loads the kernel image to the memory, and gives control to the Linux kernel.
After the Linux kernel obtains control, it starts to do its own work.
* Hardware Detection
Decompress yourself and install necessary drivers
Initialize Virtual Devices related to the file system, LVM or RAID
Load the root file system and mount it under the root directory
After the process is completed, linux loads the init program in the process space, and the next task is init.
Based on the path of the kernel image set by grub, the system reads the memory image and decompress it. At this time, the screen will usually output the "Uncompressing Linux" prompt. After the kernel is decompressed, the screen outputs "OK, booting the kernel ".
The system places the decompressed kernel in the memory, and calls the start_kernel () function to start a series of initialization functions and initialize various devices to complete the establishment of the Linux core environment. So far, the Linux kernel has been established, and the Linux-based program should be able to run normally.
Step 5 -- User-layer init sets the running level based on the inittab File
After the kernel is loaded, the first program to run is/sbin/init, which reads the/etc/inittab file and initializes the file based on the file.
In fact, the main function of the/etc/inittab file is to set the Linux running level. The setting format is ": id: 5: initdefault :", this indicates that Linux needs to run on level 5. The Linux operating level is set as follows:
0: Shutdown
1: single-user mode
2: multi-user mode without network support
3: multi-user mode with network support
4: reserved, not used
5. Multi-user mode with network support and X-Window support
6. reboot the system.
There are still a lot of knowledge about the/etc/inittab file.
The init process executes rc. sysinit.
After the running level is set, the first user-layer file executed by Linux is/etc/rc. d/rc. the sysinit script program does a lot of work, including setting PATH, setting network configuration (/etc/sysconfig/network), starting swap partitions, and setting/proc. If you are interested, you can check the rc. sysinit file in/etc/rc. d. The script in it is enough for a few days.
Start the kernel module
The kernel module is loaded Based on the/etc/modules. conf file or the file in the/etc/modules. d directory.
Execute script programs of different running levels
Depending on the running level, the system will run the corresponding script programs from rc0.d to rc6.d to complete the initialization and start the corresponding service.
Run/etc/rc. d/rc. local.
If you open this file, there is a sentence in it. After reading it, you will see the role of this command at a Glance:
# This script will be executed *after* all the other init scripts.# You can put your own initialization stuff in here if you don’t# want to do the full Sys V style init stuff.
Rc. local is a place for users to personalize Linux after all initialization work. You can put what you want to set and start here.
Run the/bin/login program to enter the logon status.
Now, the system has entered the waiting time for the user to enter username and password. You can use your account to log on to the system. :)