& Nbsp; Step 1: Get the kernel code & nbsp; Linux has become a buzzword in recent years. None of the students and IT professionals who boast computer proficiency have installed one or two Linux operating systems on their computers, and have consciously caught up with fashion. However, in Ubuntu or SUSE forums, there are often such conversations :&
Step 1: obtain the kernel code
In these years, Linux has become a buzzword. None of the students and IT professionals who boast computer proficiency have installed one or two Linux operating systems on their computers, and have consciously caught up with fashion. However, in Ubuntu or SUSE forums, there are often such conversations:
"What have you learned after studying Linux for so long ?"
"Oh, I am familiar with Linux installation, upgrade, and desktop beautification! You see, this is the latest Ubuntu version. the desktop is very beautiful !"
"……"
There is a famous saying in the Linux community: If you do not know what to do when you enter your operating system, you 'd better turn off your computer and there must be more important things waiting for you to do. To be honest, if you are not familiar with Linux commands, you cannot really learn Linux. On the other hand, Linux kernel is the most interesting part of the Linux operating system, although it is not available to users. Especially for developers, Linux kernel development is definitely the best place to hone. 51CTO editor has always believed that it technology is widely used in foreign countries, and they have little access to UNIX-like systems and play with kernel development.
The following is an entry-level article written by Linux kernel developer Robert Love, known as the "package Church". we recommend that you do not miss out on students, Linux fans, developers, and system administrators who are interested in Linux kernel development. Of course, although the title is package-oriented, you may need certain Linux commands and C language basics.
The following is the body content:
Linux kernel has always been regarded as the most difficult part to learn about Linux. I believe you have read many articles about the kernel, but ask yourself, how much have you mastered? This article will introduce from scratch what is regarded as a deep Linux kernel, which involves the download, compilation, installation, and kernel development of the kernel source code.
How to obtain the Linux kernel source code
To download the Linux kernel, you must go to the official website. The website provides two types of file downloads: one is the complete Linux kernel, and the other is the incremental Kernel Patch. they are all tar archive packages. Unless you need to use the old Linux kernel for special reasons, you should always upgrade to the latest version.
Use Git
The Linux kernel development team led by Linus began using the Git version control system to manage the Linux kernel a few years ago (refer to: What is Git ?), The Git project is also created by Linus. unlike traditional CVS, Git is distributed. Therefore, many developers may feel unfamiliar with its usage and workflow, however, I strongly recommend that you use Git to download and manage the Linux kernel source code.
You can use the following Git command to obtain the latest "push" version of the Linus kernel code tree:
$ Git clone git: // git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6.git
Run the following command to synchronize the latest status of your code tree with the Linus code tree:
$ Git pull
Install kernel source code
The kernel package is in GNU zip and bzip2 formats. Bzip2 is the default and preferred format, because its compression ratio is usually better than gzip, bzip2 format linux x.y.z.tar.bz2 format file name, here x. y. z is the specific version of the kernel source code. after downloading it to the source code package, it is very easy to extract and extract it. if you download the bzip2 package, run:
$ Tar xvjf linux-x.y.z.tar.bz2
If you download a gzip package, run:
$ Tar xvzf linux-x.y.z.tar.gz
No matter which command is executed, the source code will be decompressed and extracted to the linux-x.y.z Directory, if you use Git to download and manage the kernel source code, you do not need to download the tar package, you only need to run the git clone command to automatically download and decompress it.
The kernel source code is usually installed in/usr/src/linux, but it is best not to use this source code tree during development, because the kernel version compiled for your C library is usually linked here.
Application patches
Linux kernel developers will make their modifications into patches to share with others, and the patches are incremental. incremental patching is an effective way to move from one kernel tree to another, you can upgrade the kernel without downloading the complete kernel package. This not only saves bandwidth, but also saves Kernel upgrade time. before applying the patch, go to the Directory of the kernel source code tree and run:
$ Patch? P1 patch-x.y.z
Note that the patch package also has a clear version number. the version number here must be the same as the version number of the Linux kernel source code. When the kernel and patch version number are inconsistent, force application of the patch will cause unexpected consequences.
Kernel source code tree introduction
The kernel source code tree is divided into many directories, which contain many subdirectories. The top-level directories of the source code tree and their descriptions are listed in the table below.
There are still many files in the root directory of the source code tree. COPYING is the kernel license description file (gnu gpl v2), and CREDITS is the list of developers involved in the Linux kernel, MAINTAINERS lists individuals who maintain subsystems and drivers. Makefile is the basis of kernel Makefile.
Generate kernel
It is actually easier to generate a kernel than to compile and install other system-level components, such as glibc. from version 2.6, the Linux kernel introduces a new configuration and generation system, it makes operations on the production kernel easier.
Configure the kernel
Now that we have obtained the kernel source code, we can configure and customize it as needed before compiling, and compile your designated functions and desired drivers, configuring the kernel is a step required to generate the kernel. because the kernel provides a large number of functions and supports various hardware, many of which require configuration. the kernel configuration is controlled by the configuration options, configuration options have a CONFIG prefix. for example, symmetric multi-processing (SMP) is configured by the CONFIG_SMP configuration option. if this option is set, SMP is enabled, and vice versa, the configuration option can determine the file to be generated or manipulate the code through the preprocessing command.
Configuration options can control the generation process either Boolean or tri-state, and Boolean is "yes" or "no". most kernel configuration options are Boolean, such as CONFIG_PREEMPT, the three-state model adds a "module" option on the basis of "yes" and "no". the module option indicates that the configuration option is set, but it is finally compiled into a module, instead of directly compiling the data into the kernel, the module can be understood as an independent and dynamic loading object. Generally, the driver configuration is usually in three states.
The configuration option can also be a string or integer. This option does not control the generation process. the specified value is used when the kernel source code accesses the pre-processing macro. for example, you can specify the size of the static allocation array for a configuration option.
Linux vendors also provide pre-compiled kernels with the release, such as the kernel provided by Canonical for Ubuntu or Red Hat for Fedora. such kernels usually only enable the required kernel functions, almost all drivers are compiled into modules. Such a kernel provides a good basic kernel and extensive hardware module support. In any case, you want to become a kernel master, you should compile your own kernel.
Fortunately, the kernel provides many tools to simplify the configuration. the simplest tool is a text command line-based utility, such:
$ Make config
This tool will be configured with one option, but the user needs to participate, such as specifying "Yes (y)", "No (m)" or "module (m )", the entire configuration process takes a long time. because of this, unless someone is billed hourly, please upgrade the kernel. there is no other reason to use this original method to configure the kernel. On the contrary, there are ready-made ncurses-based graphical tools to replace.
$ Make menuconfig
Or a graphical tool based on gtk +
$ Make gconfig
All three of the preceding tools divide configuration options into multiple categories, such as "processor type and feature". you can move back and forth between these categories to view kernel options, of course, you can also modify their settings.
The following command creates a default configuration basis based on your architecture.
$ Make defconfig
Although the default configuration is somewhat arbitrary (on i386, the default configuration is configured by Linus), if you have never configured the kernel, it provides a good start.
The configuration option is stored in the next name in the source code root directory. In the config file, you can open this file and manually edit the configuration options. after modification, or you want to apply the existing configuration file to the new kernel source code tree, you can use the following command to verify and update the configuration:
$ Make oldconfig
You must run this command before generating the kernel.
The configuration option CONFIG_IKCONFIG_PROC specifies the location of the complete kernel configuration file compressed package. the default value is/proc/config.gz, which makes it very easy to clone the existing configuration when generating the new kernel. If this option is enabled for your current kernel, you can copy the configuration file from/proc and then generate a new kernel:
$ Zcat/proc/config.gz>. config $ make oldconfig
After the kernel is configured, use the following command to generate it:
$ Make
Unlike the kernel earlier than 2.6, you no longer need to execute the make dep command before generating the kernel. the dependency tree is automatically maintained and you do not need to specify a specific generation type, such as bzImage, or an independent generation module. by default, Makefile rules automatically process everything.
Minimize interference information
Alarms and errors may interfere with the generation process. One trick to minimize interference information is to redirect the make output, but you will still see some warnings and errors:
$ Make>/detritus
If you want to view the generated output, you can read this file later. if you do not want to see any output at all, redirect to/dev/null:
$ Make>/dev/null
Execute multiple generated jobs at the same time
The Make Command provides a function to split the generation process into multiple parallel jobs, which can be run independently or in parallel, in a multi-processor system, the generation speed is greatly improved, and the processor utilization is also improved, because a large source code tree will generate a large amount of I/O wait time.
By default, make can only be split into one job, because Makefiles often contain incorrect dependency information. if so, multiple parallel jobs will cause confusion, this will eventually cause the generation process to fail. if the dependency information in Makefiles is correct, it can be split into multiple jobs for execution, for example:
$ Make? Jn
Here, n indicates the number of jobs to be split. generally, one or two jobs are split by each processor. for example, on a 16-core machine, you can run:
$ Make-j32>/dev/null
Using excellent tools such as distcc or ccache can also greatly increase the generation speed.
Install new kernel
After the kernel is generated, you need to install it. how to install it in the system architecture depends on the boot loader. we will take the x86 architecture and the grub boot loader as an example.
First, copy arch/i386/boot/bzImage to/boot and rename it to vmlinuz-version. the version here is also the version number, and then edit/boot/grub. conf to add the corresponding project for the new kernel. if you are using the LILO boot loader, modify/etc/lilo. conf file, and then run lilo.
The module installation is not related to the system architecture and is automatically completed. run the following command as the root user:
% Make modules_install
This command will install all the compiled modules in the corresponding sub-directories under/lib/modules.
The generation process creates a System under the root directory of the source code. the map file contains a symbolic lookup table that maps the kernel symbols to their starting addresses. during debugging, you can use it to convert the memory addresses into functions and variable names.
Possible problems
Compared with applications in common user space, Linux kernel has multiple special attributes. The following are some of the most important differences:
◆ The Kernel neither accesses the C library nor the standard C header;
◆ The kernel is encoded by gnu c;
◆ The kernel lacks the memory protection provided by the user space;
◆ The kernel cannot easily perform floating point operations;
◆ The kernel has a small fixed-size process stack;
◆ Because the kernel supports asynchronous interrupt and SMP, synchronization and concurrency are the main concerns of the kernel;
◆ Portability is also important.
Next, let's take a look at these issues one by one. all kernel developers must remember them.
No libc or standard header
Unlike User space applications, the kernel is not linked to the standard C library, nor to any other library. There are many reasons for this design, this includes the problem of having a chicken or an egg, but the main reason is the speed and kernel size. do not say that the complete C library is large enough, that is, a subset of it, if the kernel is too large, it will only cause low efficiency.
Don't worry, many common libc functions are implemented in the kernel. for example, common string operation functions are located in lib/string. c and only need to include their header files. You can.
The header file here refers to the header file in the kernel source code tree. the kernel can only use the header file in the tree. The basic file is located in the include/directory of the source code root directory. for example, The header file is in include/linux/inotify. h.
The architecture-related header files are located at arch/include/asm. for example, if you compile the files in the x86 architecture, the files related to your architecture are arch/x86/include/asm, you only need to add the asm/prefix to reference these headers, as shown in.
Most of the missing functions are functions similar to printf (). The kernel does not use printf (), but it provides the printk () function, which is no worse than printf (). printk () the system will copy the formatted string to the kernel log buffer. The syslog program reads the information from here and its usage is similar to that of printf:
Printk ("Hello world! A string % s and an integer % d ", str, I );
The biggest difference between printf () and printk () is that printk () allows you to specify a priority mark, which syslogd uses to determine where to display kernel messages, the following is an example of using priority labels:
Printk (KERN_ERR "this is an error! ");
Note that there is no comma between the KERN_ERR and the printed message. this is designed on purpose. the priority is defined by a predefined character. during compilation, it is connected to the printed information.
GNU C
Like many Unix kernels, the Linux kernel is also written in C, but it may be surprising that the kernel is not written in rigorous ansi c, kernel developers use various language extensions in gcc (GNU compiler set, including C compiler for compiling the kernel and Linux C program.
Kernel developers use the C language's ISO C99 and gnu c extensions at the same time. these changes make the Linux kernel more closely integrated with gcc, but a new compiler has appeared recently? Intel C compiler? It also supports the gcc function quite well, so you can use it to compile the Linux kernel. The minimum supported gcc version is 3.2. we recommend that you use gcc 4.4 or later. You can also use the ISO C99 extension because C99 is an official C language version.
Inline functions
Both C99 and gnu c support inline functions. inline functions are directly inserted to the position of each function call. This eliminates the overhead of function call and return and allows further optimization, because the compiler can optimize callers and called functions at the same time, but it also has disadvantages, the code size will increase, because the function content is directly copied to the caller's internal, therefore, memory consumption and instruction cache space are also increased. Kernel developers generally use inline functions in small time-critical functions.
When defining a function, use the static and inline keywords to declare an inline function. for example:
Static inline void wolf (unsigned long tail_size)
The function must be declared first and then used. Otherwise, the compiler cannot inline the function. generally, inline functions are placed in the header file because they are marked as static and no output function is created, if inline functions are only used in one file, they can be placed at the top of the file.
In the kernel, inline functions are preferred for security and readability compared with complex macros.
Inline assembly
The Gcc C Compiler allows you to embed assembly commands in C functions. The asm () compiler commands are used to inline assembly code. for example, this inline assembly command executes the rdtsc command of the x86 processor, return the value of the timestamp register (tsc:
Unsigned int low, high;
Asm volatile ("rdtsc": "= a" (low), "= d" (high ));
/* Low and high now contain the lower and upper 32-bits of the 64-bit tsc */
The Linux kernel is written in a mix of C and assembly languages. many of the code related to the underlying hardware is written in assembly language, and most of the remaining kernel code is directly written in C.
Branch annotation
The Gcc C compiler has a built-in command optimization condition branch. the kernel packs this into easy-to-use macros-likely () and unlikely ().
First look at the following if statement:
If (error ){/*... */}
Mark this branch as very impossible to use
/* We predict error is nearly always zero... */If (unlikely (error )){/*... */}
Rather, it is very likely to use
/* We predict success is nearly always nonzero... */If (likely (success )){/*... */}
When the branch instruction already knows a priority, or you want to optimize another condition in one case, use the preceding command. The most important thing is that when the branch is correctly marked, these commands improve performance, but if the branch flag is incorrect, the performance will be reduced. in kernel code, unlikely () needs to be used more, because if statements tend to indicate a special situation.
No memory protection
When an application in the user space tries an illegal memory access, the kernel can capture the error, send the SIGSEGV signal, and kill the process. if the kernel tries an illegal memory access, the result is out of control, because no one can control the kernel, which is also the main mistake of the kernel.
In addition, the kernel memory is not paging, so each memory byte you consume is less than one byte of physical memory.
Cannot (easy) use of floating point numbers
When a user space process uses floating point commands, the kernel is responsible for the conversion from integer to floating point mode.
Unlike the user space, the kernel cannot seamlessly support floating point numbers because it cannot easily capture itself. to use floating point numbers in the kernel, you must manually save and restore floating point registers unless necessary, otherwise, do not perform floating point operations in the kernel.
Small, fixed-size stack
The user space can be statically allocated with many different stacks, including giant structures and arrays of thousands of RMB. this behavior is legal because the user space has a large stack and can dynamically grow.
The kernel stack is neither big nor dynamic. On the contrary, it is small and fixed. the precise size of the kernel stack varies according to the architecture. on x86, the stack size is determined during compilation, generally, it is 4 kB or 8 kB. in history, the kernel stack has two pages, which usually indicates that it is in a 32-bit architecture with a size of 8 kB. if it is 16 kB, it indicates a 64-bit architecture, in short, the size is fixed, and each process receives its own stack.
Synchronization and concurrency
The kernel is most vulnerable to competition. unlike a single-threaded User space application, the kernel features allow simultaneous access to shared resources, so synchronization is required to prevent competition, especially:
◆ Linux is a preemptible multi-task operating system. processes are scheduled and re-scheduled by the kernel's process scheduler. The Kernel must synchronize these tasks;
◆ Linux supports symmetric multi-processing (SMP). Therefore, if no proper protection is provided, kernel code executed simultaneously on two or more processors may access the same resources at the same time;
◆ Interruptions occur asynchronously. Therefore, if appropriate protection is not provided, they may also be interrupted during resource access, and the interrupt handler may access the same resource;
◆ Linux has priority. Therefore, if appropriate protection is not provided, kernel code may be executed first to access resources in use by other codes.
The general solution to these problems is spin locks and semaphores.
The importance of portability
Although user space applications generally do not place too much emphasis on portability, Linux is indeed a portable operating system and should be consistent, this means that the C code unrelated to the architecture must be correctly compiled and run on a large number of systems, and the code related to the architecture must be separated by a specific directory in the kernel source code tree.
Summary
It is certain that the kernel has its unique nature and has its own principles. However, the complexity and obstacles of the kernel are no different from those of other large software projects, the most important step in Linux development is to realize that the kernel is not terrible and unfamiliar with it? Of course! Insurmountable? Of course not!