Document directory
- 1. kernel startup address
- 2. kernel Startup Process Analysis
Linux Kernel startup Analysis
1. kernel startup address 1.1. Glossary
Ztextaddr
Extract the start address of the Code. There is no physical address or virtual address, because MMU is disabled at this time. The RAM address may be a storage medium such as flash that supports read/write addressing.
Start address of decompressor. here's no point in talking about virtual or physical addresses here, since the MMU will be off at the time when you call the decompressor code. you normally call the kernel at this address to start it booting. this doesn't have to be located in Ram, it can be in flash or other read-only or read-write addressable medium.
Zreladdr
The address of the kernel startup in Ram. The compressed kernel image is extracted to this address and then executed.
This is the address where the decompressed kernel will be written, and eventually executed. The following constraint must be valid:
_ Pai_to_phys (textaddr) = zreladdr
The initial part of the kernel is carefully coded to be position independent.
Textaddr
The virtual address of kernel startup, which corresponds to zreladdr. Generally, the virtual address started by the kernel is 0x8000 added to the First Bank address of RAM.
Textaddr = page_offset + textoffst
Virtual start address of kernel, normally page_offset + 0x8000. this is where the kernel image ends up. with the latest kernels, it must be located at 32768 bytes into a 128 MB region. previous kernels placed a restriction of 256 MB here.
Textoffset
Kernel offset address. Set in arch/ARM/makefile.
Phys_offset
The physical start address of the First Bank of RAM.
Physical start address of the First Bank of RAM.
Page_offset
The virtual start address of the First Bank of RAM.
Virtual start address of the First Bank of Ram. During the kernel
Boot phase, virtual address page_offset will be mapped to physical
Address phys_offset, along with any other mappings you supply.
This shoshould be the same value as task_size.
1.2. Check the kernel startup address
The boot address of the kernel is determined by BOOTP. LDS. BOOTP. LDS: ARCH/ARM/Bootp
Output_arch (ARM)
Entry (_ start)
Sections
{
. = 0;
. Text :{
_ Stext = .;
* (. Start)
* (. Text)
Initrd_size = initrd_end-initrd_start;
_ Etext = .;
}
}
From top. = 0, you can determine that the start address of the decompressed code is 0x0. The value of ztextaddr determines this value.
Makefile: ARCH/ARM/boot/compressed
If you set the kernel to start from Rom, you can set the start address of the decompressed code on the make menuconfig configuration interface. Otherwise, the start address of the decompressed code is 0x0. In fact, the start address of the decompressed code is 0x0 by default when starting from Rom.
Feq ($ (config_zboot_rom), Y)
Ztextaddr: = $ (config_zboot_rom_text)
Zbssaddr: = $ (config_zboot_rom_bss)
Else
Ztextaddr: = 0 zbssaddr: = align (4)
Endif
Sedflags = s/text_start/$ (ztextaddr)/; S/bss_start/$ (zbssaddr )/
......
$ (OBJ)/vmlinux. LDS: $ (OBJ)/vmlinux. LDS. In ARCH/ARM/mach-s3c2410/makefile. config
@ Sed "$ (sedflags)" <$ <>$ @
@ Sed "$ (sedflags)" <$ <> $ @ the rule sets text_start to ztextaddr. Text_start is used in arch/ARM/boot/compressed/vmlinux. LDS. In to set the start address of the decompressed code.
Output_arch (ARM)
Entry (_ start)
Sections
{
. = Text_start;
_ Text = .;
. Text :{
_ Start = .;
* (. Start)
* (. Text)
* (. Text .*)
......
}
}
Kernel compilation relies on vmlinux. LDS. vmlinux. LDS is generated by vmlinux. LDS. S. The following code shows that the virtual address of kernel startup is set to page_offset + text_offset, and the physical address of kernel startup zreladdr is set in arch/ARM/boot/makefile.
Output_arch (ARM)
Entry (stext)
Sections
{
# Ifdef config_xip_kernel
. = Xip_virt_addr (config_xip_phys_addr );
# Else
. = Page_offset + text_offset;
# Endif
. Init: {/* init code and Data */
_ Stext = .;
_ Sinittext = .;
* (. Init. Text)
_ Einittext = .;
......
}
}
# Arch/ARM/boot/makefile
# Note: The following conditions must always be true:
# Zreladdr = pai_to_phys (page_offset + text_offset)
# Params_phys must be within 4 MB of zreladdr
# Initrd_phys must be in Ram
Zreladdr: = $ (zreladdr-y)
# ---> Zrealaddr-y is specified with 0x30008000 in arch/ARM/boot/makefile. boot
Params_phys: = $ (params_phys-y)
Initrd_phys: = $ (initrd_phys-y)
Export zreladdr initrd_phys params_phys
Run the following command to compile the kernel image. The entry address of-a and-E is set to zreladdr, which is specified in zreladdr :=$ (zreladdr-Y.
Quiet_pai_uimage = uimage $ @
Export _uimage = $ (config_shell) $ (mkimage)-A arm-O Linux-T kernel/
-C none-A $ (zreladdr)-E $ (zreladdr )/
-N'linux-$ (kernelrelease) '-d $ <$ @
1.3. Summary
From the above analysis, we can know that after the Linux kernel is copied to ram by bootloader, the decompressed code starts to run from ztextaddr (this code is a location-independent pic ). The kernel is decompressed to zrealaddr, that is, the physical address of the kernel startup. Correspondingly, the virtual address of kernel startup is set to textaddr, which meets the following conditions:
Textaddr = page_offset + text_offset
The physical and virtual addresses of kernel startup meet the following conditions:
Zreladdr = pai_to_phys (page_offset + text_offset) = pai_to_phys (textaddr)
Assume that the Development Board is smdk2410:
Virtual Address of kernel startup
Textaddr = 0xc0008000
Physical address of kernel startup
Zreladdr = 0x30008000
If it is started directly from flash, you also need to set the ztextaddr address.
2. kernel Startup Process Analysis
The kernel startup process is divided into two phases: Kernel Image Self-boot and kernel sub-module initialization.
2.1. kernel Image Self-boot
The main task at this stage is to decompress the compressed kernel and enter the kernel code entry.
After bootloader completes system boot, the kernel image is transferred to the physical address ztextaddr specified by the memory. A typical kernel image consists of a self-boot program and a compressed vmlinux. Therefore, you need to decompress the kernel before starting the kernel. The first code at the kernel image entry is the self-guided program. It is in the arch/ARM/boot/compressed/head. s file.
The main function of the head. s file is to decompress the compressed kernel and jump to the kernel vmlinux kernel entry. Decompress_kernel (): ARCH/ARM/boot/compressed/Misc. C and call_kernel functions implement the above functions. Before calling decompress_kernel () to decompress the kernel, make sure that the decompressed kernel code does not overwrite the original kernel image. And set the kernel code entry address zrealaddr.
. Text
ADR r0, lc0
Ldmia r0, {R1, R2, R3, R4, R5, R6, IP, SP}
. Type lc0, # object
Lc0:. Word lc0 @ r1
. Word _ bss_start @ r2
. Word _ end @ r3
. Word zreladdr @ r4
. Word _ start @ R5
. Word _ got_start @ R6
. Word _ got_end @ IP
. Word user_stack + 4096 @ sp
The above code gets the entry address of the kernel code, which is saved in R4.
/*
* Check to see if we will overwrite ourselves.
* R4 = final kernel address
* R5 = start of this image
* R2 = end of malloc space (and therefore this image)
* We basically want:
* R4> = R2-> OK
* R4 + image length <= R5-> OK
*/
CMP R4, r2
BHS wont_overwrite
Add r0, R4, #4096*1024 @ 4 MB largest kernel size
CMP r0, R5
BLS wont_overwrite
MoV R5, R2 @ decompress after malloc Space
MoV r0, R5
MoV R3, r7
BL decompress_kernel
B call_kernel
The code above checks whether the extracted kernel code will overwrite the original kernel image, and then calls the kernel decompression function decompress_kernel ().
Ulg
Decompress_kernel (ulg output_start, ulg free_mem_ptr_p, ulg free_mem_ptr_end_p,
Int arch_id)
{
Output_data = (UCH *) output_start;/* specify the kernel execution address and save it in R4 */
Free_mem_ptr = free_mem_ptr_p;
Free_mem_ptr_end = free_mem_ptr_end_p;
_ Machine_arch_type = arch_id;
Arch_decomp_setup ();/* initialize and set before decompression, including serial port baud rate settings */
Makecrc ();/* CRC check */
Putstr ("Uncompressing Linux ...");
Gunzip ();/* call the extract function */
Putstr ("done, booting the kernel./N ");
Return output_ptr;
}
Decompress the kernel image to the zeraladdr address, and call the call_kernel function to enter the kernel code entry address.
Call_kernel: BL cache_clean_flush
BL cache_off
MoV r0, #0 @ must be zero
MoV R1, R7 @ restore architecture number
MoV R2, R8 @ restore atags pointer
MoV PC, R4 @ call Kernel
We know that the kernel execution address is saved in the R4 register. mov PC and R4 point the program pointer to the kernel execution address, so the following will enter the kernel code execution stage.
2.2. Initialization of Linux kernel submodules 2.2.1. Preparations
Enter the real kernel code. The first execution is a file called head. S (ARCH/ARM/kernel. Head. s also contains the head-common.S (ARCH/ARM/kernel/) in the same directory /). These two files are mainly responsible for the following work:
Determine the CPU type and check whether the running cpu id and Linux compilation support the ID.
Determine the system type and check whether the architecture type value of the R1 register is supported
Create a page table
Enable MMU
Jump to start_kernel () (kernel sub-module initialization program)
Note: The subprograms are not analyzed in detail for the moment.
2.2.2. kernel submodule Initialization
The start_kernel function is a common initialization function of the Linux kernel. This function is required for Linux regardless of the architecture. The start_kernel () function is the basic process of kernel initialization. The following describes the initialization sequence of the kernel module based on the function.
Asmlinkage void _ init start_kernel (void)
{
Char * command_line;
Extern struct kernel_param _ start ___ Param [], _ Stop ___ Param [];
Smp_setup_processor_id ();/* specifies the logic Number of the current CPU. This function corresponds to the setting of symmetric multi-processor. This function is empty when there is only one CPU in the system, do nothing */
Lockdep_init ();/* initialize the lockdep hash table */
/* Initialize IRQ */
Local_irq_disable ();
Early_boot_irqs_off ();
Early_init_irq_lock_class ();
/* Lock the kernel, set the CPU status to 'present', 'online', initialize the page table, print the kernel version number, set the architecture, and allocate startup memory space for the CPU, the interruption is still disabled during this period */
Lock_kernel ();
Boot_cpu_init ();
Page_address_init ();
Printk (kern_notice );
Printk (linux_banner );
Setup_arch (& command_line );
Setup_per_cpu_areas ();
Smp_prepare_boot_cpu ();/* arch-specific boot-CPU hooks */
/* Open the scheduler before opening any interruptions */
Sched_init ();
/* Disable the task preemption function because the early schedulers were weak until cpu_idle () was called for the first time ()*/
Preempt_disable ();
/* Create a linked list node in the memory area. For a single CPU node, the number of nodes is 1 */
Build_all_zonelists ();
/* Send a notification to each CPU to process the memory status of each CPU */
Page_alloc_init ();
/* No command parameters in the early stage of analysis */
Printk (kern_notice "kernel command line: % s/n", saved_command_line );
Parse_early_param ();
/* Analyze command parameters */
Parse_args ("booting kernel", command_line, _ start ___ Param,
_ Stop ___ param-_ start ___ Param,
& Unknown_bootoption );
/* Sort the exception table created by the kernel */
Sort_main_extable ();
Unwind_init ();
/* Set trap and interrupt doors */
Trap_init ();
/* Initialize the read-copy-Update (read-copy-update RCU) subsystem in the kernel */
Rcu_init ();
/* Initialize IRQ */
Init_irq ();
/* Initialize the PID hash table based on the physical memory on the Development Office */
Pidhash_init ();
/* Initialize the timer */
Init_timers ();
/* High-Resolution & High-precision timer initialization */
Hrtimers_init ();
/* Initialize Soft Interrupt */
Softirq_init ();
/* Initialize the value of the clock resource and common timer */
Timekeeping_init ();
/* Initialize the system time */
Time_init ();
/* Allocate memory for the kernel to store collected data */
Profile_init ();
/* Open interrupt */
If (! Irqs_disabled ())
Printk ("start_kernel (): Bug: interrupts were enabled early/N ");
Early_boot_irqs_on ();
Local_irq_enable ();
/*
* Hack alert! This is early. We're re enabling the console before
* We 've done PCI setups etc, and console_init () must be aware
* This. But we do want output early, in case something goes wrong.
*/
/* Initialize the console. In order to help with debugging as early as possible, display the system boot information */
Lele_init ();
If (panic_later)
Panic (panic_later, panic_param );
/* If the config_lockdep macro is defined, the lock dependency information is printed; otherwise, nothing is done */
Lockdep_info ();
/*
* Need to run this when irqs are enabled, because it wants
* To self-test [Hard/soft]-irqs On/Off lock inversion bugs
* Too:
*/
/* If the config_debug_locking_api_selftests macro is defined, locking_selftest () is an empty function. Otherwise, the locks are automatically tested */
Locking_selftest ();
# Ifdef config_blk_dev_initrd
If (initrd_start &&! Initrd_below_start_ OK &&
Initrd_start <min_low_pfn <page_shift ){
Printk (kern_crit "initrd overwritten (0x % 08lx <0x % 08lx )-"
"Disabling it./N", initrd_start, min_low_pfn <page_shift );
Initrd_start = 0;
}
# Endif
/*
(1) dcache_init () creates an slab cache, which stores the directory item descriptor. Stored data is called dentry_cache. When a process accesses a file or directory, the directory name involved consists of multiple directory components. The directory item descriptor is created for each component. The structure of each directory item combines the file or directory component with its index node, so that you can quickly find the corresponding index node through this directory item
(2) inode_init () initializes the hash table index node and waits for the queue to be matched. This header stores the hash index node to be locked by the kernel.
(3) file_init () determines the maximum amount of memory allocated to each zhogn file for each process.
(4) mnt_init () creates a cache that stores the vfsmount object and is named mnt_cache. VFS uses this pair to attach it to the file system. This routine also creates a mount_hashtable queue, which stores the fast access objects referenced in mnt_cache. Then the routine sends a call to initialize the sysfs file system and mount the root file system.
*/
Vfs_caches_init_early ();
Cpuset_init_early ();
/* The mem_init () function marks the Free Zone in mem_map and prints the free memory size. This function is executed after all parts of the system have applied for memory */
Mem_init ();
/* Initialize the cache-related linked list. The function is executed before smp_init () after the page table distributor is initialized */
Kmem_cache_init ();
/* Indicates the CPU initialization page with the logic number 0. In the case of SMP, as long as the CPU performance is online, this function will execute */
Setup_per_cpu_pageset ();
/* NUMA memory policyholder initialization */
Numa_policy_init ();
/* Called after memory initialization */
If (late_time_init)
Late_time_init ();
/* Calculate and print many well-known "bogomips" values, which measure the number of delay () that can be repeatedly executed by the processor in a clock cycle (). for processors with different speeds, cali_brate_delay () allows about the same latency */
Calibrate_delay ();
/* Initialize pidmap_array and assign pid = 0 to the current process */
Pidmap_init ();
/* Initialize the page table high-speed cache */
Pgtable_cache_init ();
/* Initialize the priority tree index_bits_to_maxindex array */
Prio_tree_init ();
/* Create an anon_vma structure object slab cache */
Anon_vma_init ();
# Ifdef config_x86
If (efi_enabled)
Efi_enter_virtual_mode ();
# Endif
/* Create the user buffer uid_cache based on the available memory size, initialize the maximum number of threads max_threads, and configure rlimit_nproc for init_task as max_threads/2 */
Fork_init (num_physpages );
/* Create various block buffers, such as VFS and Vm */
Proc_caches_init ();
Buffer_init ();
Unnamed_dev_init ();
Key_init ();
Security_init ();
Vfs_caches_init (num_physpages );
Radix_tree_init ();
Signals_init ();
/* Rootfs populating might need page-writeback */
Page_writeback_init ();
# Ifdef config_proc_fs
Proc_root_init ();
# Endif
Cpuset_init ();
Taskstats_init_early ();
Delayacct_init ();
/* Check errors are actually caused by calling the check_writebuffer_bugs () function to check whether physical address obfuscation exists */
Check_bugs ();
/* Advanced Configuration and power management interface */
Acpi_early_init ();/* Before lapic and SMP init */
/* Do the rest non-_ init 'ed, we're now alive */
/* Create the INIT process, delete the kernel lock, and start the idle thread */
Rest_init ();
}
After the INIT process is started, the init () function is executed to complete the INIT process of mounting the root file system, initializing the device driver, and starting the user space. (Sunny is responsible for this part)