## printk()

printk输出到日志的内容可以用dmesg，普通的驱动问题靠输出的log定位问题就可以了。比如我要找HDMI的log：dmesg | grep HDMI。如果信息还不够多就加一个参数CONFIG_DEBUG_DRIVERkernel parameter里面，这会把来自Linux Kernel Driver Database的原始数据全都打印出来（非常非常多，除非写驱动的或者Debug找不到足够信息否则不要开）

printk有7个级别，见Message logging with printk。从0-7打印信息逐渐增加，调试的时候选一个合适的就行了

printk(KERN_WARNING "这里好像有问题，打印一下");

### Kernel Panic 后来不及printk

printk是异步的
printk.synchronous=1

printk()有一个问题，每次想添加printk()的时候都要重新编译（6.S081/6.828用的教学xv6那种几千行代码的玩具操作系统还好办，Linux内核这样庞大的东西CPU不太好的时候要编译很久的）

## 其他工具

systemtap，相当于一个kprobe的封装

## 调试的原理

### gdb

gdb的实现利用了ptrace的systemcall

### printk

printk: Why is it so complicated? Linux Plumbers Conf 的ppt
Why printk() is so complicated (and how to fix it)

## 你真的需要Debugger吗

Linus在邮件Re: Availability of kdb里是这样说的： I don't like debuggers. Never have, probably never will. I use gdb all the time, but I tend to use it not as a debugger, but as a disassembler on steroids that you can program.

I happen to believe that not having a kernel debugger forces people to think about their problem on a different level than with a debugger. I think that without a debugger, you don’t get into that mindset where you know how it behaves, and then you fix it from there. Without a debugger,you tend to think about problems another way. You want to understand things on a different level.

you start being careful, or you start whining about a kernel debugger.

Quite frankly, I’d rather weed out the people who don’t start being
careful early rather than late.

If you dive into the bug, you tend to fix the local issue in the code, but if you think about the bug first, how the bug came to be, you often find and correct a higher-level problem in the code that will improve the design and prevent further bugs.

（强烈推荐4k显示器，画质飞跃，头也不疼眼也不花了）

（据说一个大的显示屏有buff加成，据说，据说再在旁边摆一个小显示器开个终端也不错）

## 链接

《Debug Hacks 深入调试的技术和工具》 （吉冈弘隆） 这本书讲的很好，这还是之前我在图书馆乱逛无意间翻到的，结果发现是讲内核的，当时根本看不懂。今天又从图书馆翻出来了，发现讲的还挺好。

https://lwn.net/2000/0914/a/lt-debugger.php3
https://www.kernel.org/doc/html/v5.12-rc3/core-api/printk-basics.html

printk: Why is it so complicated? Linux Plumbers Conf 的ppt
Why printk() is so complicated (and how to fix it)

https://elinux.org/Debugging_by_printing

https://blog.csdn.net/tangkegagalikaiwu/article/details/8572365