Linux Kernel development-system call

Source: Internet
Author: User
ArticleDirectory
    • System Call and User Programming API
    • Example of direct system call and C library call using getpid
    • Implementation of system calls
    • Implementation example of getpid system call
    • System Call performance problems
    • Number of system calls that use systemtap to track processes

What is system call

System calling is an interface for interaction between the user space and the kernel space. The user space cannot directly access the kernel space, but can only be accessed through system calling. This is to ensure the stability and security of the kernel space.

System Call and User Programming API

User spaceProgramGenerally, system calls are called indirectly through APIS instead of directly using system calls. APIS encapsulate system calls, but not every API uses system calls. There is no strict correspondence between APIs and system calls. An API may correspond to only one system call, such as read () API and read () System Call; an API may also be implemented by multiple systems. Sometimes, the function of an API may not require services provided by the kernel, so this API does not need to be called by any system, for example, ABS (). In addition, a system call may be called by multiple different APIs.

Linux User programming interfaces follow the POSIX standard, the most popular application programming interface standard in the Unix world, which defines a series of APIs. In Linux (Unix as well), these APIs are mainly implemented through the C library (libc). Besides defining some standard C functions, A very important task is to provide a set of wrapper routine to package system calls in user space for programming.

But encapsulation is not necessary. If you want to call it directly, the Linux kernel also provides a syscall () function to call

Example of direct system call and C library call using getpid

# Include <syscall. h>
# Include <unistd. h>
# Include <stdio. h>
# Include <sys/types. h>

Int main (void ){
Long id1, Id2;
/*-----------------------------*/
/* Direct system call */
/* Sys_getpid (func No. Is 20 )*/
/*-----------------------------*/
Id1 = syscall (sys_getpid );
Printf ("syscall (sys_getpid) = % LD \ n", id1 );
/*-----------------------------*/
/* System Call encapsulated by "libc */
/* Sys_getpid (func No. Is 20 )*/
/*-----------------------------*/
Id2 = getpid ();
Printf ("getpid () = % LD \ n", Id2 );
Return (0 );
}

Implementation of system calls

In Linux, system calls are implemented using software interruptions in the 0x86 architecture. Software interruptions are different from what we often call hardware interruptions because they are triggered by software commands rather than peripheral interruptions. That is to say, it is also an exception developed by programmers. Specifically, it is to call the int $0x80 Assembly command, which will generate a programming exception with a vector of 128.

The reason why system calls need to be implemented with exceptions is that when a user-state process calls a system call, the CPU is switched to the kernel state to execute the kernel function, but entering the kernel -- Entering the High-Level authorization level -- must go through the system's door mechanism, the exception here is actually thrown into the kernel through the system gate (in addition to int 0x80, the user space can also enter the kernel through abnormal commands such as int3 -- Vector 3, into -- Vector 4, bound -- Vector 5, etc, other exceptions cannot be used by user space programs, which are used by the system ).

We will explain this process in more detail. The purpose of the int $0x80 command is to generate a programming exception numbered 128, which corresponds to the 128th item in the IDT of the Interrupt Descriptor Table-that is, the corresponding system gate descriptor. The gate descriptor contains a preset kernel space address, which points to the system call handler: system_call () (do not confuse with the system call service program, this program is in the entry. s files are written in assembly languages ).

Obviously, all system calls are directed to this address, but in Linux, there are two or three hundred system calls from here, after entering the kernel, how should we distribute them to their respective service programs? Don't faint. The solution to this problem is very simple: first, Linux numbers (0-nr_syscall) for each system call, and saves a system call table in the kernel, this table stores the system call numbers and their corresponding service routines. Therefore, before the system call is transferred to the kernel through the system gate, the system call numbers must be passed into the kernel together, on x86, this transfer operation is implemented by loading the call number into the eax register before int 0x80 is executed. In this way, once the system call handler runs, you can obtain data from eax and then search for the corresponding service routine in the system call table.

In addition to the system call number, many system calls also need to pass some parameters to the kernel, such as sys_write (unsigned int FD, const char * Buf, size_t count) for a call, you need to pass the file descriptor FD, the content Buf to be written, and the number of bytes to be written to the kernel. In this case, Linux has six registers that can be used to pass these parameters: eax (storing the system call number), EBX, ECx, EDX, ESI, and EDI are used to store these additional parameters (in ascending order of letters ). The specific method is to use the save_all macro in system_call () to save the values of these registers in the kernel state stack.

Implementation example of getpid system call

System Call table ARCH/x86/kernel/syscall_table_32.s. The position of sys_getpid in sys_call_table is the system call number. Here is 20

. Long sys_getpid/* 20 */

Define the system call number in the supported architecture (such as x86:

ARCH/x86/include/ASM/unistd_64.h: The system call number here does not need to be consistent with the system call table above.

# DEFINE _ nr_getpid 39
_ Syscall (_ nr_getpid, sys_getpid)

Implement the system call in kernel/Timer. C: note that the getpid name here will be spliced into sys_getpid in syscall_define0.
/**
* Sys_getpid-return the thread group ID of the current process
*
* Note, despite the name, this returns the tgid not the PID. The tgid and
* The PID are identical unless clone_thread was specified on clone () in
* Which case the tgid is the same in all threads of the same group.
*
* This is SMP safe as current-> tgid does not change.
*/
Syscall_define0 (getpid)
{
Return task_tgid_vnr (current );
}

The preceding syscall_define0 is defined in include/Linux/syscall. h:
# Define syscall_define0 (sname )\
Syscall_trace_enter_event (_ ## sname );\
Syscall_trace_exit_event (_ # sname );\
Static struct syscall_metadata _ used \
_ Syscall_meta __## sname = {\
. Name = "sys _" # sname ,\
. Syscall_nr =-1,/* Filled in at boot */\
. Nb_args = 0 ,\
. Enter_event = & event_enter __## sname ,\
. Exit_event = & event_exit __## sname ,\
. Enter_fields = list_head_init (_ syscall_meta __## sname. enter_fields ),\
};\
Static struct syscall_metadata _ used \
_ Attribute _ (Section ("_ syscalls_metadata ")))\
* _ P_syscall_meta _ # sname = & __ syscall_meta __## sname ;\
Asmlinkage long sys _ # sname (void)
# Else
# Define syscall_define0 (name) asmlinkage long sys _ # NAME (void)
# Endif

According to the above definition, it is easy to add a system call to the kernel. For the method, see http://edsionte.com/techblog/archives/2086.

System Call performance problems

System calls need to fall into the kernel space from the user space. After processing, the system needs to return to the user space. In addition to the actual time consumption of the system call service routine, it takes some time to fall into the/return process and the system call processing program (query the system call table and store/recover the user's site, these times add up to the response speed of a system call. System calling is not inferior to other user programs. It has strict performance requirements because it needs to be executed in the kernel, which is the same as other kernel programs.CodeConcise and fast. Fortunately, Linux has an incredible rate of context switching, making it concise and efficient to access the kernel. At the same time, all the Linux System Call handlers and each system call are very concise.

In most cases, the performance of Linux system calls is acceptable, but for some applications with very high performance requirements, although they want to use the services called by the system, however, we hope to speed up the response and avoid spending on/return and System Call handlers. Therefore, the kernel directly calls the system call service routine, the best example is httpd-to avoid the above overhead, it calls the service routine from the kernel to call the socket and other systems.

Number of system calls that use systemtap to track processes

Global syscalllist

Probe begin {
Printf ("System Call monitoring started (10 seconds)... \ n ")
}

Probe syscall .*
{
Syscalllist [PID (), execname (), name] ++
}

Probe timer. MS (10000 ){
Foreach ([pid, procname, name] In syscalllist ){
Printf ("% s [% d] CILS % S % d times \ n", procname,
PID,
Name,
Syscalllist [pid, procname, name])
}
Exit ()
}

Output example:
# STAP system_call_count.stp
System Call monitoring started (10 seconds )...
Stapio [2328] CILS fcntl 82 times
Stapio [2328] callread 92 times
Stapio [2328] callnanosleep 40 times
Mongod [2099] CILS select 1978 times
Mongod [2099] CILS gettimeofday 400 times
Mongod [2099] callnanosleep 298 times
Compiz [8661] callread 253 times
Compiz [8661] callclock_gettime 2466 times
Compiz [8661] callpoll 555 times
Compiz [8661] CILS writev 168 times
Xorg [2242] CILS clock_gettime 733 times
Xorg [2242] CILS setitimer 340 times
Xorg [2242] callread 340 times
Xorg [2242] CILS writev 177 times
Xorg [2242] CILS select 170 times
Compiz [8661] CILS recvfrom 1187 times
Redis-server [3600] CILS gettimeofday 400 times
Redis-server [3600] CILS epoll_wait 100 times

Reference:

Http://edsionte.com/techblog/archives/2071
Http://www.kerneltravel.net/journal/iv/syscall.htm

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.