Next Previous Contents

5. Linux architecture-independent initialization

(from "linux/init/main.c")

"linux/init/main.c" begins execution with the start_kernel() function, which is called from "linux/arch/i386/kernel/head.S". start_kernel() never returns to its caller. It ends by calling the cpu_idle() function.

5.1 start_kernel:

Interrupts are still disabled. Do necessary setups, then enable them.

Lock the kernel (BKL: big kernel lock).

Print the linux_banner string (this string resides in "linux/init/version.c") using printk(). NOTE: printk() doesn't actually print this to the console yet; it just buffers the string until a console device registers itself with the kernel, then the kernel passes the buffered console log contents to the registered console device(s). There can be multiple registered console devices.

********** printk() can be called very early because it doesn't actually print to anywhere. It just logs the message to "log_buf", which is allocated statically in "linux/kernel/printk.c". The messages that are saved in "log_buf" are passed to registered console devices as they register. **********

More architecture-specific init

Call setup_arch(&command_line):

This performs architecture-specific initializations (details below). Then back to architecture-independent initialization....

The remainder of start_kernel() is done as follows for all processor architecures, although several of these function calls are to architecture-specific setup/init functions.

Continue architecture-independent init

Print the kernel command line.

Parsing command line options

parse_options(command_line): Parse the kernel options on the command line. This is a simple kernel command line parsing function. It parses the command line and fills in the arguments and environment to init (thread) as appropriate. Any command-line option is taken to be an environment variable if it contains the character '='. It also checks for options meant for the kernel by calling checksetup(), which checks the command line for kernel parameters, these being specified by declaring them using "__setup", as in:



__setup("debug", debug_kernel);

This declaration causes the debug_kernel() function to be called when the string "debug" is scanned. See "linux/Documentation/kernel-parameters.txt" for the list of kernel parameters.

These options are not given to init -- they are for internal kernel use only. The default argument list for the init thread is {"init", NULL}, with a maximum of 8 command-line arguments. The default environment list for the init thread is {"HOME=/", "TERM=linux", NULL}, with a maximum of 8 command-line environment variable settings. In case LILO is going to boot us with default command line, it prepends "auto" before the whole cmdline which makes the shell think it should execute a script with such name. So we ignore all arguments entered _before_ init=... [MJ]

trap_init

(in linux/arch/i386/kernel/traps.c)

Install exception handlers for basic processor exceptions, i.e., not hardware device interrupt handlers.

Install the handler for the system call software interrupt.

Install handlers for lcall7 (for iBCS) and lcall27 (for Solaris/x86 binaries).

Call cpu_init() to do:

init_IRQ

(in linux/arch/i386/kernel/i8259.c)

Call init_ISA_irqs() to initialize the two 8259A interrupt controllers and install default interrupt handlers for the ISA IRQs.

Set an interrupt gate for all unused interrupt vectors.

For CONFIG_SMP configurations, set up IRQ 0 early, since it's used before the IO APIC is set up.

For CONFIG_SMP, install the interrupt handler for CPU-to-CPU IPIs that are used for the "reschedule helper."

For CONFIG_SMP, install the interrupt handler for the IPI that is used to invalidate TLBs.

For CONFIG_SMP, install the interrupt handler for the IPI that is used for generic function calls.

For CONFIG_X86_LOCAL_APIC configurations, install the interrupt handler for the self-generated local APIC timer IPI.

For CONFIG_X86_LOCAL_APIC configurations, install interrupt handlers for spurious and error interrupts.

Set the system's clock chip to generate a timer tick interrupt every HZ Hz.

If the system has an external FPU, set up IRQ 13 to handle floating point exceptions.

sched_init

(in linux/kernel/sched.c)

time_init

(in linux/arch/i386/kernel/time.c)

Initialize the system's current time of day (xtime) from CMOS.

Install the irq0 timer tick interrupt handler.

softirq_init

(in linux/kernel/softirq.c)

console_init

(in linux/drivers/char/tty_io.c)

HACK ALERT! This is early. We're enabling the console before we've done PCI setups etc., and console_init() must be aware of this. But we do want output early, in case something goes wrong.

init_modules

(in linux/kernel/module.c)

For CONFIG_MODULES configurations, call init_modules(). This initializes the size (or number of symbols) of the kernel symbol table.

Profiling setup

if profiling ("profile=#" on the kernel command line): calculate the kernel text (code) profile "segment" size; calculate the profile buffer size in pages (round up); allocate the profile buffer: prof_buffer = alloc_bootmem(size);

kmem_cache_init

(in linux/mm/slab.c)

sti

********** Interrupts are now enabled. **********
This allows "calibrate_delay()" (below) to work.

calibrate_delay

Calculate the "loops_per_jiffy" delay loop value and print it in BogoMIPS.

INITRD setup


#ifdef CONFIG_BLK_DEV_INITRD

        if (initrd_start && !initrd_below_start_ok &&
                        initrd_start < (min_low_pfn << PAGE_SHIFT)) {
                printk("initrd overwritten (initrd_start < (min_low_pfn << PAGE_SHIFT)) - disabling it.\n");
                initrd_start = 0;       // mark initrd as disabled
        }

#endif /* CONFIG_BLK_DEV_INITRD */

mem_init

(in linux/arch/i386/mm/init.c)

********** get_free_pages() can be used after mem_init(). **********

kmem_cache_sizes_init

(in linux/mm/slab.c)

Set up remaining internal and general caches. Called after the "get_free_page()" functions have been enabled and before smp_init().

********** kmalloc() can be used after kmem_cache_sizes_init(). **********

proc_root_init

(in linux/fs/proc/root.c)

For CONFIG_PROC_FS configurations:

mempages = num_physpages;

fork_init(mempages)

(in linux/kernel/fork.c)

The default maximum number of threads is set to a safe value: the thread structures can take up at most half of memory.

proc_caches_init()

(in linux/kernel/fork.c)

Call kmem_cache_create() to create slab caches for signal_act (signal action), files_cache (files_struct), fs_cache (fs_struct), vm_area_struct, and mm_struct.

vfs_caches_init(mempages)

(in linux/fs/dcache.c)

Call kmem_cache_create() to create slab caches for buffer_head, names_cache, filp, and for CONFIG_QUOTA, dquot.

Call dcache_init() to create the dentry_cache and dentry_hashtable.

buffer_init(mempages)

(in linux/fs/buffer.c)

Allocate the buffer cache hash table and init the free list.
Use get_free_pages() for the hash table to decrease TLB misses; use SLAB cache for buffer heads.
Setup the hash chains, free lists, and LRU lists.

page_cache_init(mempages)

(in linux/mm/filemap.c)

Allocate and clear the page-cache hash table.

kiobuf_setup()

(in linux/fs/iobuf.c)

Call kmem_cache_create() to create the kernel iobuf cache.

signals_init()

(in linux/kernel/signal.c)

Call kmem_cache_create() to create the "sigqueue" SLAB cache.

bdev_init()

(in linux/fs/block_dev.c)

Initialize the bdev_hashtable list heads.

Call kmem_cache_create() to create the "bdev_cache" SLAB cache.

inode_init(mempages)

(in linux/fs/inode.c)

ipc_init()

(in linux/ipc/util.c)

For CONFIG_SYSVIPC configurations, call ipc_init().

The various System V IPC resources (semaphores, messages, and shared memory) are initialized.

dquot_init_hash()

(in linux/fs/dquot.c)

For CONFIG_QUOTA configurations, call dquot_init_hash().

check_bugs()

(in linux/include/asm-i386/bugs.h)

Start other SMP processors (as applicable)

smp_init() works in one of three ways, depending upon the kernel configuration.

For a uniprocessor (UP) system without an IO APIC (CONFIG_X86_IO_APIC is not defined), smp_init() is empty -- it has nothing to do.

For a UP system with (an) IO APIC for interrupt routing, it calls IO_APIC_init_uniprocessor().

For an SMP system, its main job is to call the architecture-specific function "smp_boot_cpus()", which does the following.

Start init thread

We count on the initial thread going OK.

Like idlers, init is an unlocked kernel thread, which will make syscalls (and thus be locked).


kernel_thread(init, NULL, CLONE_FS | CLONE_FILES | CLONE_SIGNAL);

{details below}

unlock_kernel()

Release the BKL.

current->need_resched = 1;

cpu_idle()

This function remains as process number 0. Its purpose is to use up idle CPU cycles. If the kernel is configured for APM support or ACPI support, cpu_idle() invokes the supported power-saving features of these specifications. Otherwise it nominally executes a "hlt" instruction.

{end of start_kernel()}

5.2 setup_arch

(in "linux/arch/i386/kernel/setup.c")

Copy and convert system parameter data

Copy and convert parameter data passed from 16-bit real mode to the 32-bit startup code.

For RAMdisk-enabled configs (CONFIG_BLK_DEV_RAM)

Initialize rd_image_start, rd_prompt, and rd_doload from the real-mode parameter data.

setup_memory_region

Use the BIOS-supplied memory map to setup memory regions.

Set memory limits

Set values for the start of kernel code, end of kernel code, end of kernel data, and "_end" (end of kernel code = the "brk" address).

Set values for code_resource start and end and data_resource start and end.

parse_mem_cmdline

Parse any "mem=" parameters on the kernel command line and remember them.

Setup Page Frames

Use the BIOS-supplied memory map to setup page frames.

Register available low RAM pages with the bootmem allocator.

Reserve physical page 0: "it's a special BIOS page on many boxes, enabling clean reboots, SMP operation, laptop functions."

Handle SMP and IO APIC Configurations

For CONFIG_SMP, reserve the page immediately above page 0 for stack and trampoline usage, then call smp_alloc_memory() to allocate low memory for AP processor(s) real mode trampoline code.

For CONFIG_X86_IO_APIC configurations, call find_smp_config() to find and reserve any boot-time SMP configuration information memory, such as MP (Multi Processor) table data from the BIOS.

paging_init()

paging_init() sets up the page tables - note that the first 8 MB are already mapped by head.S.

This routine also unmaps the page at virtual kernel address 0, so that we can trap those pesky NULL-reference errors in the kernel.

Save the boot-time SMP configuration

For CONFIG_X86_IO_APIC configurations, call get_smp_config() to read and save the MP table IO APIC interrupt routing configuration data.

For CONFIG_X86_LOCAL_APIC configurations, call init_apic_mappings().

Reserve INITRD memory

For CONFIG_BLK_DEV_INITRD configurations, if there is enough memory for the initial RamDisk, call reserve_bootmem() to reserve RAM for the initial RamDisk.

Scan for option ROMs

Call probe_roms() and reserve their memory space resource(s) if found and valid. This is done for the standard video BIOS ROM image, any option ROMs found, and for the system board extension ROM (space).

Reserve system resources

Call request_resource() to reserve video RAM memory.

Call request_resource() to reserve all standard PC I/O system board resources.

{end of setup_arch()}

5.3 init thread

The init thread begins at the init() function in "linux/init/main.c". This is always expected to be process number 1.

init() first locks the kernel and then calls do_basic_setup() to perform lots of bus and/or device initialization {more detail below}. After do_basic_setup(), most kernel initialization has been completed. init() then frees any memory that was specified as being for initialization only [marked with "__init", "__initdata", "__init_call", or "__initsetup"] and unlocks the kernel (BKL).

init() next opens /dev/console and duplicates that file descriptor two times to create stdin, stdout, and stderr files for init and all of its children.

Finally init() tries to execute the command specified on the kernel parameters command line if there was one, or an init program or script if it can find one in {/sbin/init, /etc/init, /bin/init}, and lastly /bin/sh. If init() cannot execute any of these, it panics ("No init found. Try passing init= option to kernel.")

5.4 do_basic_setup {part of the init thread}

The machine is now initialized. None of the devices have been touched yet, but the CPU subsystem is up and running, and memory and process management works.

Be the reaper of orphaned children

The init process handles all orphaned tasks.

MTRRs

// SMP init is completed before this.
For CONFIG_MTRR, call mtrr_init() [in linux/arch/i386/kernel/mtrr.c].

SYSCTLs

For CONFIG_SYSCTL configurations, call sysctl_init() [in linux/kernel/sysctl.c].

Init Many Devices


/*
 * Ok, at this point all CPU's should be initialized, so
 * we can start looking into devices..
 */

PCI

For CONFIG_PCI configurations, call pci_init() [in linux/drivers/pci/pci.c].

Micro Channel

For CONFIG_MCA configurations, call mca_init() [in linux/arch/i386/kernel/mca.c].

ISA PnP

For CONFIG_ISAPNP configurations, call isapnp_init() [in linux/drivers/pnp/isapnp.c].

Networking Init


        /* Networking initialization needs a process context */
        sock_init();
[in linux/net/socket.c]

Initial RamDisk


#ifdef CONFIG_BLK_DEV_INITRD

        real_root_dev = ROOT_DEV;
        real_root_mountflags = root_mountflags;
        if (initrd_start && mount_initrd)
                root_mountflags &= ~MS_RDONLY;      // change to read/write
        else
                mount_initrd =0;

#endif /* CONFIG_BLK_DEV_INITRD */

Start the kernel "context" thread (keventd)

[in linux/kernel/context.c]

Initcalls

Call all functions marked as "__initcall":


        do_initcalls();
[in linux/init/main.c]

This initializes many functions and some subsystems --- in no specific or guaranteed order unless fixed in their Makefiles --- if they were built into the kernel, such as:

Filesystems

Call filesystem_setup():

[in linux/fs/filesystems.c]

IRDA

For CONFIG_IRDA configurations, call irda_device_init().
/* Must be done after protocol initialization */
[in linux/net/irda/irda_device.c]

PCMCIA

/* Do this last */
For CONFIG_PCMCIA configurations, call init_pcmcia_ds().
[in linux/drivers/pcmcia/ds.c]

Mount the root filesystem


        mount_root();
[in linux/fs/super.c]

Mount the dev (device) filesystem


        mount_devfs_fs ();
[in linux/fs/devfs/base.c]

Switch to the Initial RamDisk


#ifdef CONFIG_BLK_DEV_INITRD

        if (mount_initrd && MAJOR(ROOT_DEV) == RAMDISK_MAJOR && MINOR(ROOT_DEV) == 0) {
                // Start the linuxrc thread.
                pid = kernel_thread(do_linuxrc, "/linuxrc", SIGCHLD);
                if (pid > 0)
                        while (pid != wait(&i));
                if (MAJOR(real_root_dev) != RAMDISK_MAJOR
                     || MINOR(real_root_dev) != 0) {
                        error = change_root(real_root_dev,"/initrd");
                        if (error)
                                printk(KERN_ERR "Change root to /initrd: "
                                    "error %d\n",error);
                }
        }

#endif /* CONFIG_BLK_DEV_INITRD */

See "linux/Documentation/initrd.txt" for more information on initial RAM disks.

{end of do_basic_setup()}


Next Previous Contents