printk()函数学习笔记

参考:

https://www.cnblogs.com/sky-heaven/p/6742062.html
韦东山老师的printk讲解:https://blog.csdn.net/W1107101310/article/details/80526039

1.平台内核启动参数:
bootargs = "console=ttySC0,115200n8 rw root=/dev/mmcblk0p3 rootwait ignore_loglevel vt.global_cursor_default=0"

ignore_loglevel:printk.c中即作为启动参数也作为模块参数,指定了它:ignore loglevel setting (prints all kernel messages to the console)"
只有suppress_message_printing()使用了它,拿它做判断

2. 4.14.35内核printk()的调用路径:

printk
    vprintk_fun
        vprintk_emit    调用local_irq_save(flags)并获取spin_lock!
            console_unlock() 关闭本地中断调用call_console_drivers
                call_console_drivers()
                    sc-shi.c中注册的console_write()

suppress_message_printing()  里面检测了printk()的打印等级,决定哪些等级打印,哪些等级不打印,到那时配置了一个命令行参数使其恒为假

TODO:确认一下cmdline中的ignore_loglevel生效了没有!

平台上配置的是128K的log_buf
#define CONFIG_LOG_BUF_SHIFT 17 /*1<<17=128K*/
static char __log_buf[__LOG_BUF_LEN] __aligned(LOG_ALIGN); /*128k,以struct printk_log大小对其*/

3.Kernel代码查看

#define KERN_EMERG      KERN_SOH "0"    /* system is unusable */
#define KERN_ALERT      KERN_SOH "1"    /* action must be taken immediately */
#define KERN_CRIT       KERN_SOH "2"    /* critical conditions */
#define KERN_ERR        KERN_SOH "3"    /* error conditions */
#define KERN_WARNING    KERN_SOH "4"    /* warning conditions */
#define KERN_NOTICE     KERN_SOH "5"    /* normal but significant condition */
#define KERN_INFO       KERN_SOH "6"    /* informational */
#define KERN_DEBUG      KERN_SOH "7"    /* debug-level messages */

//在menuconfig中或下面将第一个参数改为8,也能都打印出来。
int console_printk[4] = {
    CONSOLE_LOGLEVEL_DEFAULT,    /*7: console_loglevel  将其改为8,KERN_DEBUG等级的也可以打印出来! */ 
    MESSAGE_LOGLEVEL_DEFAULT,    /*4: default_message_loglevel */
    CONSOLE_LOGLEVEL_MIN,        /*1: minimum_console_loglevel */
    CONSOLE_LOGLEVEL_DEFAULT,    /*7: default_console_loglevel */
};

4.实验

目前能打印的级别:7    4    1    7 (7打印不出来,高于7才能打印出来)

printk(KERN_ERR"kernel: %s: kernel error printed!
", __func__);    //能打印出来
printk(KERN_INFO"kernel: %s: kernel info printed!
", __func__);    //能打印出来
printk(KERN_DEBUG"kernel: %s: kernel debug printed!
", __func__);  //不能打印出来

但是此时使用dmesg都可以打印的出来:

[    5.171903] kernel: request_exclusive: kernel error printed!
[    5.217513] kernel: request_exclusive: kernel debug printed!
[    5.217517] kernel: request_exclusive: kernel info printed!

测试dmesg和dmesg -n 8是一样的!也就是#dmesg -n 8 只对打印到串口上的有影响,8会KERNEL_DEBUG也打印出来。但是它与dmesg dump出来的log无关。

//目前默认状态:
# cat /proc/sys/kernel/printk
    7    4    1    7
//dmesg -n 8后:
# cat /proc/sys/kernel/printk
    8    4    1    7

此时程序再打印KERN_DEBUG的信息也能打印出来了!

原文地址:https://www.cnblogs.com/hellokitty2/p/9867168.html