Starts applications in parallel to accelerate Linux boot.

Source: Internet
Author: User
Tags disk usage
Starts applications in parallel to accelerate Linux boot.

The biggest complaint about Linux (especially from developers) is the Linux boot speed. By default, Linux is a common operating system and can be used as an out-of-the-box client desktop or server. Linux is flexible and can be used as the basis for various purposes, but it is not the best choice for any specific configuration. This article will show you some ways to improve the Linux boot speed, including two ways to perform parallel operations on the initialization process. This article also describes how to graphically display the performance of the boot process.

One of the common complaints about GNU/Linux (except for lack of a good kernel debugger) is that it takes a lot of time to start the operating system. You can summarize this processGuideBut there are already several independent projects that can be improved from the cold system to interact with the system through shell or window manager. Let's review the Linux boot and initialization processes.

Main phases of Linux boot

Although booting LINUX involves many steps, you can divide the entire process into three basic steps.Bios,Kernel bootAndSystem initialization, 1.

Figure 1. Short view of Linux boot process

Bios

When the computer is started or restarted for the first time, the computer's processor will start to execute at a well-known location, that isBasic Input/Output System(BiOS ). BIOS is usually stored in a flash device on the system motherboard. BiOS requires a lot of work, such as initial testing of basic components (such as system memory) to determine how to boot the operating system. Since PC-based computers are flexible, boot devices can be one of the various devices connected to the motherboard, including hard drives, CD-ROM, or other devices, such as network interfaces.

You can select the most frequently-guided device (usually the hard disk) to optimize the process of determining the boot device. So far, the most time-consuming process in the BIOS stage is the memory test. Disabling some parts of this test (such as a full memory test) does help speed up boot, but the cost of doing so is the loss of System Integrity testing during boot.

Kernel boot

Find the boot device and start the Linux kernel boot process. This process takes place in two phases (approximately )--Phase 1 GuidanceAndPhase 2 Guidance. The first stage contains a simple Boot Loader (which can be found in the Master Boot Record MBR of the boot device), which is used to load the boot loader of the second stage. The pilot loader in the first stage uses the partition table to find the pilot loader in the second stage. The pilot loader in the first stage scans the table and finds the active partitions. When the loader finds the partition, it loads the pilot loader in the second stage into RAM and calls it.

After the boot loader in the second stage is loaded into RAM, the Linux kernel image and the initial RAM disk image (initrdIs also loaded into RAM. When the kernel is called, it is automatically decompressed into the high-end memory and copiedinitrdFor later installation and use.

Lilo and grub

The first-stage boot loader and the second-stage Boot Loader are usually calledLinux Loader(Lilo) orGrand uniied bootloader(Grub), depending on the name used by your system.

The kernel boot process is usually quite complex, but very fast, because most of the Code is written in the system's machine language. At the end of the kernel boot sequenceinitProcess. BecauseinitIs the first process created in Linux, so it is the ancestor of all other processes (all processes areinit).

System initialization

initProcess -- the focus of this article -- is the first process created when the kernel boot process is completed. LinuxinitProcess to initialize the services and applications that make up Linux.

WheninitWhen a process starts, it opens/Etc/inittab. This file isinitThe configuration file defines how to initialize the system. This file also contains information about the operations performed in case of a power failure (if supported by the system) and how to respond when the Ctrl-alt-delete key sequence is detected. See the short section of this file in Listing 1 to learn about what it provides.

inittabThe configuration file defines several items in a common format:ID: runlevels: Action: Process. WhereIDIs the character sequence that uniquely identifies the item.RunlevelsDefines the operation level.ActionSpecifies the specific operation to be executed. Finally,ProcessDefines the process to be executed.

Listing 1. inittab file excerpt

 # The default runlevelid:2:initdefault# Boot-time system configuration/initialization scriptsi::sysinit:/etc/init.d/rcS# Runlevelsl0:0:wait:/etc/init.d/rc 0l1:1:wait:/etc/init.d/rc 1l2:2:wait:/etc/init.d/rc 2l3:3:wait:/etc/init.d/rc 3l4:4:wait:/etc/init.d/rc 4l5:5:wait:/etc/init.d/rc 5l6:6:wait:/etc/init.d/rc 6z6:6:respawn:/sbin/sulogin# How to react to ctrl-alt-delca:12345:ctrlaltdel:/sbin/shutdown -t1 -a -r now

Init and telinit

You can usetelinitTool (this is a pointinitTool link) andinitProcess for communication. For example, if you want to switch to runlevel 1 in the multi-user mode (runlevel 2), runtelinit 1You can (use the superuser mode ).

IninitAfter the/etc/inittab is loaded, the system will be switchedinitdefaultThe operation level. As shown in List 1, that is, level 2. We can regard the running level as the state of the system. For example, run level 0 defines the system suspension status, and run level 1 is a single user mode. The running level 2 to 5 is multi-user status, and the running level 6 indicates restarting. (Note that some releases have different running-level representations ). You can also consider the running level in another way, that is, it is a method that defines which processes can be executed (processes that define the system status.

Note:To view the current running level of the system, use the commandrunlevel.

As defined in Listing 1,initdefaultSpecify the defaultinitLevel is2(Multi-user mode ). After the initial running level is definedrcScripts and Parameters2(Run level) to start the system. This script then calls various services and application scripts to start or stop specific elements. In this example, all files are defined in/etc/rc2.d. For example, if you want to start a MySQL application (such as a system startup), you can call:/etc/rc2.d/S20mysql start. When the system is shut down, usestopThe same script set is called by parameters.

Modify the INIT process

Modifying the initialization process is very simple. During boot (using LILO or GRUB), specify a new process to start processing system initialization. Specifyinit=/sbin/mynewinitCall this process as part of the kernel boot line, instead of the defaultinitProcess. In the kernel source code of./Linux/init/Main. C, you can see this usage. IfinitCommand. Otherwise, the kernel will try to start one of the four alternatives (the first one is/Sbin/init ).

Finally, execute a large number of scripts in sequence to start various required services (usually seen on the Linux boot screen ). Even if these services have nothing to do with each other, they will be started in sequence. The result is that the boot process is very time-consuming (especially for large systems with many services ).

An obvious solution to this problem is to removeinitReplace the serial feature of a command with a parallel operation. This usage can be seen in many multi-processing systems. For example,Socket stripingOr, using two or more sockets to move data in parallel is a solution based on this topic. The Redundant Array (RAID) system of Independent Disks also improves I/O performance by dividing disks into bars (usually parallel.


Replacement of the init daemon

Simple init Optimization

PairinitThe simplest way to optimize a process is to disable unnecessary services. For example, if you are running a desktop system (rather than a server), you can disable services such as Apache, Sendmail, and MySQL.initSequence.

Because of the traditionalinitProcess (sysvinit) Is a serialized process, so this sub-system can be fully optimized. In fact, you can use any methodinitProcess optimization. Let's take a look at some of the methods and how they solve the problem. The first two methods are based on dependencies (that is, using dependencies to provide parallelization ), the third method is an event-based system (that is, the process depends on the event to indicate when it was started or stopped ).


Initng

Method 1initng(Next Generationinit) Will completely replace the asynchronous Startup Processinit, Can be completed more quicklyinitProcess. When writing this article,initngIs a beta product created by Jimmy wennlund.

initngThe basic idea behind it is that it can be started as long as the service dependency is satisfied. In this way, the system can achieve a better balance between CPU and I/O. When loading a script from the disk or waiting for the hardware device to start, you can run another script to start another service.

How initng works

As a dependency-based solution,initngUse your own initialization script set to encode the dependencies between services and daemon. Listing 2 shows an example. This script specifies the service to be started for a given running level. The Service has two dependencies.needKeyword definitions: System/initial and net/All. These services must be available before system/my_service can be started. When these services are available,execThe keyword starts to work.execKeywords (andstartOption) defines how to use any available options to start the service. To stop this service, you will useexecKeyword andstop.

Listing 2. Defining services for initng

 service system/my_service {     need = system/initial net/all;     exec start = /sbin/my_service --start --option;     exec stop = /sbin/my_service --stop --option;}

You can use the service definition to encode the entire system, as shown in Listing 2. Services without dependency can be started immediately (in parallel), while those with dependency must wait for a secure start. You caninitngAs a target-based system. The goal is to start the service. There is no explicit planning. On the contrary, dependencies simply define the service initialization process, which implies parallel operations.

Use initng

initngPackage installation is relatively simple for typical usage. For non-standard packages (not included in the default configuration), some compilation is required.

initngTypical installation requirementsinitngRelease (source code or binary files) and ifiles release. You can use./configure,makeAndmake installCompile your owninitngRelease version. You must usecmakeTo compile the ifiles file (this is a script file ). Depending on the system requirements, you may need to create a new service/daemon definition (but it is very likely thatinitngSomeone already does this in the community ). Then you must modify the configuration of LILO or GRUB to point to the new/sbin/initng.

To controlinitng, You need to usengc(ComparisontelinitWith traditionalinit). Their syntaxes are somewhat different, but their functions are the same.

Upstart

ReplaceinitAnother option isupstart, The method usedinitngThe method is slightly different.upstartIs an event-basedinitThis means that the startup and stop of the service are based on event communication.upstartIs being developed by Scott James remnant for Ubuntu release, but it wants to become any Linux releaseinit.

How upstart works

UpstartYou are required to update the initialization script to support the event-based operation mode.upstartMaintain your own startupinitProcess (for all other methods ). First,initWill be issuedStartupEvent-this is one of the two core events. EventStartupYesbyinitEvents triggered at system startupShutdownIt is issued when the system is disabled. Other core events includeCtrlaltdelIt indicates that you have pressed Ctrl-alt-delete, orKbdrequestIt indicates that you have pressed the alt-up (up arrow) key combination.

You can create new events for other usage. For example, you can createMyeventAnd useechoCommand to receive the event. Use the following short job:

on myeventexec echo myevent receivedconsole output

This Code specifies thatMyeventThis job will be triggered when the event occurs. Then the code executes the specified operation (send text to the console ). UseupstartConfiguration file (/etc/event. d), you can useinitctlThe tool triggers it:

initctl emit myevent

upstartThe script file used works in a similar way as the traditionalrc initFiles, which are operated spontaneously Based on Asynchronous events. Listing 3 provides a simple sample script that can receive three events:Startup, Start the job;ShutdownAndRunlevel-3To stop the job. The shell executes the jobscriptPartial content (Use-eTo end the error script ).

Listing 3. Simplified upstart script of the sysvinit RC 2 script

 start on startupstop on shutdownstop on runlevel-3script set $(runlevel --set 2 || true) exec /etc/init.d/rc 2end script

initctlThe tool providestelinitBut added some features specificupstart. You can useinitctlAndemitOption:upstartGenerate an event.listOption allows you to gain a deeper understanding of system operations by identifying the job status. It tells you which services are waiting for and which services are currently active.initctlThe tool can also display events received for debugging.

UpstartYesinitAnd has some unique advantages. In fact, there is no reason to use the running level, because the system will make full use of hardware for boot. No hardware is provided to trigger the task that requires it.UpstartIt can also handle hot swapping devices well. For example, if a PCMCIA Nic is inserted after the system boot is completed for a long timeNetwork-interface-addedEvent. This event will cause a Dynamic Host Configuration Protocol (DHCP) job to configure this Nic and generateNetwork-interface-upEvent. When a default route is assigned to this new interface,Default-route-upEvent. In this case, the network interface job (such as the mail server or Web Server) can be automatically started (if the interface disappears, these services will be automatically stopped ).

Use upstart

Compile and installupstartVery simple and follow the typicalconfigure,makeAndmake installMode.UpstartProvides a set of sample jobs with typicalinitConfiguration compatibility. AndinitngSimilarly, new applications must write their own jobs as needed (new events may need to be added ). Either way, deploy the newinitThe system may have some risks. HoweverupstartOf course, it is worth taking these risks and performing other necessary operations.

As described above,initctlTools providetelinitThe expected function. HoweverinitctlIt also provides additional features for tracking and debugging.

Other options

The two methods described in this article --initngAndupstart-- Not only these two programs can replaceinit. You will find otherinitReplacement program, suchrunit,pardus,minitAndeinit. All these programs have some supporters and motivation in the Linux community. Now,upstartIt may be something we want to know, because it has been adopted by the popular Ubuntu releaseinit. For more information, see references.

Monitor init performance using bootchart

After the system boot process is modified, it is very helpful to understand the modification content and how it affects the total time of system boot. Ziga mahkovec has developed a very useful tool.bootchartCan visually represent the composition of the startup process. This tool consists of several elements, including a data logging tool and a visualization tool.

The data logging Recorder (bootchartd) Is ininitRunning in the process (usually specified in the grub or Lilo. conf file ). InbootchartdAfter Initialization is complete, the control will be handed over to the realinitProcess (usually/sbin/init ).BootchartdEssentially, it is a analyzer that periodically samples the environment at intervals (the default interval is 200 ms ). The so-calledSample the environmentThat is to say, it can read statistics of the current CPU, I/O and idle events, disk usage, and information of each active process (throughprocFile System ). Data is stored in a temporary file (/var/log/bootchart. tgz) for further processing.

BootchartThen, a secondary processing tool is used to convert the raw data into a bootstrap chart. In this process, you can use a Java application (bootchartBut the simpler method is to usebootchartA web form on the home page. Figure 2 shows some examples of the bootstrap chart. Note that these graphs will be very large (depending on the services and applications started ). For the link to the complete example, see references.

Figure 2. bootchartd

Summary

Some friends in the group mentioned that they encountered an init loading error during arm development and transplantation, causing them to be unable to start, and asked me for a solution. As a substitute for init, there are a lot of things. I can find this article in some Linux communities and hope it can help you in your learning. I do not need to annotate the article here, but it is already quite detailed.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.