← Documents Documentation/process/debugging/kgdb.rst GitHub 원문 ↗

Linux 6.18.37 · Debugging

KGDB, KDB와 kernel debugger internals

KGDB·KDB build option, kgdboc transport와 boot argument, serial·keyboard quick start, GDB 연결, test suite와 architecture hook을 설명합니다.

Source pathDocumentation/process/debugging/kgdb.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

KGDB와 KDB의 역할과 build option

kgdb.rst:2-122

KGDB는 remote GDB가 kernel execution을 제어하는 source-level debugger이고 KDB는 target console에서 register, task, memory와 breakpoint를 다루는 in-kernel shell이다. 두 frontend는 같은 debug core를 공유한다.

  • CONFIG_KGDB: debugger core
  • CONFIG_KGDB_SERIAL_CONSOLE: kgdboc serial transport
  • CONFIG_KGDB_KDB: KDB frontend
  • CONFIG_KDB_KEYBOARD: supported keyboard polling
  • CONFIG_DEBUG_INFO와 CONFIG_GDB_SCRIPTS: source-level symbol 조사
  • CONFIG_FRAME_POINTER 등 architecture에 맞는 stack unwinding option

kgdboc, earlycon, kgdbwait와 nokaslr

kgdb.rst:123-382

kgdboc는 tty device와 baud rate 같은 I/O console을 debugger transport로 사용한다. Built-in driver는 kernel command line에서, module은 load parameter 또는 sysfs runtime setting으로 구성할 수 있다.

kgdboc=ttyS0,115200 kgdbwait nokaslr
kgdboc_earlycon kgdboc=ttyS0,115200
kgdbcon
kgdbreboot=1

kgdbwait는 I/O driver가 준비된 뒤 debugger가 붙을 때까지 boot를 멈춘다. kgdboc_earlycon은 early console polling을 지원하는 driver에서 더 이른 entry를 가능하게 한다. kgdbcon은 printk를 debugger console로 전달하지만 debugger I/O와 normal console을 같은 port에서 공유할 때 제약을 확인한다. nokaslr은 vmlinux symbol과 runtime address를 직접 맞춘다.

Serial·keyboard에서 KDB 시작

kgdb.rst:383-496

Serial kgdboc를 구성한 뒤 SysRq-G 또는 debugger break sequence로 KDB에 진입한다. Keyboard console support가 있는 platform은 kdb keyboard polling을 사용할 수 있다. KDB의 help, ps, bt, bt <pid>, md, rd, bp, go command로 task와 register를 조사한다.

KDB가 모든 CPU를 멈추는 동안 normal scheduler와 interrupt-driven driver가 동작하지 않을 수 있다. Debug transport는 polling 가능해야 하고 filesystem·network 같은 blocking operation에 기대지 않는다.

Remote GDB 연결과 frontend 전환

kgdb.rst:497-661
gdb vmlinux
(gdb) set serial baud 115200
(gdb) target remote /dev/ttyUSB0
(gdb) continue

Host GDB는 target과 같은 vmlinux를 열고 serial 또는 network-backed remote transport에 연결한다. Module symbol은 runtime load address를 반영한다. KDB prompt에서 kgdb command로 GDB protocol mode로 전환하고 GDB에서 maintenance packet 또는 detach 절차로 KDB로 돌아갈 수 있다.

GDB에서도 monitor command로 일부 KDB command를 실행할 수 있다. Breakpoint와 single-step이 NMI, exception entry와 no-instrumentation 영역에서 안전한지는 architecture limitation을 확인한다.

Test suite와 architecture implementation

kgdb.rst:662-921

KGDB test suite는 breakpoint, single-step과 bad memory access 같은 core 동작을 자동 확인한다. Architecture port는 pt_regs mapping, breakpoint instruction, exception notification, single-step과 cache synchronization hook을 구현한다.

kgdboc driver는 UART의 normal interrupt path가 멈춘 상태에서도 character를 poll get·put할 수 있어야 한다. Keyboard와 KMS console도 debugger context에서 lock과 sleep 없이 접근 가능한 제한된 polling path를 사용한다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 =================================================
2 Using kgdb, kdb and the kernel debugger internals
3 =================================================
4
5 :Author: Jason Wessel
6
7 Introduction
8 ============
9
10 The kernel has two different debugger front ends (kdb and kgdb) which
11 interface to the debug core. It is possible to use either of the
12 debugger front ends and dynamically transition between them if you
13 configure the kernel properly at compile and runtime.
14
15 Kdb is simplistic shell-style interface which you can use on a system
16 console with a keyboard or serial console. You can use it to inspect
17 memory, registers, process lists, dmesg, and even set breakpoints to
18 stop in a certain location. Kdb is not a source level debugger, although
19 you can set breakpoints and execute some basic kernel run control. Kdb
20 is mainly aimed at doing some analysis to aid in development or
21 diagnosing kernel problems. You can access some symbols by name in
22 kernel built-ins or in kernel modules if the code was built with
23 ``CONFIG_KALLSYMS``.
24
25 Kgdb is intended to be used as a source level debugger for the Linux
26 kernel. It is used along with gdb to debug a Linux kernel. The
27 expectation is that gdb can be used to "break in" to the kernel to
28 inspect memory, variables and look through call stack information
29 similar to the way an application developer would use gdb to debug an
30 application. It is possible to place breakpoints in kernel code and
31 perform some limited execution stepping.
32
33 Two machines are required for using kgdb. One of these machines is a
34 development machine and the other is the target machine. The kernel to
35 be debugged runs on the target machine. The development machine runs an
36 instance of gdb against the vmlinux file which contains the symbols (not
37 a boot image such as bzImage, zImage, uImage...). In gdb the developer
38 specifies the connection parameters and connects to kgdb. The type of
39 connection a developer makes with gdb depends on the availability of
40 kgdb I/O modules compiled as built-ins or loadable kernel modules in the
41 test machine's kernel.
42
43 Compiling a kernel
44 ==================
45
46 - In order to enable compilation of kdb, you must first enable kgdb.
47
48 - The kgdb test compile options are described in the kgdb test suite
49 chapter.
50
51 Kernel config options for kgdb
52 ------------------------------
53
54 To enable ``CONFIG_KGDB`` you should look under
55 :menuselection:`Kernel hacking --> Kernel debugging` and select
56 :menuselection:`KGDB: kernel debugger`.
57
58 While it is not a hard requirement that you have symbols in your vmlinux
59 file, gdb tends not to be very useful without the symbolic data, so you
60 will want to turn on ``CONFIG_DEBUG_INFO`` which is called
61 :menuselection:`Compile the kernel with debug info` in the config menu.
62
63 It is advised, but not required, that you turn on the
64 ``CONFIG_FRAME_POINTER`` kernel option which is called :menuselection:`Compile
65 the kernel with frame pointers` in the config menu. This option inserts code
66 into the compiled executable which saves the frame information in registers
67 or on the stack at different points which allows a debugger such as gdb to
68 more accurately construct stack back traces while debugging the kernel.
69
70 If the architecture that you are using supports the kernel option
71 ``CONFIG_STRICT_KERNEL_RWX``, you should consider turning it off. This
72 option will prevent the use of software breakpoints because it marks
73 certain regions of the kernel's memory space as read-only. If kgdb
74 supports it for the architecture you are using, you can use hardware
75 breakpoints if you desire to run with the ``CONFIG_STRICT_KERNEL_RWX``
76 option turned on, else you need to turn off this option.
77
78 Next you should choose one or more I/O drivers to interconnect the debugging
79 host and debugged target. Early boot debugging requires a KGDB I/O
80 driver that supports early debugging and the driver must be built into
81 the kernel directly. Kgdb I/O driver configuration takes place via
82 kernel or module parameters which you can learn more about in the
83 section that describes the parameter kgdboc.
84
85 Here is an example set of ``.config`` symbols to enable or disable for kgdb::
86
87 # CONFIG_STRICT_KERNEL_RWX is not set
88 CONFIG_FRAME_POINTER=y
89 CONFIG_KGDB=y
90 CONFIG_KGDB_SERIAL_CONSOLE=y
91
92 Kernel config options for kdb
93 -----------------------------
94
95 Kdb is quite a bit more complex than the simple gdbstub sitting on top
96 of the kernel's debug core. Kdb must implement a shell, and also adds
97 some helper functions in other parts of the kernel, responsible for
98 printing out interesting data such as what you would see if you ran
99 ``lsmod``, or ``ps``. In order to build kdb into the kernel you follow the
100 same steps as you would for kgdb.
101
102 The main config option for kdb is ``CONFIG_KGDB_KDB`` which is called
103 :menuselection:`KGDB_KDB: include kdb frontend for kgdb` in the config menu.
104 In theory you would have already also selected an I/O driver such as the
105 ``CONFIG_KGDB_SERIAL_CONSOLE`` interface if you plan on using kdb on a
106 serial port, when you were configuring kgdb.
107
108 If you want to use a PS/2-style keyboard with kdb, you would select
109 ``CONFIG_KDB_KEYBOARD`` which is called :menuselection:`KGDB_KDB: keyboard as
110 input device` in the config menu. The ``CONFIG_KDB_KEYBOARD`` option is not
111 used for anything in the gdb interface to kgdb. The ``CONFIG_KDB_KEYBOARD``
112 option only works with kdb.
113
114 Here is an example set of ``.config`` symbols to enable/disable kdb::
115
116 # CONFIG_STRICT_KERNEL_RWX is not set
117 CONFIG_FRAME_POINTER=y
118 CONFIG_KGDB=y
119 CONFIG_KGDB_SERIAL_CONSOLE=y
120 CONFIG_KGDB_KDB=y
121 CONFIG_KDB_KEYBOARD=y
122
123 Kernel Debugger Boot Arguments
124 ==============================
125
126 This section describes the various runtime kernel parameters that affect
127 the configuration of the kernel debugger. The following chapter covers
128 using kdb and kgdb as well as providing some examples of the
129 configuration parameters.
130
131 Kernel parameter: kgdboc
132 ------------------------
133
134 The kgdboc driver was originally an abbreviation meant to stand for
135 "kgdb over console". Today it is the primary mechanism to configure how
136 to communicate from gdb to kgdb as well as the devices you want to use
137 to interact with the kdb shell.
138
139 For kgdb/gdb, kgdboc is designed to work with a single serial port. It
140 is intended to cover the circumstance where you want to use a serial
141 console as your primary console as well as using it to perform kernel
142 debugging. It is also possible to use kgdb on a serial port which is not
143 designated as a system console. Kgdboc may be configured as a kernel
144 built-in or a kernel loadable module. You can only make use of
145 ``kgdbwait`` and early debugging if you build kgdboc into the kernel as
146 a built-in.
147
148 Optionally you can elect to activate kms (Kernel Mode Setting)
149 integration. When you use kms with kgdboc and you have a video driver
150 that has atomic mode setting hooks, it is possible to enter the debugger
151 on the graphics console. When the kernel execution is resumed, the
152 previous graphics mode will be restored. This integration can serve as a
153 useful tool to aid in diagnosing crashes or doing analysis of memory
154 with kdb while allowing the full graphics console applications to run.
155
156 kgdboc arguments
157 ~~~~~~~~~~~~~~~~
158
159 Usage::
160
161 kgdboc=[kms][[,]kbd][[,]serial_device][,baud]
162
163 The order listed above must be observed if you use any of the optional
164 configurations together.
165
166 Abbreviations:
167
168 - kms = Kernel Mode Setting
169
170 - kbd = Keyboard
171
172 You can configure kgdboc to use the keyboard, and/or a serial device
173 depending on if you are using kdb and/or kgdb, in one of the following
174 scenarios. The order listed above must be observed if you use any of the
175 optional configurations together. Using kms + only gdb is generally not
176 a useful combination.
177
178 Using loadable module or built-in
179 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
180
181 1. As a kernel built-in:
182
183 Use the kernel boot argument::
184
185 kgdboc=<tty-device>,[baud]
186
187 2. As a kernel loadable module:
188
189 Use the command::
190
191 modprobe kgdboc kgdboc=<tty-device>,[baud]
192
193 Here are two examples of how you might format the kgdboc string. The
194 first is for an x86 target using the first serial port. The second
195 example is for the ARM Versatile AB using the second serial port.
196
197 1. ``kgdboc=ttyS0,115200``
198
199 2. ``kgdboc=ttyAMA1,115200``
200
201 Configure kgdboc at runtime with sysfs
202 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
203
204 At run time you can enable or disable kgdboc by writing parameters
205 into sysfs. Here are two examples:
206
207 1. Enable kgdboc on ttyS0::
208
209 echo ttyS0 > /sys/module/kgdboc/parameters/kgdboc
210
211 2. Disable kgdboc::
212
213 echo "" > /sys/module/kgdboc/parameters/kgdboc
214
215 .. note::
216
217 You do not need to specify the baud if you are configuring the
218 console on tty which is already configured or open.
219
220 More examples
221 ^^^^^^^^^^^^^
222
223 You can configure kgdboc to use the keyboard, and/or a serial device
224 depending on if you are using kdb and/or kgdb, in one of the following
225 scenarios.
226
227 1. kdb and kgdb over only a serial port::
228
229 kgdboc=<serial_device>[,baud]
230
231 Example::
232
233 kgdboc=ttyS0,115200
234
235 2. kdb and kgdb with keyboard and a serial port::
236
237 kgdboc=kbd,<serial_device>[,baud]
238
239 Example::
240
241 kgdboc=kbd,ttyS0,115200
242
243 3. kdb with a keyboard::
244
245 kgdboc=kbd
246
247 4. kdb with kernel mode setting::
248
249 kgdboc=kms,kbd
250
251 5. kdb with kernel mode setting and kgdb over a serial port::
252
253 kgdboc=kms,kbd,ttyS0,115200
254
255 .. note::
256
257 Kgdboc does not support interrupting the target via the gdb remote
258 protocol. You must manually send a `SysRq-G` unless you have a proxy
259 that splits console output to a terminal program. A console proxy has a
260 separate TCP port for the debugger and a separate TCP port for the
261 "human" console. The proxy can take care of sending the `SysRq-G`
262 for you.
263
264 When using kgdboc with no debugger proxy, you can end up connecting the
265 debugger at one of two entry points. If an exception occurs after you
266 have loaded kgdboc, a message should print on the console stating it is
267 waiting for the debugger. In this case you disconnect your terminal
268 program and then connect the debugger in its place. If you want to
269 interrupt the target system and forcibly enter a debug session you have
270 to issue a `Sysrq` sequence and then type the letter `g`. Then you
271 disconnect the terminal session and connect gdb. Your options if you
272 don't like this are to hack gdb to send the `SysRq-G` for you as well as
273 on the initial connect, or to use a debugger proxy that allows an
274 unmodified gdb to do the debugging.
275
276 Kernel parameter: ``kgdboc_earlycon``
277 -------------------------------------
278
279 If you specify the kernel parameter ``kgdboc_earlycon`` and your serial
280 driver registers a boot console that supports polling (doesn't need
281 interrupts and implements a nonblocking read() function) kgdb will attempt
282 to work using the boot console until it can transition to the regular
283 tty driver specified by the ``kgdboc`` parameter.
284
285 Normally there is only one boot console (especially that implements the
286 read() function) so just adding ``kgdboc_earlycon`` on its own is
287 sufficient to make this work. If you have more than one boot console you
288 can add the boot console's name to differentiate. Note that names that
289 are registered through the boot console layer and the tty layer are not
290 the same for the same port.
291
292 For instance, on one board to be explicit you might do::
293
294 kgdboc_earlycon=qcom_geni kgdboc=ttyMSM0
295
296 If the only boot console on the device was "qcom_geni", you could simplify::
297
298 kgdboc_earlycon kgdboc=ttyMSM0
299
300 Kernel parameter: ``kgdbwait``
301 ------------------------------
302
303 The Kernel command line option ``kgdbwait`` makes kgdb wait for a
304 debugger connection during booting of a kernel. You can only use this
305 option if you compiled a kgdb I/O driver into the kernel and you
306 specified the I/O driver configuration as a kernel command line option.
307 The kgdbwait parameter should always follow the configuration parameter
308 for the kgdb I/O driver in the kernel command line else the I/O driver
309 will not be configured prior to asking the kernel to use it to wait.
310
311 The kernel will stop and wait as early as the I/O driver and
312 architecture allows when you use this option. If you build the kgdb I/O
313 driver as a loadable kernel module kgdbwait will not do anything.
314
315 Kernel parameter: ``kgdbcon``
316 -----------------------------
317
318 The ``kgdbcon`` feature allows you to see printk() messages inside gdb
319 while gdb is connected to the kernel. Kdb does not make use of the kgdbcon
320 feature.
321
322 Kgdb supports using the gdb serial protocol to send console messages to
323 the debugger when the debugger is connected and running. There are two
324 ways to activate this feature.
325
326 1. Activate with the kernel command line option::
327
328 kgdbcon
329
330 2. Use sysfs before configuring an I/O driver::
331
332 echo 1 > /sys/module/debug_core/parameters/kgdb_use_con
333
334 .. note::
335
336 If you do this after you configure the kgdb I/O driver, the
337 setting will not take effect until the next point the I/O is
338 reconfigured.
339
340 .. important::
341
342 You cannot use kgdboc + kgdbcon on a tty that is an
343 active system console. An example of incorrect usage is::
344
345 console=ttyS0,115200 kgdboc=ttyS0 kgdbcon
346
347 It is possible to use this option with kgdboc on a tty that is not a
348 system console.
349
350 Run time parameter: ``kgdbreboot``
351 ----------------------------------
352
353 The kgdbreboot feature allows you to change how the debugger deals with
354 the reboot notification. You have 3 choices for the behavior. The
355 default behavior is always set to 0.
356
357 .. tabularcolumns:: |p{0.4cm}|p{11.5cm}|p{5.6cm}|
358
359 .. flat-table::
360 :widths: 1 10 8
361
362 * - 1
363 - ``echo -1 > /sys/module/debug_core/parameters/kgdbreboot``
364 - Ignore the reboot notification entirely.
365
366 * - 2
367 - ``echo 0 > /sys/module/debug_core/parameters/kgdbreboot``
368 - Send the detach message to any attached debugger client.
369
370 * - 3
371 - ``echo 1 > /sys/module/debug_core/parameters/kgdbreboot``
372 - Enter the debugger on reboot notify.
373
374 Kernel parameter: ``nokaslr``
375 -----------------------------
376
377 If the architecture that you are using enables KASLR by default,
378 you should consider turning it off. KASLR randomizes the
379 virtual address where the kernel image is mapped and confuses
380 gdb which resolves addresses of kernel symbols from the symbol table
381 of vmlinux.
382
383 Using kdb
384 =========
385
386 Quick start for kdb on a serial port
387 ------------------------------------
388
389 This is a quick example of how to use kdb.
390
391 1. Configure kgdboc at boot using kernel parameters::
392
393 console=ttyS0,115200 kgdboc=ttyS0,115200 nokaslr
394
395 OR
396
397 Configure kgdboc after the kernel has booted; assuming you are using
398 a serial port console::
399
400 echo ttyS0 > /sys/module/kgdboc/parameters/kgdboc
401
402 2. Enter the kernel debugger manually or by waiting for an oops or
403 fault. There are several ways you can enter the kernel debugger
404 manually; all involve using the `SysRq-G`, which means you must have
405 enabled ``CONFIG_MAGIC_SYSRQ=y`` in your kernel config.
406
407 - When logged in as root or with a super user session you can run::
408
409 echo g > /proc/sysrq-trigger
410
411 - Example using minicom 2.2
412
413 Press: `CTRL-A` `f` `g`
414
415 - When you have telneted to a terminal server that supports sending
416 a remote break
417
418 Press: `CTRL-]`
419
420 Type in: ``send break``
421
422 Press: `Enter` `g`
423
424 3. From the kdb prompt you can run the ``help`` command to see a complete
425 list of the commands that are available.
426
427 Some useful commands in kdb include:
428
429 =========== =================================================================
430 ``lsmod`` Shows where kernel modules are loaded
431 ``ps`` Displays only the active processes
432 ``ps A`` Shows all the processes
433 ``summary`` Shows kernel version info and memory usage
434 ``bt`` Get a backtrace of the current process using dump_stack()
435 ``dmesg`` View the kernel syslog buffer
436 ``go`` Continue the system
437 =========== =================================================================
438
439 4. When you are done using kdb you need to consider rebooting the system
440 or using the ``go`` command to resuming normal kernel execution. If you
441 have paused the kernel for a lengthy period of time, applications
442 that rely on timely networking or anything to do with real wall clock
443 time could be adversely affected, so you should take this into
444 consideration when using the kernel debugger.
445
446 Quick start for kdb using a keyboard connected console
447 ------------------------------------------------------
448
449 This is a quick example of how to use kdb with a keyboard.
450
451 1. Configure kgdboc at boot using kernel parameters::
452
453 kgdboc=kbd
454
455 OR
456
457 Configure kgdboc after the kernel has booted::
458
459 echo kbd > /sys/module/kgdboc/parameters/kgdboc
460
461 2. Enter the kernel debugger manually or by waiting for an oops or
462 fault. There are several ways you can enter the kernel debugger
463 manually; all involve using the `SysRq-G`, which means you must have
464 enabled ``CONFIG_MAGIC_SYSRQ=y`` in your kernel config.
465
466 - When logged in as root or with a super user session you can run::
467
468 echo g > /proc/sysrq-trigger
469
470 - Example using a laptop keyboard:
471
472 Press and hold down: `Alt`
473
474 Press and hold down: `Fn`
475
476 Press and release the key with the label: `SysRq`
477
478 Release: `Fn`
479
480 Press and release: `g`
481
482 Release: `Alt`
483
484 - Example using a PS/2 101-key keyboard
485
486 Press and hold down: `Alt`
487
488 Press and release the key with the label: `SysRq`
489
490 Press and release: `g`
491
492 Release: `Alt`
493
494 3. Now type in a kdb command such as ``help``, ``dmesg``, ``bt`` or ``go`` to
495 continue kernel execution.
496
497 Using kgdb / gdb
498 ================
499
500 In order to use kgdb you must activate it by passing configuration
501 information to one of the kgdb I/O drivers. If you do not pass any
502 configuration information kgdb will not do anything at all. Kgdb will
503 only actively hook up to the kernel trap hooks if a kgdb I/O driver is
504 loaded and configured. If you unconfigure a kgdb I/O driver, kgdb will
505 unregister all the kernel hook points.
506
507 All kgdb I/O drivers can be reconfigured at run time, if
508 ``CONFIG_SYSFS`` and ``CONFIG_MODULES`` are enabled, by echo'ing a new
509 config string to ``/sys/module/<driver>/parameter/<option>``. The driver
510 can be unconfigured by passing an empty string. You cannot change the
511 configuration while the debugger is attached. Make sure to detach the
512 debugger with the ``detach`` command prior to trying to unconfigure a
513 kgdb I/O driver.
514
515 Connecting with gdb to a serial port
516 ------------------------------------
517
518 1. Configure kgdboc
519
520 Configure kgdboc at boot using kernel parameters::
521
522 kgdboc=ttyS0,115200
523
524 OR
525
526 Configure kgdboc after the kernel has booted::
527
528 echo ttyS0 > /sys/module/kgdboc/parameters/kgdboc
529
530 2. Stop kernel execution (break into the debugger)
531
532 In order to connect to gdb via kgdboc, the kernel must first be
533 stopped. There are several ways to stop the kernel which include
534 using kgdbwait as a boot argument, via a `SysRq-G`, or running the
535 kernel until it takes an exception where it waits for the debugger to
536 attach.
537
538 - When logged in as root or with a super user session you can run::
539
540 echo g > /proc/sysrq-trigger
541
542 - Example using minicom 2.2
543
544 Press: `CTRL-A` `f` `g`
545
546 - When you have telneted to a terminal server that supports sending
547 a remote break
548
549 Press: `CTRL-]`
550
551 Type in: ``send break``
552
553 Press: `Enter` `g`
554
555 3. Connect from gdb
556
557 Example (using a directly connected port)::
558
559 % gdb ./vmlinux
560 (gdb) set serial baud 115200
561 (gdb) target remote /dev/ttyS0
562
563
564 Example (kgdb to a terminal server on TCP port 2012)::
565
566 % gdb ./vmlinux
567 (gdb) target remote 192.168.2.2:2012
568
569
570 Once connected, you can debug a kernel the way you would debug an
571 application program.
572
573 If you are having problems connecting or something is going seriously
574 wrong while debugging, it will most often be the case that you want
575 to enable gdb to be verbose about its target communications. You do
576 this prior to issuing the ``target remote`` command by typing in::
577
578 set debug remote 1
579
580 Remember if you continue in gdb, and need to "break in" again, you need
581 to issue an other `SysRq-G`. It is easy to create a simple entry point by
582 putting a breakpoint at ``sys_sync`` and then you can run ``sync`` from a
583 shell or script to break into the debugger.
584
585 kgdb and kdb interoperability
586 =============================
587
588 It is possible to transition between kdb and kgdb dynamically. The debug
589 core will remember which you used the last time and automatically start
590 in the same mode.
591
592 Switching between kdb and kgdb
593 ------------------------------
594
595 Switching from kgdb to kdb
596 ~~~~~~~~~~~~~~~~~~~~~~~~~~
597
598 There are two ways to switch from kgdb to kdb: you can use gdb to issue
599 a maintenance packet, or you can blindly type the command ``$3#33``.
600 Whenever the kernel debugger stops in kgdb mode it will print the
601 message ``KGDB or $3#33 for KDB``. It is important to note that you have
602 to type the sequence correctly in one pass. You cannot type a backspace
603 or delete because kgdb will interpret that as part of the debug stream.
604
605 1. Change from kgdb to kdb by blindly typing::
606
607 $3#33
608
609 2. Change from kgdb to kdb with gdb::
610
611 maintenance packet 3
612
613 .. note::
614
615 Now you must kill gdb. Typically you press `CTRL-Z` and issue
616 the command::
617
618 kill -9 %
619
620 Change from kdb to kgdb
621 ~~~~~~~~~~~~~~~~~~~~~~~
622
623 There are two ways you can change from kdb to kgdb. You can manually
624 enter kgdb mode by issuing the kgdb command from the kdb shell prompt,
625 or you can connect gdb while the kdb shell prompt is active. The kdb
626 shell looks for the typical first commands that gdb would issue with the
627 gdb remote protocol and if it sees one of those commands it
628 automatically changes into kgdb mode.
629
630 1. From kdb issue the command::
631
632 kgdb
633
634 2. At the kdb prompt, disconnect the terminal program and connect gdb in
635 its place.
636
637 Running kdb commands from gdb
638 -----------------------------
639
640 It is possible to run a limited set of kdb commands from gdb, using the
641 gdb monitor command. You don't want to execute any of the run control or
642 breakpoint operations, because it can disrupt the state of the kernel
643 debugger. You should be using gdb for breakpoints and run control
644 operations if you have gdb connected. The more useful commands to run
645 are things like lsmod, dmesg, ps or possibly some of the memory
646 information commands. To see all the kdb commands you can run
647 ``monitor help``.
648
649 Example::
650
651 (gdb) monitor ps
652 1 idle process (state I) and
653 27 sleeping system daemon (state M) processes suppressed,
654 use 'ps A' to see all.
655 Task Addr Pid Parent [*] cpu State Thread Command
656
657 0xc78291d0 1 0 0 0 S 0xc7829404 init
658 0xc7954150 942 1 0 0 S 0xc7954384 dropbear
659 0xc78789c0 944 1 0 0 S 0xc7878bf4 sh
660 (gdb)
661
662 kgdb Test Suite
663 ===============
664
665 When kgdb is enabled in the kernel config you can also elect to enable
666 the config parameter ``KGDB_TESTS``. Turning this on will enable a special
667 kgdb I/O module which is designed to test the kgdb internal functions.
668
669 The kgdb tests are mainly intended for developers to test the kgdb
670 internals as well as a tool for developing a new kgdb architecture
671 specific implementation. These tests are not really for end users of the
672 Linux kernel. The primary source of documentation would be to look in
673 the ``drivers/misc/kgdbts.c`` file.
674
675 The kgdb test suite can also be configured at compile time to run the
676 core set of tests by setting the kernel config parameter
677 ``KGDB_TESTS_ON_BOOT``. This particular option is aimed at automated
678 regression testing and does not require modifying the kernel boot config
679 arguments. If this is turned on, the kgdb test suite can be disabled by
680 specifying ``kgdbts=`` as a kernel boot argument.
681
682 Kernel Debugger Internals
683 =========================
684
685 Architecture Specifics
686 ----------------------
687
688 The kernel debugger is organized into a number of components:
689
690 1. The debug core
691
692 The debug core is found in ``kernel/debugger/debug_core.c``. It
693 contains:
694
695 - A generic OS exception handler which includes sync'ing the
696 processors into a stopped state on an multi-CPU system.
697
698 - The API to talk to the kgdb I/O drivers
699
700 - The API to make calls to the arch-specific kgdb implementation
701
702 - The logic to perform safe memory reads and writes to memory while
703 using the debugger
704
705 - A full implementation for software breakpoints unless overridden
706 by the arch
707
708 - The API to invoke either the kdb or kgdb frontend to the debug
709 core.
710
711 - The structures and callback API for atomic kernel mode setting.
712
713 .. note:: kgdboc is where the kms callbacks are invoked.
714
715 2. kgdb arch-specific implementation
716
717 This implementation is generally found in ``arch/*/kernel/kgdb.c``. As
718 an example, ``arch/x86/kernel/kgdb.c`` contains the specifics to
719 implement HW breakpoint as well as the initialization to dynamically
720 register and unregister for the trap handlers on this architecture.
721 The arch-specific portion implements:
722
723 - contains an arch-specific trap catcher which invokes
724 kgdb_handle_exception() to start kgdb about doing its work
725
726 - translation to and from gdb specific packet format to struct pt_regs
727
728 - Registration and unregistration of architecture specific trap
729 hooks
730
731 - Any special exception handling and cleanup
732
733 - NMI exception handling and cleanup
734
735 - (optional) HW breakpoints
736
737 3. gdbstub frontend (aka kgdb)
738
739 The gdbstub is located in ``kernel/debug/gdbstub.c``. It contains:
740
741 - All the logic to implement the gdb serial protocol
742
743 4. kdb frontend
744
745 The kdb debugger shell is broken down into a number of components.
746 The kdb core is located in kernel/debug/kdb. There are a number of
747 helper functions in some of the other kernel components to make it
748 possible for kdb to examine and report information about the kernel
749 without taking locks that could cause a kernel deadlock. The kdb core
750 implements the following functionality.
751
752 - A simple shell
753
754 - The kdb core command set
755
756 - A registration API to register additional kdb shell commands.
757
758 - A good example of a self-contained kdb module is the ``ftdump``
759 command for dumping the ftrace buffer. See:
760 ``kernel/trace/trace_kdb.c``
761
762 - For an example of how to dynamically register a new kdb command
763 you can build the kdb_hello.ko kernel module from
764 ``samples/kdb/kdb_hello.c``. To build this example you can set
765 ``CONFIG_SAMPLES=y`` and ``CONFIG_SAMPLE_KDB=m`` in your kernel
766 config. Later run ``modprobe kdb_hello`` and the next time you
767 enter the kdb shell, you can run the ``hello`` command.
768
769 - The implementation for kdb_printf() which emits messages directly
770 to I/O drivers, bypassing the kernel log.
771
772 - SW / HW breakpoint management for the kdb shell
773
774 5. kgdb I/O driver
775
776 Each kgdb I/O driver has to provide an implementation for the
777 following:
778
779 - configuration via built-in or module
780
781 - dynamic configuration and kgdb hook registration calls
782
783 - read and write character interface
784
785 - A cleanup handler for unconfiguring from the kgdb core
786
787 - (optional) Early debug methodology
788
789 Any given kgdb I/O driver has to operate very closely with the
790 hardware and must do it in such a way that does not enable interrupts
791 or change other parts of the system context without completely
792 restoring them. The kgdb core will repeatedly "poll" a kgdb I/O
793 driver for characters when it needs input. The I/O driver is expected
794 to return immediately if there is no data available. Doing so allows
795 for the future possibility to touch watchdog hardware in such a way
796 as to have a target system not reset when these are enabled.
797
798 If you are intent on adding kgdb architecture specific support for a new
799 architecture, the architecture should define ``HAVE_ARCH_KGDB`` in the
800 architecture specific Kconfig file. This will enable kgdb for the
801 architecture, and at that point you must create an architecture specific
802 kgdb implementation.
803
804 There are a few flags which must be set on every architecture in their
805 ``asm/kgdb.h`` file. These are:
806
807 - ``NUMREGBYTES``:
808 The size in bytes of all of the registers, so that we
809 can ensure they will all fit into a packet.
810
811 - ``BUFMAX``:
812 The size in bytes of the buffer GDB will read into. This must
813 be larger than NUMREGBYTES.
814
815 - ``CACHE_FLUSH_IS_SAFE``:
816 Set to 1 if it is always safe to call
817 flush_cache_range or flush_icache_range. On some architectures,
818 these functions may not be safe to call on SMP since we keep other
819 CPUs in a holding pattern.
820
821 There are also the following functions for the common backend, found in
822 ``kernel/kgdb.c``, that must be supplied by the architecture-specific
823 backend unless marked as (optional), in which case a default function
824 maybe used if the architecture does not need to provide a specific
825 implementation.
826
827 .. kernel-doc:: include/linux/kgdb.h
828 :internal:
829
830 kgdboc internals
831 ----------------
832
833 kgdboc and uarts
834 ~~~~~~~~~~~~~~~~
835
836 The kgdboc driver is actually a very thin driver that relies on the
837 underlying low level to the hardware driver having "polling hooks" to
838 which the tty driver is attached. In the initial implementation of
839 kgdboc the serial_core was changed to expose a low level UART hook for
840 doing polled mode reading and writing of a single character while in an
841 atomic context. When kgdb makes an I/O request to the debugger, kgdboc
842 invokes a callback in the serial core which in turn uses the callback in
843 the UART driver.
844
845 When using kgdboc with a UART, the UART driver must implement two
846 callbacks in the struct uart_ops.
847 Example from ``drivers/8250.c``::
848
849
850 #ifdef CONFIG_CONSOLE_POLL
851 .poll_get_char = serial8250_get_poll_char,
852 .poll_put_char = serial8250_put_poll_char,
853 #endif
854
855
856 Any implementation specifics around creating a polling driver use the
857 ``#ifdef CONFIG_CONSOLE_POLL``, as shown above. Keep in mind that
858 polling hooks have to be implemented in such a way that they can be
859 called from an atomic context and have to restore the state of the UART
860 chip on return such that the system can return to normal when the
861 debugger detaches. You need to be very careful with any kind of lock you
862 consider, because failing here is most likely going to mean pressing the
863 reset button.
864
865 kgdboc and keyboards
866 ~~~~~~~~~~~~~~~~~~~~~~~~
867
868 The kgdboc driver contains logic to configure communications with an
869 attached keyboard. The keyboard infrastructure is only compiled into the
870 kernel when ``CONFIG_KDB_KEYBOARD=y`` is set in the kernel configuration.
871
872 The core polled keyboard driver for PS/2 type keyboards is in
873 ``drivers/char/kdb_keyboard.c``. This driver is hooked into the debug core
874 when kgdboc populates the callback in the array called
875 :c:expr:`kdb_poll_funcs[]`. The kdb_get_kbd_char() is the top-level
876 function which polls hardware for single character input.
877
878 kgdboc and kms
879 ~~~~~~~~~~~~~~~~~~
880
881 The kgdboc driver contains logic to request the graphics display to
882 switch to a text context when you are using ``kgdboc=kms,kbd``, provided
883 that you have a video driver which has a frame buffer console and atomic
884 kernel mode setting support.
885
886 Every time the kernel debugger is entered it calls
887 kgdboc_pre_exp_handler() which in turn calls con_debug_enter()
888 in the virtual console layer. On resuming kernel execution, the kernel
889 debugger calls kgdboc_post_exp_handler() which in turn calls
890 con_debug_leave().
891
892 Any video driver that wants to be compatible with the kernel debugger
893 and the atomic kms callbacks must implement the ``mode_set_base_atomic``,
894 ``fb_debug_enter`` and ``fb_debug_leave operations``. For the
895 ``fb_debug_enter`` and ``fb_debug_leave`` the option exists to use the
896 generic drm fb helper functions or implement something custom for the
897 hardware. The following example shows the initialization of the
898 .mode_set_base_atomic operation in
899 drivers/gpu/drm/i915/intel_display.c::
900
901
902 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
903 [...]
904 .mode_set_base_atomic = intel_pipe_set_base_atomic,
905 [...]
906 };
907
908
909 Here is an example of how the i915 driver initializes the
910 fb_debug_enter and fb_debug_leave functions to use the generic drm
911 helpers in ``drivers/gpu/drm/i915/intel_fb.c``::
912
913
914 static struct fb_ops intelfb_ops = {
915 [...]
916 .fb_debug_enter = drm_fb_helper_debug_enter,
917 .fb_debug_leave = drm_fb_helper_debug_leave,
918 [...]
919 };
920
921
922 Credits
923 =======
924
925 The following people have contributed to this document:
926
927 1. Amit Kale <amitkale@linsyssoft.com>
928
929 2. Tom Rini <trini@kernel.crashing.org>
930
931 In March 2008 this document was completely rewritten by:
932
933 - Jason Wessel <jason.wessel@windriver.com>
934
935 In Jan 2010 this document was updated to include kdb.
936
937 - Jason Wessel <jason.wessel@windriver.com>
938

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

kdb, kgdb와 debug core

1-41

커널에는 공통 debug core 위에서 동작하는 kdb와 kgdb라는 두 디버거 프런트엔드가 있다. 커널 빌드 설정과 런타임 설정을 알맞게 구성하면 둘 가운데 하나만 사용할 수도 있고, 디버깅 도중 두 프런트엔드 사이를 전환할 수도 있다.

kdb는 시스템 콘솔의 키보드 또는 직렬 콘솔에서 사용하는 단순한 셸 형태 인터페이스다. 메모리, 레지스터, 프로세스 목록과 dmesg를 조사하고 특정 위치에 breakpoint를 설정할 수 있다. 기본적인 실행 제어는 제공하지만 소스 레벨 디버거는 아니며, 주 목적은 커널 개발과 장애 진단을 위한 현장 분석이다. CONFIG_KALLSYMS로 빌드했다면 커널 내장 코드와 모듈의 일부 심볼을 이름으로 참조할 수 있다.

kgdb는 Linux 커널을 소스 레벨에서 디버깅하기 위한 gdb 연동 인터페이스다. 응용 프로그램을 gdb로 분석하듯 커널 실행을 중단하고 메모리와 변수, 호출 스택을 살펴볼 수 있으며, 커널 코드에 breakpoint를 두고 제한적인 단일 단계 실행도 할 수 있다.

kgdb에는 개발 호스트와 디버깅 대상 장비 두 대가 필요하다. 대상 장비는 분석할 커널을 실행하고, 개발 호스트는 심볼이 포함된 vmlinux를 gdb에 연다. bzImage, zImage, uImage 같은 부팅 이미지는 심볼 분석용 파일이 아니다. gdb에서 연결 인수를 지정해 대상의 kgdb에 접속하며, 가능한 전송 방식은 대상 커널에 built-in 또는 모듈로 포함된 kgdb I/O 드라이버에 따라 달라진다.

kgdb 기본 연결 구조
개발 호스트전송 경로대상 장비
01 gdb + vmlinuxGDB remote serial protocolkgdb I/O driver
02 심볼·소스 좌표 해석명령/응답 패킷debug core + arch backend
03 breakpoint·레지스터 표시정지 상태에서 polling실행 중인 Linux kernel

호스트의 gdb는 심볼이 든 vmlinux를 읽고, 직렬선이나 프록시를 통해 대상 커널의 I/O 드라이버와 debug core에 명령을 보낸다.

kgdb 커널 빌드 설정

43-91

kdb를 빌드하려면 먼저 kgdb를 활성화해야 한다. kgdb 자체 시험 옵션은 이 문서 뒤의 test suite 절에서 설명한다. CONFIG_KGDB는 Kernel hacking → Kernel debugging → KGDB: kernel debugger 메뉴에서 선택한다.

vmlinux에 심볼이 없어도 kgdb 자체는 빌드할 수 있지만 gdb가 주소를 함수명과 소스 줄로 해석하지 못하므로 실용성이 크게 떨어진다. Compile the kernel with debug info 메뉴의 CONFIG_DEBUG_INFO를 켜는 것이 좋다.

필수는 아니지만 CONFIG_FRAME_POINTER도 권장한다. 이 옵션은 함수 프레임 정보를 레지스터나 스택에 보존하는 코드를 넣어 gdb가 커널 호출 스택을 더 정확하게 복원하도록 돕는다.

대상 아키텍처가 CONFIG_STRICT_KERNEL_RWX를 지원한다면 디버깅 빌드에서 끌지 검토한다. 이 옵션은 커널 메모리 일부를 읽기 전용으로 만들어 소프트웨어 breakpoint를 기록하지 못하게 한다. 해당 아키텍처의 kgdb가 하드웨어 breakpoint를 지원하면 STRICT_KERNEL_RWX를 유지할 수 있지만, 그렇지 않으면 소프트웨어 breakpoint를 위해 꺼야 한다.

호스트와 대상을 연결할 I/O 드라이버도 하나 이상 선택한다. early boot를 디버깅하려면 조기 polling을 지원하는 I/O 드라이버를 모듈이 아니라 커널에 직접 포함해야 한다. I/O 장치와 속도는 kgdboc 같은 커널 또는 모듈 인수로 지정한다.

# CONFIG_STRICT_KERNEL_RWX is not set
CONFIG_FRAME_POINTER=y
CONFIG_KGDB=y
CONFIG_KGDB_SERIAL_CONSOLE=y

kdb 커널 빌드 설정

92-121

kdb는 debug core 위에 얹힌 단순 gdbstub보다 구성 요소가 많다. 셸과 명령 해석기를 구현하며, lsmod와 ps에 해당하는 정보를 잠금 교착 없이 출력하기 위한 커널 내부 보조 함수도 사용한다. 기본 kgdb 설정을 마친 뒤 CONFIG_KGDB_KDB를 켜 kdb 프런트엔드를 포함한다.

직렬 포트에서 kdb를 쓸 계획이라면 CONFIG_KGDB_SERIAL_CONSOLE 같은 I/O 인터페이스가 필요하다. PS/2 형식 키보드를 입력 장치로 쓰려면 CONFIG_KDB_KEYBOARD를 선택한다. 이 키보드 옵션은 gdb와 kgdb 연결에는 쓰이지 않고 kdb에만 적용된다.

# CONFIG_STRICT_KERNEL_RWX is not set
CONFIG_FRAME_POINTER=y
CONFIG_KGDB=y
CONFIG_KGDB_SERIAL_CONSOLE=y
CONFIG_KGDB_KDB=y
CONFIG_KDB_KEYBOARD=y

kgdboc 부팅 인수와 런타임 구성

123-274

kgdboc는 원래 'kgdb over console'의 약자였으며, 현재는 gdb가 kgdb와 통신할 장치와 kdb 셸의 입력 장치를 지정하는 주된 구성 수단이다. kgdb/gdb 조합에서는 하나의 직렬 포트를 대상으로 설계되었다. 시스템의 기본 직렬 콘솔과 디버그 채널을 공유할 수도 있고, 콘솔로 지정되지 않은 별도 직렬 포트를 사용할 수도 있다.

kgdboc는 built-in 또는 모듈로 사용할 수 있지만 kgdbwait와 early debugging은 built-in일 때만 가능하다. 선택적으로 KMS 통합을 켜면 atomic mode setting hook을 제공하는 그래픽 드라이버에서 그래픽 콘솔 상태를 보존한 채 디버거의 텍스트 화면으로 들어갈 수 있고, 실행 재개 시 원래 그래픽 모드를 복원할 수 있다.

kgdboc=[kms][[,]kbd][[,]serial_device][,baud]

선택 인수를 함께 쓸 때는 kms, kbd, serial_device, baud 순서를 지켜야 한다. kms는 Kernel Mode Setting, kbd는 keyboard를 뜻한다. kdb와 kgdb 중 무엇을 쓸지에 따라 키보드와 직렬 장치를 조합한다. kdb 없이 gdb만 사용하면서 kms를 지정하는 조합은 일반적으로 유용하지 않다.

커널에 내장한 경우 부팅 명령행에 kgdboc=<tty-device>,[baud]를 지정한다. 모듈이면 modprobe kgdboc kgdboc=<tty-device>,[baud]를 사용한다. x86의 첫 직렬 포트 예는 ttyS0, ARM Versatile AB의 두 번째 포트 예는 ttyAMA1이다.

kgdboc=ttyS0,115200
kgdboc=ttyAMA1,115200

modprobe kgdboc kgdboc=ttyS0,115200

부팅 뒤에도 sysfs로 kgdboc를 켜거나 끌 수 있다. 이미 열려 있거나 console 설정으로 속도가 정해진 tty라면 baud를 다시 지정할 필요가 없다.

# ttyS0에서 kgdboc 활성화
echo ttyS0 > /sys/module/kgdboc/parameters/kgdboc

# kgdboc 비활성화
echo "" > /sys/module/kgdboc/parameters/kgdboc
사용 목적kgdboc 값
직렬 포트 하나에서 kdb와 kgdbkgdboc=ttyS0,115200
키보드 kdb + 직렬 kgdbkgdboc=kbd,ttyS0,115200
키보드만 사용하는 kdbkgdboc=kbd
KMS 화면 + 키보드 kdbkgdboc=kms,kbd
KMS/키보드 kdb + 직렬 kgdbkgdboc=kms,kbd,ttyS0,115200

kgdboc 자체는 gdb remote protocol로 실행 중인 대상을 중단시키는 기능을 제공하지 않는다. 콘솔 출력을 사람이 보는 터미널과 디버거용 TCP 포트로 분리하고 SysRq-G까지 대신 보내는 프록시가 없다면, 사용자가 직접 SysRq-G를 보내야 한다.

프록시가 없을 때는 예외 발생으로 kgdb가 디버거를 기다리는 메시지를 출력한 뒤 터미널 프로그램을 끊고 그 자리에 gdb를 연결하거나, 사용자가 SysRq 시퀀스와 g를 입력해 강제로 진입한 다음 터미널을 gdb로 교체한다. 이를 자동화하려면 gdb가 최초 연결 시 SysRq-G를 보내도록 수정하거나 별도 디버거 프록시를 사용한다.

kgdboc_earlycon과 kgdbwait

276-313

kgdboc_earlycon을 지정하고 직렬 드라이버가 polling 가능한 boot console을 등록하면, kgdb는 정규 tty 드라이버가 올라오기 전까지 boot console을 사용한다. 이 콘솔은 인터럽트가 없어도 동작해야 하고 nonblocking read()를 구현해야 한다. 이후 kgdboc 인수로 지정한 일반 tty 드라이버로 전환한다.

read를 지원하는 boot console이 하나뿐이면 이름 없이 kgdboc_earlycon만 지정해도 된다. 여러 boot console이 있으면 이름을 붙여 구별한다. 같은 물리 포트라도 boot console 계층의 이름과 tty 계층의 이름은 서로 다를 수 있다.

kgdboc_earlycon=qcom_geni kgdboc=ttyMSM0

# qcom_geni가 유일한 boot console이면
kgdboc_earlycon kgdboc=ttyMSM0

kgdbwait는 부팅 중 디버거가 연결될 때까지 커널을 멈춘다. 이를 사용하려면 kgdb I/O 드라이버가 built-in이어야 하고, 해당 드라이버의 설정 인수를 커널 명령행에 먼저 적어야 한다. 명령행 순서에서도 kgdbwait는 kgdboc 같은 I/O 설정 뒤에 와야 한다.

정지 가능한 시점은 I/O 드라이버와 아키텍처 구현이 허용하는 가장 이른 지점이다. I/O 드라이버를 모듈로 빌드하면 부팅 시점에 존재하지 않으므로 kgdbwait는 아무 동작도 하지 않는다.

조기 부팅 디버그 전환
커널
boot console 등록earlycon pollingtty 초기화tty 전환
디버거
kgdbwait접속 대기remote handshake디버깅 시작
time

boot console polling으로 시작해 정규 tty로 전환하고, kgdbwait에서 호스트 연결을 기다리는 순서다.

kgdbcon, kgdbreboot와 KASLR

315-381

kgdbcon은 gdb가 커널에 연결된 동안 printk() 메시지를 gdb 안에서 보게 한다. kdb는 이 기능을 사용하지 않는다. gdb serial protocol의 콘솔 메시지 패킷을 이용하며, 부팅 명령행에 kgdbcon을 쓰거나 I/O 드라이버를 구성하기 전에 sysfs의 kgdb_use_con을 1로 설정해 활성화한다.

kgdbcon

echo 1 > /sys/module/debug_core/parameters/kgdb_use_con

I/O 드라이버를 이미 구성한 뒤 sysfs 값을 바꾸면 다음 I/O 재구성 때까지 적용되지 않는다. 활성 시스템 콘솔인 tty 하나에 kgdboc와 kgdbcon을 동시에 사용할 수 없다. 예를 들어 console=ttyS0,115200 kgdboc=ttyS0 kgdbcon은 잘못된 조합이다. 시스템 콘솔이 아닌 별도 tty라면 kgdboc와 kgdbcon을 함께 쓸 수 있다.

kgdbreboot 값명령재부팅 알림 처리
-1echo -1 > /sys/module/debug_core/parameters/kgdbreboot재부팅 알림을 완전히 무시
0 (기본값)echo 0 > /sys/module/debug_core/parameters/kgdbreboot연결된 디버거에 detach 메시지 전송
1echo 1 > /sys/module/debug_core/parameters/kgdbreboot재부팅 알림 시 디버거 진입

대상 아키텍처가 기본으로 KASLR을 켠다면 nokaslr 사용을 검토한다. KASLR은 커널 이미지의 가상 매핑 주소를 무작위화하지만, gdb는 로컬 vmlinux 심볼 테이블의 고정 주소를 기준으로 심볼을 해석하므로 둘의 주소가 어긋날 수 있다.

직렬 콘솔에서 kdb 사용

383-444

직렬 포트 kdb의 빠른 시작은 먼저 부팅 명령행에서 console과 kgdboc를 같은 속도로 설정하고 주소 해석을 위해 nokaslr를 지정하는 것이다. 부팅 뒤라면 sysfs에 tty 이름을 기록해 kgdboc를 구성할 수 있다.

console=ttyS0,115200 kgdboc=ttyS0,115200 nokaslr

# 또는 부팅 뒤
echo ttyS0 > /sys/module/kgdboc/parameters/kgdboc

oops나 fault를 기다리지 않고 수동으로 진입하는 방법은 모두 SysRq-G를 사용하므로 CONFIG_MAGIC_SYSRQ=y가 필요하다. root 셸에서는 /proc/sysrq-trigger에 g를 쓰고, minicom 2.2에서는 CTRL-A, f, g를 누른다. remote break를 지원하는 터미널 서버의 telnet 세션에서는 CTRL-], send break, Enter, g 순서로 입력한다.

echo g > /proc/sysrq-trigger
kdb 명령기능
lsmod커널 모듈이 적재된 주소 표시
ps활성 프로세스만 표시
ps A모든 프로세스 표시
summary커널 버전과 메모리 사용량 표시
btdump_stack()을 이용한 현재 프로세스 backtrace
dmesg커널 syslog 버퍼 열람
go커널 실행 재개

help 명령으로 전체 명령을 확인한다. 작업을 마치면 시스템을 재부팅하거나 go로 실행을 재개한다. 커널을 오래 멈추면 네트워크 시간 제한과 실제 시각에 의존하는 응용 프로그램이 영향을 받을 수 있으므로, 디버거에서 보낸 시간 자체가 관측 대상의 상태를 바꾼다는 점을 고려해야 한다.

키보드 콘솔에서 kdb 사용

446-495

키보드 입력을 사용할 때는 부팅 인수 kgdboc=kbd를 지정하거나, 부팅 뒤 sysfs에 kbd를 기록한다. 수동 진입에는 직렬 방식과 마찬가지로 CONFIG_MAGIC_SYSRQ=y와 SysRq-G가 필요하다.

kgdboc=kbd

# 또는 부팅 뒤
echo kbd > /sys/module/kgdboc/parameters/kgdboc

echo g > /proc/sysrq-trigger

노트북 키보드에서는 Alt를 누른 채 Fn을 누르고 SysRq 키를 눌렀다 놓은 다음 Fn을 놓고 g를 눌렀다 놓은 뒤 Alt를 놓는다. PS/2 101키 키보드에서는 Alt를 누른 채 SysRq를 눌렀다 놓고 g를 누른 뒤 Alt를 놓는다. 실제 키 조합은 키보드 펌웨어와 SysRq 키 배치에 따라 다를 수 있다.

kdb 프롬프트가 나타나면 help, dmesg, bt 같은 조사 명령을 실행하고 go로 커널 실행을 계속한다.

kgdb와 gdb 연결

497-583

kgdb는 I/O 드라이버에 구성 정보를 전달해야 활성화된다. 설정되지 않은 상태에서는 커널 trap hook에도 연결되지 않는다. I/O 드라이버가 적재되고 구성되면 hook을 등록하고, 드라이버 구성을 해제하면 모든 커널 hook을 다시 제거한다.

CONFIG_SYSFS와 CONFIG_MODULES가 켜져 있으면 /sys/module/<driver>/parameter/<option>에 새 문자열을 기록해 런타임 재구성을 할 수 있고 빈 문자열로 해제할 수 있다. 디버거가 붙어 있는 동안에는 구성을 바꿀 수 없으므로 먼저 gdb의 detach 명령으로 연결을 종료해야 한다.

직렬 연결은 kgdboc=ttyS0,115200으로 부팅하거나 부팅 뒤 sysfs에서 ttyS0를 선택하는 것으로 시작한다. gdb가 연결하려면 대상 커널이 먼저 멈춰 있어야 한다. kgdbwait, SysRq-G 또는 예외 발생 후 디버거 대기 상태 가운데 하나를 사용한다.

kgdboc=ttyS0,115200

# 또는 부팅 뒤
echo ttyS0 > /sys/module/kgdboc/parameters/kgdboc

# 실행 중 커널을 중단
echo g > /proc/sysrq-trigger

개발 호스트에서는 부팅 이미지가 아니라 vmlinux를 gdb에 열고 직렬 속도와 remote target을 지정한다. 터미널 서버나 디버거 프록시를 사용한다면 장치 파일 대신 IP 주소와 TCP 포트를 지정한다.

% gdb ./vmlinux
(gdb) set serial baud 115200
(gdb) target remote /dev/ttyS0

# TCP 포트 2012의 터미널 서버
% gdb ./vmlinux
(gdb) target remote 192.168.2.2:2012

연결 실패나 protocol 이상을 추적하려면 target remote 전에 set debug remote 1을 실행해 gdb의 remote packet 로그를 켠다. gdb에서 continue한 뒤 다시 중단하려면 또 SysRq-G를 보내야 한다. 반복 진입점을 만들고 싶다면 sys_sync에 breakpoint를 두고 대상 셸이나 스크립트에서 sync를 실행하는 방법도 있다.

(gdb) set debug remote 1
(gdb) target remote /dev/ttyS0

kdb와 kgdb 사이 전환

585-660

kdb와 kgdb는 실행 중 동적으로 전환할 수 있다. debug core는 마지막으로 사용한 프런트엔드를 기억하고 다음 진입 때 같은 모드로 시작한다.

kgdb에서 kdb로 바꾸는 방법은 gdb maintenance packet을 보내거나 연결선에 $3#33을 직접 입력하는 두 가지다. kgdb 모드로 정지하면 콘솔에 'KGDB or $3#33 for KDB'가 표시된다. 이 바이트열은 한 번에 정확히 입력해야 하며 Backspace나 Delete도 debug stream의 일부로 해석된다.

# 연결선에 직접 입력
$3#33

# gdb에서 전환
(gdb) maintenance packet 3

maintenance packet으로 kdb에 넘긴 뒤에는 기존 gdb를 종료해야 한다. 원문은 CTRL-Z로 중지한 다음 kill -9 %를 실행하는 예를 든다.

kill -9 %

kdb에서 kgdb로 바꾸려면 kdb 프롬프트에서 kgdb 명령을 실행하거나, 터미널 프로그램을 끊고 그 자리에 gdb를 연결한다. kdb 셸은 gdb remote protocol이 처음 보내는 전형적인 패킷을 감지하면 자동으로 kgdb 모드로 바뀐다.

kdb> kgdb

gdb가 연결된 상태에서는 monitor 명령으로 일부 kdb 명령을 실행할 수 있다. 실행 제어와 breakpoint는 두 프런트엔드의 상태를 충돌시킬 수 있으므로 gdb 기능을 사용한다. monitor에서는 lsmod, dmesg, ps와 메모리 정보 명령이 유용하며 monitor help로 허용된 명령을 확인한다.

(gdb) monitor ps
1 idle process (state I) and
27 sleeping system daemon (state M) processes suppressed,
use 'ps A' to see all.
Task Addr       Pid   Parent [*] cpu State Thread     Command

0xc78291d0        1        0  0    0   S  0xc7829404  init
0xc7954150      942        1  0    0   S  0xc7954384  dropbear
0xc78789c0      944        1  0    0   S  0xc7878bf4  sh
(gdb)

kgdb test suite

662-680

CONFIG_KGDB를 켠 커널은 KGDB_TESTS도 선택할 수 있다. 이 옵션은 kgdb 내부 함수를 시험하도록 설계된 특수 I/O 모듈을 활성화한다. 주 대상은 일반 사용자보다 kgdb 내부 개발자와 새 아키텍처 backend를 구현하는 개발자이며, 가장 직접적인 설명은 drivers/misc/kgdbts.c 소스에 있다.

KGDB_TESTS_ON_BOOT를 켜면 핵심 시험 묶음을 부팅 때 자동 실행한다. 자동 회귀 시험을 위한 옵션이므로 별도 커널 명령행 수정이 필요하지 않다. 이 설정으로 빌드한 커널에서 시험을 막으려면 부팅 인수 kgdbts=를 지정한다.

debug core 내부

682-714

공통 debug core는 kernel/debugger/debug_core.c에 있다. 운영체제 예외를 받아 디버거 진입을 시작하고, SMP에서는 다른 CPU들을 정지 상태로 동기화한다. 정지된 커널에서 여러 CPU가 동시에 상태를 바꾸지 않도록 만드는 중심 계층이다.

  • kgdb I/O 드라이버와 통신하는 API
  • 아키텍처별 kgdb 구현을 호출하는 API
  • 디버거 문맥에서 메모리를 안전하게 읽고 쓰는 로직
  • 아키텍처가 덮어쓰지 않는 경우 사용할 공통 소프트웨어 breakpoint 구현
  • kdb 또는 kgdb 프런트엔드를 호출하는 API
  • atomic Kernel Mode Setting을 위한 구조체와 callback API

KMS callback을 실제로 호출하는 쪽은 kgdboc다. debug core는 공통 인터페이스와 진입·복귀 순서를 제공한다.

debug core 구성
CPU exception / SysRq-Garch trap hookkgdb_handle_exception()debug core: CPU stop·memory access·breakpointkgdb gdbstub 또는 kdb shellkgdb I/O driver polling

예외가 아키텍처 trap handler를 거쳐 공통 core로 들어온 뒤 선택된 프런트엔드와 I/O 드라이버로 분기한다.

아키텍처 backend, gdbstub과 kdb 프런트엔드

715-773

아키텍처별 구현은 보통 arch/*/kernel/kgdb.c에 있다. 예를 들어 arch/x86/kernel/kgdb.c는 하드웨어 breakpoint와 x86 trap handler를 동적으로 등록·해제하는 코드를 포함한다.

  • 아키텍처 예외를 포착하고 kgdb_handle_exception()을 호출하는 trap catcher
  • gdb 패킷의 레지스터 형식과 struct pt_regs 사이 변환
  • 아키텍처 trap hook 등록과 해제
  • 특수 예외 처리와 복귀 정리
  • NMI 예외 처리와 복귀 정리
  • 선택적인 하드웨어 breakpoint 구현

kgdb라고 부르는 gdbstub 프런트엔드는 kernel/debug/gdbstub.c에 있으며 GDB remote serial protocol 전체를 구현한다. 패킷 파싱, 레지스터와 메모리 요청, 실행 제어 응답이 이 계층에 속한다.

kdb 셸의 핵심은 kernel/debug/kdb에 있다. 다른 커널 하위 시스템에도 kdb가 잠금을 잡아 교착을 일으키지 않고 상태를 조사하도록 돕는 함수가 들어 있다. kdb core는 단순 셸, 기본 명령 집합, 추가 명령 등록 API와 breakpoint 관리를 구현한다.

독립적인 확장 예로 ftrace 버퍼를 출력하는 ftdump 명령은 kernel/trace/trace_kdb.c에 있다. samples/kdb/kdb_hello.c는 동적 명령 등록 예다. CONFIG_SAMPLES=y와 CONFIG_SAMPLE_KDB=m으로 빌드하고 modprobe kdb_hello를 실행하면 다음 kdb 진입부터 hello 명령을 사용할 수 있다.

kdb_printf()는 커널 로그를 거치지 않고 I/O 드라이버로 직접 메시지를 보낸다. 이는 일반 printk 경로가 정지된 CPU나 잠금에 의존할 수 있는 디버거 문맥에서 중요하다. kdb 셸은 자체 소프트웨어·하드웨어 breakpoint 관리도 제공한다.

kgdb I/O 드라이버와 아키텍처 계약

774-829

각 kgdb I/O 드라이버는 built-in 또는 모듈 인수 처리, 동적 구성과 kgdb hook 등록, 문자 단위 read/write, 구성 해제 시 cleanup handler를 제공해야 한다. 필요하면 early debug 방식도 구현한다.

I/O 드라이버는 하드웨어에 매우 가까운 문맥에서 동작한다. 인터럽트를 켜거나 다른 시스템 상태를 바꿨다면 반환 전에 완전히 복원해야 한다. debug core는 입력이 필요할 때 드라이버를 반복 polling하므로 데이터가 없으면 즉시 반환해야 한다. 이 비차단 규칙은 향후 polling 사이에 watchdog을 갱신해 디버깅 중 대상이 재설정되지 않게 할 가능성도 남긴다.

새 아키텍처에 kgdb를 추가하려면 아키텍처 Kconfig에서 HAVE_ARCH_KGDB를 정의하고 전용 backend를 작성한다. asm/kgdb.h에는 모든 레지스터를 패킷에 담는 데 필요한 NUMREGBYTES, GDB 입력 버퍼 크기 BUFMAX, 정지된 SMP 문맥에서도 cache flush가 안전한지를 나타내는 CACHE_FLUSH_IS_SAFE를 정의한다.

심볼의미와 제약
NUMREGBYTES모든 레지스터를 직렬화한 총 바이트 수
BUFMAXGDB가 읽을 패킷 버퍼 크기이며 NUMREGBYTES보다 커야 함
CACHE_FLUSH_IS_SAFEflush_cache_range/flush_icache_range를 항상 호출해도 안전하면 1; 다른 CPU를 holding 상태로 둔 SMP에서는 안전하지 않을 수 있음

공통 backend가 요구하는 나머지 함수 계약은 include/linux/kgdb.h의 kernel-doc에 정의된다. optional로 표시되지 않은 함수는 아키텍처 backend가 제공해야 하며, optional 함수는 공통 기본 구현을 사용할 수 있다.

.. kernel-doc:: include/linux/kgdb.h
   :internal:

kgdboc와 UART polling

830-863

kgdboc 자체는 얇은 연결 계층이다. tty가 붙은 하위 하드웨어 드라이버의 polling hook에 의존한다. 초기 구현에서는 serial_core가 atomic context에서도 UART 문자 하나를 polling으로 읽고 쓸 수 있는 저수준 hook을 노출하도록 변경되었다.

kgdb가 입출력을 요청하면 kgdboc가 serial core callback을 호출하고, serial core는 다시 실제 UART 드라이버 callback을 호출한다. UART 드라이버는 struct uart_ops에 poll_get_char와 poll_put_char를 구현해야 한다.

#ifdef CONFIG_CONSOLE_POLL
    .poll_get_char = serial8250_get_poll_char,
    .poll_put_char = serial8250_put_poll_char,
#endif

polling 구현은 CONFIG_CONSOLE_POLL로 조건부 빌드한다. callback은 atomic context에서 호출 가능해야 하고, 디버거 detach 뒤 시스템이 정상 동작하도록 UART 칩 상태를 원래대로 복원해야 한다. 이 경로의 잠금 선택을 잘못하면 인터럽트도 스케줄링도 기대할 수 없는 상태에서 교착되어 하드웨어 reset 외에는 복구 방법이 없을 수 있다.

UART 문자 한 개의 polling 경로
gdbstub 문자 요청debug core I/O APIkgdboc callbackserial_core polling hookuart_ops.poll_get_char / poll_put_charUART register

정지된 커널에서는 인터럽트 기반 tty 수신 대신 아래 callback 사슬을 동기적으로 왕복한다.

kgdboc 키보드와 KMS 통합

865-919

kgdboc의 키보드 통신 코드는 CONFIG_KDB_KEYBOARD=y일 때만 빌드된다. PS/2 키보드의 공통 polling 드라이버는 drivers/char/kdb_keyboard.c에 있다. kgdboc가 kdb_poll_funcs[] 배열에 callback을 등록하면 debug core와 연결되고, 최상위 kdb_get_kbd_char()가 하드웨어에서 문자 하나를 polling한다.

kgdboc=kms,kbd를 사용하고 frame buffer console 및 atomic KMS를 지원하는 그래픽 드라이버가 있으면, kgdboc는 디버거 진입 때 화면을 텍스트 문맥으로 전환한다. 진입 시 kgdboc_pre_exp_handler()가 virtual console의 con_debug_enter()를 호출하고, 실행 재개 시 kgdboc_post_exp_handler()가 con_debug_leave()를 호출한다.

kernel debugger와 atomic KMS callback을 지원하려는 영상 드라이버는 mode_set_base_atomic, fb_debug_enter, fb_debug_leave 동작을 구현해야 한다. fb_debug_enter와 fb_debug_leave에는 공통 DRM framebuffer helper를 사용하거나 하드웨어 전용 구현을 둘 수 있다.

static const struct drm_crtc_helper_funcs intel_helper_funcs = {
[...]
        .mode_set_base_atomic = intel_pipe_set_base_atomic,
[...]
};

static struct fb_ops intelfb_ops = {
[...]
       .fb_debug_enter = drm_fb_helper_debug_enter,
       .fb_debug_leave = drm_fb_helper_debug_leave,
[...]
};
KMS 디버거 진입과 복귀
debug corekgdbocvirtual console / DRM
01 예외 진입kgdboc_pre_exp_handler()con_debug_enter()
02 kdb 실행키보드 polling텍스트 콘솔 표시
03 go / continuekgdboc_post_exp_handler()con_debug_leave()
04 커널 실행 재개I/O 상태 복원기존 그래픽 모드 복원

그래픽 응용 화면을 보존하고 kdb 텍스트 콘솔로 전환한 뒤 원래 모드로 돌아오는 callback 순서다.

기여자

922-937

이 문서에는 Amit Kale과 Tom Rini가 기여했다. Jason Wessel이 2008년 3월 문서를 전면 개정했고, 2010년 1월 kdb 내용을 추가해 갱신했다.