Article Title: linux kernel log system. Linux is a technology channel of the IT lab in China. Includes basic categories such as desktop applications, Linux system management, kernel research, embedded systems, and open source.
Today, a colleague asked me how to print the information in the application. There is printk in the kernel. What is the use of user space? I think this problem is very strange. Can I use printf? He said that his code is in a so, and I am speechless! He used to work on windows. In windows, many of them are win32 programs with interfaces rather than console programs. Most of them use single-step tracking and breakpoint to learn information about program running, actually, I really don't like single-step or breakpoint. Except for special debugging needs, I usually get information by printing logs. linux has a powerful log recording system, you can give the program a more secure execution environment. The log is only a bypass function, which records an audit and does not affect the execution of the program. The single step and breakpoint are different, you can't find many problems, especially the concurrency problems, but the programmers who write code on windows always like one step, just like they always like disassembly, the reason for this is: first, most windows programs are not the console, and there is actually no place to print information. Second, windows has a powerful visual IDE, this provides convenience for a single step and a breakpoint.
In linux, syslogd is a daemon of the user space. All other processes that need to record logs can communicate with the daemon, and can entrust the daemon to help record logs, why not record it on your own? That's because syslogd is very professional and can record logs to a very detailed level. You can check the configuration files under etc, since all processes can delegate syslogd to record logs, inter-process communication is involved. This is another major part of linux, linux is good at combining small programs into a large computer system, and linux is good at distributed ideas rather than centralization. But why do I need to delegate logs to a daemon? In fact, isn't this a different job? Therefore, this is still a boundary issue. Besides syslogd, there is a klogd, which is not a hierarchical one. syslogd is a total logger, and klogd is just a syslogd client, similar to the level of many processes that need to record logs, you can call the syslog function to send logs to the syslogd daemon. However, the kernel is not a process, therefore, it is necessary to set up a user process to pass logs to syslogd. This process is klogd. It is its own business to get kernel log information from the kernel, in fact, the kernel leaves two log interfaces. One is sys_syslog System Call (Be sure not to confuse with the syslog function. syslog system calls communicate with the inner core, the syslog function communicates with syslogd), and the other is the/proc/kmsg file. klogd uses the latter. Of course, ksyslog can also be called directly. First, let's take a look at some kernel log structures. First, most kernel logs are generated by printk. You can also think that the kernel logs are generated by printk completely. But we know that printk prints the information to the screen, there are no other side effects. In fact, it is not just what we see. In fact, printk does not directly write information into the standard output file, the information is only inserted into a circular buffer, and when the content of the buffer zone is displayed as standard output, it is another thing, kernel logs exist in this circular buffer area, and only a copy of the buffer zone is printed to the screen. The real data is still retained in the buffer zone, only when klogd or another syslog system call is used to read information or when the buffer zone is full (the beginning and end of the ring buffer zone) will some or all data be cleared, as mentioned earlier, there are two methods to obtain kernel logs:/proc/kmsg. One is system calling. Fortunately, both of them call the do_syslog kernel function:
Int do_syslog (int type, char _ user * buf, int len)
{
Unsigned long I, j, limit, count;
Int do_clear = 0;
Char c;
Int error = 0;
Error = security_syslog (type );
If (error)
Return error;
Switch (type ){
...
Case 2:
...
Error = wait_event_interruptible (log_wait, (log_start-log_end); // if no data exists, wait for sleep.
If (error)
Goto out;
I = 0;
Spin_lock_irq (& logbuf_lock); // if you want to read data outside, you do not want the data to change during the reading process. Therefore, you must lock the circular data buffer.
While (! Error & (log_start! = Log_end) & I <len) {// This is where the kernel ring buffer actually consumes.
C = LOG_BUF (log_start); // get a character
Log_start ++; // data in the ring buffer is logically cleared only here.
Spin_unlock_irq (& logbuf_lock );
Error = _ put_user (c, buf );
Buf ++;
I ++;
Spin_lock_irq (& logbuf_lock );
}
Spin_unlock_irq (& logbuf_lock );
...
}
Let's take a look at the vprintk kernel function called by printk:
Asmlinkage int vprintk (const char * fmt, va_list args)
{
Unsigned long flags;
Int printed_len;
Char * p;
Static char printk_buf [1024];
Static int log_level_unknown = 1;
...
Spin_lock_irqsave (& logbuf_lock, flags); // This logbuf_lock spin lock is actually very important. Ensure that no other write process is involved in a kernel information writing process, otherwise, a lot of information will be rubbed together. For example, hello and world will change to hwellorold.
Printed_len = vscnprintf (printk_buf, sizeof (printk_buf), fmt, args );
For (p = printk_buf; * p; p ++ ){
If (log_level_unknown ){
If (p [0]! = '<' | P [1] <''| p [1]> '7' | p [2]! = '> '){
Emit_log_char ('<');
Emit_log_char (default_message_loglevel + '');
Emit_log_char ('> ');
}
Log_level_unknown = 0;
}
Emit_log_char (* p );
If (* p = '')
Log_level_unknown = 1;
}
If (! Cpu_online (smp_processor_id () & system_state! = SYSTEM_RUNNING ){
Spin_unlock_irqrestore (& logbuf_lock, flags );
Goto out;
}
If (! Down_trylock (& console_sem) {// if you can get the semaphore of the device, immediately display the data to the terminal
Lele_locked = 1;
Spin_unlock_irqrestore (& logbuf_lock, flags );
Lele_may_schedule = 0;
Release_console_sem (); // displays data for this function.
} Else {
Spin_unlock_irqrestore (& logbuf_lock, flags); // The kernel information has been written into the kernel ring buffer. In order to prevent others from writing, release the spin lock.
}
Out:
Return printed_len;
}
The circular buffer of the kernel has two purposes: one is to print directly on the screen, and the other is that the kernel log program in the user space is running, so this function has completed two functions:
Void release_lele_sem (void)
{
Unsigned long flags;
Unsigned long _ con_start, _ log_end;
Unsigned long wake_klogd = 0;
For (;) {// print to the screen. Note that when printing, make sure that logbuf_lock is owned because you do not want to change the buffer during the printing process.
Spin_lock_irqsave (& logbuf_lock, flags );
Wake_klogd | = log_start-log_end; // ensure that data exists. This variable also serves as the basis for awakening the do_syslog sleep queue.
If (con_start = log_end)
Break;/* Nothing to print */
_ Con_start = con_start;
_ Log_end = log_end;
Con_start = log_end; // note that log_end and log_start are not changed, but replicas are changed. This is because kernel buffering is also used below, and information is not consumed because the data is written to the screen.
Spin_unlock_irqrestore (& logbuf_lock, flags );
Call_lele_drivers (_ con_start, _ log_end );
}
Lele_locked = 0;
Lele_may_schedule = 0;
Up (& console_sem );
Spin_unlock_irqrestore (& logbuf_lock, flags );
If (wake_klogd &&! Oops_in_progress & waitqueue_active (& log_wait) // if there is data in the kernel wake-up buffer, wake up the sleep queue
Wake_up_interruptible (& log_wait );
}
Finally, let's take a look at the read function of the kmsg interface exported by procfs, which actually calls the do_syslog function:
Static ssize_t kmsg_read (struct file * file, char _ user * buf, size_t count, loff_t * ppos)
{
If (file-> f_flags & O_NONBLOCK )&&! Do_syslog (9, NULL, 0 ))
Return-EAGAIN;
Return do_syslog (2, buf, count );
}
Here I think there is a problem, that is, when printk is used, if we can just get the device's semaphore, we must wait until the information is fully displayed on the device and call the stack to return it, that is to say, it is better not to call the printk function in a large number in the kernel. In addition, this is also very unfavorable on the multi-processor. In the past, the number of processors was small, so the problem is not big. Now all are multi-processors, the performance may be affected by printk. I think a ring buffer can be prepared for each cpu and then controlled when splicing These buffers, such as reading the buffer of each cpu in the user space, I just understood them as a whole. I feel that they can be implemented in a file system. It is not good to call printing frequently in any program, because printing involves device operations. Think about how slow peripherals are than CPUs, and it is the only device in the machine, moreover, it is a device that almost every process uses. How long is it that we spend fighting.
Back to my colleague's question, how can I print information on linux? In fact, as long as you don't close it, each program will open three file descriptors by default: 0, 1, and 2, these three descriptors are initialized in the kernel_init process (eventually/sbin/init) called in start_kernel, that is, in the following code:
If (sys_open (const char _ user *) "/dev/console", O_RDWR, 0) <0)
Printk (KERN_WARNING "Warning: unable to open an initial console .");
(Void) sys_dup (0 );
(Void) sys_dup (0 );
Here, sys_open opens/dev/console and uses it as the standard output, which is actually our terminal, the current terminal, in sys_open, file descriptor 0 is automatically allocated to the terminal file, and then sys_dup is equivalent to copying the file represented by this terminal file descriptor to the new descriptors 1 and 2, in this case, in fact, 0, 1 and 2 represent the same thing and all refer to the current terminal. That is why you can write something in a standard error. In fact, the standard input is actually used, the output and errors are all used by the user process. For the kernel, they are a thing. Because the linux Process is fork, and the root cause is the kernel_init process, each process copies the 0, 1, and 2 file descriptors of the parent process by default (if the parent process does not close them ).