Documentation/doc-guide/kernel-doc.rst GitHub 원문 ↗

Linux 6.18.37 · Documentation Guide

Writing Kernel-doc Comments

함수, 타입, 매크로와 개요를 위한 kernel-doc 주석 형식, 강조·교차 참조 규칙, Sphinx directive 옵션과 man page 생성법을 설명합니다.

Source pathDocumentation/doc-guide/kernel-doc.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

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

1. 요약·해설

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

요약과 해설

kernel-doc.rst:1-598

함수, 타입, 매크로와 개요를 위한 kernel-doc 주석 형식, 강조·교차 참조 규칙, Sphinx directive 옵션과 man page 생성법을 설명합니다. 영어 원문 전체와 한국어 전문 번역을 함께 제공하며 함수명, 타입, symbol, source path, 명령, ReST 역할과 directive, 원문 줄 좌표를 보존합니다.

2. 영어 원문 전체

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

원문 전체 펼치기
1 .. title:: Kernel-doc comments
2
3 ===========================
4 Writing kernel-doc comments
5 ===========================
6
7 The Linux kernel source files may contain structured documentation
8 comments in the kernel-doc format to describe the functions, types
9 and design of the code. It is easier to keep documentation up-to-date
10 when it is embedded in source files.
11
12 .. note:: The kernel-doc format is deceptively similar to javadoc,
13 gtk-doc or Doxygen, yet distinctively different, for historical
14 reasons. The kernel source contains tens of thousands of kernel-doc
15 comments. Please stick to the style described here.
16
17 .. note:: kernel-doc does not cover Rust code: please see
18 Documentation/rust/general-information.rst instead.
19
20 The kernel-doc structure is extracted from the comments, and proper
21 `Sphinx C Domain`_ function and type descriptions with anchors are
22 generated from them. The descriptions are filtered for special kernel-doc
23 highlights and cross-references. See below for details.
24
25 .. _Sphinx C Domain: http://www.sphinx-doc.org/en/stable/domains.html
26
27 Every function that is exported to loadable modules using
28 ``EXPORT_SYMBOL`` or ``EXPORT_SYMBOL_GPL`` should have a kernel-doc
29 comment. Functions and data structures in header files which are intended
30 to be used by modules should also have kernel-doc comments.
31
32 It is good practice to also provide kernel-doc formatted documentation
33 for functions externally visible to other kernel files (not marked
34 ``static``). We also recommend providing kernel-doc formatted
35 documentation for private (file ``static``) routines, for consistency of
36 kernel source code layout. This is lower priority and at the discretion
37 of the maintainer of that kernel source file.
38
39 How to format kernel-doc comments
40 ---------------------------------
41
42 The opening comment mark ``/**`` is used for kernel-doc comments. The
43 ``kernel-doc`` tool will extract comments marked this way. The rest of
44 the comment is formatted like a normal multi-line comment with a column
45 of asterisks on the left side, closing with ``*/`` on a line by itself.
46
47 The function and type kernel-doc comments should be placed just before
48 the function or type being described in order to maximise the chance
49 that somebody changing the code will also change the documentation. The
50 overview kernel-doc comments may be placed anywhere at the top indentation
51 level.
52
53 Running the ``kernel-doc`` tool with increased verbosity and without actual
54 output generation may be used to verify proper formatting of the
55 documentation comments. For example::
56
57 scripts/kernel-doc -v -none drivers/foo/bar.c
58
59 The documentation format is verified by the kernel build when it is
60 requested to perform extra gcc checks::
61
62 make W=n
63
64 Function documentation
65 ----------------------
66
67 The general format of a function and function-like macro kernel-doc comment is::
68
69 /**
70 * function_name() - Brief description of function.
71 * @arg1: Describe the first argument.
72 * @arg2: Describe the second argument.
73 * One can provide multiple line descriptions
74 * for arguments.
75 *
76 * A longer description, with more discussion of the function function_name()
77 * that might be useful to those using or modifying it. Begins with an
78 * empty comment line, and may include additional embedded empty
79 * comment lines.
80 *
81 * The longer description may have multiple paragraphs.
82 *
83 * Context: Describes whether the function can sleep, what locks it takes,
84 * releases, or expects to be held. It can extend over multiple
85 * lines.
86 * Return: Describe the return value of function_name.
87 *
88 * The return value description can also have multiple paragraphs, and should
89 * be placed at the end of the comment block.
90 */
91
92 The brief description following the function name may span multiple lines, and
93 ends with an argument description, a blank comment line, or the end of the
94 comment block.
95
96 Function parameters
97 ~~~~~~~~~~~~~~~~~~~
98
99 Each function argument should be described in order, immediately following
100 the short function description. Do not leave a blank line between the
101 function description and the arguments, nor between the arguments.
102
103 Each ``@argument:`` description may span multiple lines.
104
105 .. note::
106
107 If the ``@argument`` description has multiple lines, the continuation
108 of the description should start at the same column as the previous line::
109
110 * @argument: some long description
111 * that continues on next lines
112
113 or::
114
115 * @argument:
116 * some long description
117 * that continues on next lines
118
119 If a function has a variable number of arguments, its description should
120 be written in kernel-doc notation as::
121
122 * @...: description
123
124 Function context
125 ~~~~~~~~~~~~~~~~
126
127 The context in which a function can be called should be described in a
128 section named ``Context``. This should include whether the function
129 sleeps or can be called from interrupt context, as well as what locks
130 it takes, releases and expects to be held by its caller.
131
132 Examples::
133
134 * Context: Any context.
135 * Context: Any context. Takes and releases the RCU lock.
136 * Context: Any context. Expects <lock> to be held by caller.
137 * Context: Process context. May sleep if @gfp flags permit.
138 * Context: Process context. Takes and releases <mutex>.
139 * Context: Softirq or process context. Takes and releases <lock>, BH-safe.
140 * Context: Interrupt context.
141
142 Return values
143 ~~~~~~~~~~~~~
144
145 The return value, if any, should be described in a dedicated section
146 named ``Return`` (or ``Returns``).
147
148 .. note::
149
150 #) The multi-line descriptive text you provide does *not* recognize
151 line breaks, so if you try to format some text nicely, as in::
152
153 * Return:
154 * %0 - OK
155 * %-EINVAL - invalid argument
156 * %-ENOMEM - out of memory
157
158 this will all run together and produce::
159
160 Return: 0 - OK -EINVAL - invalid argument -ENOMEM - out of memory
161
162 So, in order to produce the desired line breaks, you need to use a
163 ReST list, e. g.::
164
165 * Return:
166 * * %0 - OK to runtime suspend the device
167 * * %-EBUSY - Device should not be runtime suspended
168
169 #) If the descriptive text you provide has lines that begin with
170 some phrase followed by a colon, each of those phrases will be taken
171 as a new section heading, which probably won't produce the desired
172 effect.
173
174 Structure, union, and enumeration documentation
175 -----------------------------------------------
176
177 The general format of a struct, union, and enum kernel-doc comment is::
178
179 /**
180 * struct struct_name - Brief description.
181 * @member1: Description of member1.
182 * @member2: Description of member2.
183 * One can provide multiple line descriptions
184 * for members.
185 *
186 * Description of the structure.
187 */
188
189 You can replace the ``struct`` in the above example with ``union`` or
190 ``enum`` to describe unions or enums. ``member`` is used to mean struct
191 and union member names as well as enumerations in an enum.
192
193 The brief description following the structure name may span multiple
194 lines, and ends with a member description, a blank comment line, or the
195 end of the comment block.
196
197 Members
198 ~~~~~~~
199
200 Members of structs, unions and enums should be documented the same way
201 as function parameters; they immediately succeed the short description
202 and may be multi-line.
203
204 Inside a struct or union description, you can use the ``private:`` and
205 ``public:`` comment tags. Structure fields that are inside a ``private:``
206 area are not listed in the generated output documentation.
207
208 The ``private:`` and ``public:`` tags must begin immediately following a
209 ``/*`` comment marker. They may optionally include comments between the
210 ``:`` and the ending ``*/`` marker.
211
212 Example::
213
214 /**
215 * struct my_struct - short description
216 * @a: first member
217 * @b: second member
218 * @d: fourth member
219 *
220 * Longer description
221 */
222 struct my_struct {
223 int a;
224 int b;
225 /* private: internal use only */
226 int c;
227 /* public: the next one is public */
228 int d;
229 };
230
231 Nested structs/unions
232 ~~~~~~~~~~~~~~~~~~~~~
233
234 It is possible to document nested structs and unions, like::
235
236 /**
237 * struct nested_foobar - a struct with nested unions and structs
238 * @memb1: first member of anonymous union/anonymous struct
239 * @memb2: second member of anonymous union/anonymous struct
240 * @memb3: third member of anonymous union/anonymous struct
241 * @memb4: fourth member of anonymous union/anonymous struct
242 * @bar: non-anonymous union
243 * @bar.st1: struct st1 inside @bar
244 * @bar.st2: struct st2 inside @bar
245 * @bar.st1.memb1: first member of struct st1 on union bar
246 * @bar.st1.memb2: second member of struct st1 on union bar
247 * @bar.st2.memb1: first member of struct st2 on union bar
248 * @bar.st2.memb2: second member of struct st2 on union bar
249 */
250 struct nested_foobar {
251 /* Anonymous union/struct*/
252 union {
253 struct {
254 int memb1;
255 int memb2;
256 };
257 struct {
258 void *memb3;
259 int memb4;
260 };
261 };
262 union {
263 struct {
264 int memb1;
265 int memb2;
266 } st1;
267 struct {
268 void *memb1;
269 int memb2;
270 } st2;
271 } bar;
272 };
273
274 .. note::
275
276 #) When documenting nested structs or unions, if the struct/union ``foo``
277 is named, the member ``bar`` inside it should be documented as
278 ``@foo.bar:``
279 #) When the nested struct/union is anonymous, the member ``bar`` in it
280 should be documented as ``@bar:``
281
282 In-line member documentation comments
283 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
284
285 The structure members may also be documented in-line within the definition.
286 There are two styles, single-line comments where both the opening ``/**`` and
287 closing ``*/`` are on the same line, and multi-line comments where they are each
288 on a line of their own, like all other kernel-doc comments::
289
290 /**
291 * struct foo - Brief description.
292 * @foo: The Foo member.
293 */
294 struct foo {
295 int foo;
296 /**
297 * @bar: The Bar member.
298 */
299 int bar;
300 /**
301 * @baz: The Baz member.
302 *
303 * Here, the member description may contain several paragraphs.
304 */
305 int baz;
306 union {
307 /** @foobar: Single line description. */
308 int foobar;
309 };
310 /** @bar2: Description for struct @bar2 inside @foo */
311 struct {
312 /**
313 * @bar2.barbar: Description for @barbar inside @foo.bar2
314 */
315 int barbar;
316 } bar2;
317 };
318
319 Typedef documentation
320 ---------------------
321
322 The general format of a typedef kernel-doc comment is::
323
324 /**
325 * typedef type_name - Brief description.
326 *
327 * Description of the type.
328 */
329
330 Typedefs with function prototypes can also be documented::
331
332 /**
333 * typedef type_name - Brief description.
334 * @arg1: description of arg1
335 * @arg2: description of arg2
336 *
337 * Description of the type.
338 *
339 * Context: Locking context.
340 * Returns: Meaning of the return value.
341 */
342 typedef void (*type_name)(struct v4l2_ctrl *arg1, void *arg2);
343
344 Object-like macro documentation
345 -------------------------------
346
347 Object-like macros are distinct from function-like macros. They are
348 differentiated by whether the macro name is immediately followed by a
349 left parenthesis ('(') for function-like macros or not followed by one
350 for object-like macros.
351
352 Function-like macros are handled like functions by ``scripts/kernel-doc``.
353 They may have a parameter list. Object-like macros have do not have a
354 parameter list.
355
356 The general format of an object-like macro kernel-doc comment is::
357
358 /**
359 * define object_name - Brief description.
360 *
361 * Description of the object.
362 */
363
364 Example::
365
366 /**
367 * define MAX_ERRNO - maximum errno value that is supported
368 *
369 * Kernel pointers have redundant information, so we can use a
370 * scheme where we can return either an error code or a normal
371 * pointer with the same return value.
372 */
373 #define MAX_ERRNO 4095
374
375 Example::
376
377 /**
378 * define DRM_GEM_VRAM_PLANE_HELPER_FUNCS - \
379 * Initializes struct drm_plane_helper_funcs for VRAM handling
380 *
381 * This macro initializes struct drm_plane_helper_funcs to use the
382 * respective helper functions.
383 */
384 #define DRM_GEM_VRAM_PLANE_HELPER_FUNCS \
385 .prepare_fb = drm_gem_vram_plane_helper_prepare_fb, \
386 .cleanup_fb = drm_gem_vram_plane_helper_cleanup_fb
387
388
389 Highlights and cross-references
390 -------------------------------
391
392 The following special patterns are recognized in the kernel-doc comment
393 descriptive text and converted to proper reStructuredText markup and `Sphinx C
394 Domain`_ references.
395
396 .. attention:: The below are **only** recognized within kernel-doc comments,
397 **not** within normal reStructuredText documents.
398
399 ``funcname()``
400 Function reference.
401
402 ``@parameter``
403 Name of a function parameter. (No cross-referencing, just formatting.)
404
405 ``%CONST``
406 Name of a constant. (No cross-referencing, just formatting.)
407
408 ````literal````
409 A literal block that should be handled as-is. The output will use a
410 ``monospaced font``.
411
412 Useful if you need to use special characters that would otherwise have some
413 meaning either by kernel-doc script or by reStructuredText.
414
415 This is particularly useful if you need to use things like ``%ph`` inside
416 a function description.
417
418 ``$ENVVAR``
419 Name of an environment variable. (No cross-referencing, just formatting.)
420
421 ``&struct name``
422 Structure reference.
423
424 ``&enum name``
425 Enum reference.
426
427 ``&typedef name``
428 Typedef reference.
429
430 ``&struct_name->member`` or ``&struct_name.member``
431 Structure or union member reference. The cross-reference will be to the struct
432 or union definition, not the member directly.
433
434 ``&name``
435 A generic type reference. Prefer using the full reference described above
436 instead. This is mostly for legacy comments.
437
438 Cross-referencing from reStructuredText
439 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
440
441 No additional syntax is needed to cross-reference the functions and types
442 defined in the kernel-doc comments from reStructuredText documents.
443 Just end function names with ``()`` and write ``struct``, ``union``, ``enum``
444 or ``typedef`` before types.
445 For example::
446
447 See foo().
448 See struct foo.
449 See union bar.
450 See enum baz.
451 See typedef meh.
452
453 However, if you want custom text in the cross-reference link, that can be done
454 through the following syntax::
455
456 See :c:func:`my custom link text for function foo <foo>`.
457 See :c:type:`my custom link text for struct bar <bar>`.
458
459 For further details, please refer to the `Sphinx C Domain`_ documentation.
460
461 Overview documentation comments
462 -------------------------------
463
464 To facilitate having source code and comments close together, you can include
465 kernel-doc documentation blocks that are free-form comments instead of being
466 kernel-doc for functions, structures, unions, enums, or typedefs. This could be
467 used for something like a theory of operation for a driver or library code, for
468 example.
469
470 This is done by using a ``DOC:`` section keyword with a section title.
471
472 The general format of an overview or high-level documentation comment is::
473
474 /**
475 * DOC: Theory of Operation
476 *
477 * The whizbang foobar is a dilly of a gizmo. It can do whatever you
478 * want it to do, at any time. It reads your mind. Here's how it works.
479 *
480 * foo bar splat
481 *
482 * The only drawback to this gizmo is that is can sometimes damage
483 * hardware, software, or its subject(s).
484 */
485
486 The title following ``DOC:`` acts as a heading within the source file, but also
487 as an identifier for extracting the documentation comment. Thus, the title must
488 be unique within the file.
489
490 =============================
491 Including kernel-doc comments
492 =============================
493
494 The documentation comments may be included in any of the reStructuredText
495 documents using a dedicated kernel-doc Sphinx directive extension.
496
497 The kernel-doc directive is of the format::
498
499 .. kernel-doc:: source
500 :option:
501
502 The *source* is the path to a source file, relative to the kernel source
503 tree. The following directive options are supported:
504
505 export: *[source-pattern ...]*
506 Include documentation for all functions in *source* that have been exported
507 using ``EXPORT_SYMBOL`` or ``EXPORT_SYMBOL_GPL`` either in *source* or in any
508 of the files specified by *source-pattern*.
509
510 The *source-pattern* is useful when the kernel-doc comments have been placed
511 in header files, while ``EXPORT_SYMBOL`` and ``EXPORT_SYMBOL_GPL`` are next to
512 the function definitions.
513
514 Examples::
515
516 .. kernel-doc:: lib/bitmap.c
517 :export:
518
519 .. kernel-doc:: include/net/mac80211.h
520 :export: net/mac80211/*.c
521
522 internal: *[source-pattern ...]*
523 Include documentation for all functions and types in *source* that have
524 **not** been exported using ``EXPORT_SYMBOL`` or ``EXPORT_SYMBOL_GPL`` either
525 in *source* or in any of the files specified by *source-pattern*.
526
527 Example::
528
529 .. kernel-doc:: drivers/gpu/drm/i915/intel_audio.c
530 :internal:
531
532 identifiers: *[ function/type ...]*
533 Include documentation for each *function* and *type* in *source*.
534 If no *function* is specified, the documentation for all functions
535 and types in the *source* will be included.
536 *type* can be a struct, union, enum, or typedef identifier.
537
538 Examples::
539
540 .. kernel-doc:: lib/bitmap.c
541 :identifiers: bitmap_parselist bitmap_parselist_user
542
543 .. kernel-doc:: lib/idr.c
544 :identifiers:
545
546 no-identifiers: *[ function/type ...]*
547 Exclude documentation for each *function* and *type* in *source*.
548
549 Example::
550
551 .. kernel-doc:: lib/bitmap.c
552 :no-identifiers: bitmap_parselist
553
554 functions: *[ function/type ...]*
555 This is an alias of the 'identifiers' directive and deprecated.
556
557 doc: *title*
558 Include documentation for the ``DOC:`` paragraph identified by *title* in
559 *source*. Spaces are allowed in *title*; do not quote the *title*. The *title*
560 is only used as an identifier for the paragraph, and is not included in the
561 output. Please make sure to have an appropriate heading in the enclosing
562 reStructuredText document.
563
564 Example::
565
566 .. kernel-doc:: drivers/gpu/drm/i915/intel_audio.c
567 :doc: High Definition Audio over HDMI and Display Port
568
569 Without options, the kernel-doc directive includes all documentation comments
570 from the source file.
571
572 The kernel-doc extension is included in the kernel source tree, at
573 ``Documentation/sphinx/kerneldoc.py``. Internally, it uses the
574 ``scripts/kernel-doc`` script to extract the documentation comments from the
575 source.
576
577 .. _kernel_doc:
578
579 How to use kernel-doc to generate man pages
580 -------------------------------------------
581
582 If you just want to use kernel-doc to generate man pages you can do this
583 from the kernel git tree::
584
585 $ scripts/kernel-doc -man \
586 $(git grep -l '/\*\*' -- :^Documentation :^tools) \
587 | scripts/split-man.pl /tmp/man
588
589 Some older versions of git do not support some of the variants of syntax for
590 path exclusion. One of the following commands may work for those versions::
591
592 $ scripts/kernel-doc -man \
593 $(git grep -l '/\*\*' -- . ':!Documentation' ':!tools') \
594 | scripts/split-man.pl /tmp/man
595
596 $ scripts/kernel-doc -man \
597 $(git grep -l '/\*\*' -- . ":(exclude)Documentation" ":(exclude)tools") \
598 | scripts/split-man.pl /tmp/man
599

3. 한국어 전문 번역

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

kernel-doc 주석의 목적과 적용 범위

1-38

Linux 커널 소스 파일에는 함수, 타입, 코드 설계를 설명하는 구조화된 `kernel-doc` 형식의 문서 주석을 넣을 수 있습니다. 문서를 소스 파일 안에 두면 코드와 함께 최신 상태로 유지하기가 더 쉽습니다.

`kernel-doc` 형식은 겉보기에는 javadoc, gtk-doc, Doxygen과 비슷하지만 역사적인 이유로 명확히 다른 규칙을 사용합니다. 커널 소스에는 수만 개의 kernel-doc 주석이 있으므로 이 문서에서 설명하는 스타일을 따라야 합니다. Rust 코드는 kernel-doc 대상이 아니며 `Documentation/rust/general-information.rst`를 참고해야 합니다.

도구는 주석에서 kernel-doc 구조를 추출하고 anchor가 붙은 올바른 `Sphinx C Domain` 함수·타입 설명을 생성합니다. 설명에 있는 kernel-doc 전용 강조 표기와 교차 참조도 변환합니다. Sphinx C Domain 문서는 `http://www.sphinx-doc.org/en/stable/domains.html`에서 확인할 수 있습니다.

로드 가능한 모듈에 `EXPORT_SYMBOL` 또는 `EXPORT_SYMBOL_GPL`로 내보내는 모든 함수에는 kernel-doc 주석이 있어야 합니다. 모듈이 사용하도록 의도한 헤더 파일의 함수와 자료 구조도 마찬가지입니다.

`static`으로 표시하지 않아 다른 커널 파일에서 볼 수 있는 함수에도 kernel-doc 형식 문서를 제공하는 것이 좋습니다. 소스 배치를 일관되게 유지하려면 파일 전용 `static` 루틴에도 문서를 작성하는 것이 권장되지만, 우선순위는 더 낮으며 해당 소스 파일 maintainer의 판단에 따릅니다.

주석 배치와 형식 검사

39-63

kernel-doc 주석은 여는 표식 `/**`로 시작합니다. `kernel-doc` 도구는 이 표식이 있는 주석을 추출합니다. 나머지는 왼쪽에 별표 열을 둔 일반 여러 줄 주석처럼 작성하고, 별도 줄의 `*/`로 닫습니다.

함수와 타입을 설명하는 주석은 코드 변경자가 문서도 함께 바꿀 가능성을 높이도록 대상 함수나 타입 바로 앞에 둡니다. 개요용 kernel-doc 주석은 최상위 들여쓰기 수준의 어느 위치에나 둘 수 있습니다.

실제 출력을 생성하지 않고 `kernel-doc`의 상세 출력을 높여 주석 형식을 검사할 수 있습니다.

scripts/kernel-doc -v -none drivers/foo/bar.c

커널 빌드에 추가 gcc 검사를 요청하면 문서 형식도 검증됩니다. `n`은 원하는 경고 수준으로 바꿉니다.

make W=n

함수와 함수형 매크로 문서

64-95

함수 및 함수형 매크로의 kernel-doc 주석은 함수 이름과 짧은 설명, 순서대로 나열한 인수 설명, 선택적인 긴 설명, 호출 문맥, 반환값 설명으로 구성합니다.

/**
 * function_name() - Brief description of function.
 * @arg1: Describe the first argument.
 * @arg2: Describe the second argument.
 *        One can provide multiple line descriptions
 *        for arguments.
 *
 * A longer description, with more discussion of the function function_name()
 * that might be useful to those using or modifying it. Begins with an
 * empty comment line, and may include additional embedded empty
 * comment lines.
 *
 * The longer description may have multiple paragraphs.
 *
 * Context: Describes whether the function can sleep, what locks it takes,
 *          releases, or expects to be held. It can extend over multiple
 *          lines.
 * Return: Describe the return value of function_name.
 *
 * The return value description can also have multiple paragraphs, and should
 * be placed at the end of the comment block.
 */

함수 이름 뒤의 짧은 설명은 여러 줄에 걸칠 수 있습니다. 인수 설명이 시작되거나 빈 주석 줄 또는 주석 블록의 끝을 만나면 짧은 설명이 끝납니다. 긴 설명은 빈 주석 줄 뒤에서 시작하며 여러 문단을 포함할 수 있습니다. `Context`와 `Return`은 정해진 의미를 갖는 절 이름이고, 반환값 설명은 주석 블록 끝에 두어야 합니다.

함수 매개변수 표기

96-123

각 함수 인수는 짧은 함수 설명 바로 다음에 선언 순서대로 설명합니다. 함수 설명과 인수 사이 또는 인수들 사이에 빈 줄을 두지 않습니다. 각 `@argument:` 설명은 여러 줄로 이어질 수 있습니다.

여러 줄 설명의 후속 줄은 앞 줄의 설명이 시작된 열에 맞춰야 합니다. 한 줄에서 설명을 시작하거나, 인수 이름 뒤를 비우고 다음 줄을 추가로 들여쓰는 두 형식을 사용할 수 있습니다.

   * @argument: some long description
   *            that continues on next lines

or::

   * @argument:
   *                some long description
   *                that continues on next lines

가변 인수 함수는 kernel-doc 표기 `@...:`를 사용하여 가변 인수를 설명합니다.

* @...: description

호출 문맥과 반환값

124-173

함수를 호출할 수 있는 문맥은 `Context` 절에 기술합니다. 함수가 sleep할 수 있는지, interrupt context에서 호출할 수 있는지, 어떤 lock을 획득하거나 해제하는지, 호출자가 어떤 lock을 보유해야 하는지를 포함해야 합니다.

* Context: Any context.
* Context: Any context. Takes and releases the RCU lock.
* Context: Any context. Expects <lock> to be held by caller.
* Context: Process context. May sleep if @gfp flags permit.
* Context: Process context. Takes and releases <mutex>.
* Context: Softirq or process context. Takes and releases <lock>, BH-safe.
* Context: Interrupt context.

반환값이 있다면 `Return` 또는 `Returns`라는 전용 절에서 설명합니다.

여러 줄 설명 텍스트는 단순한 줄바꿈을 보존하지 않습니다. 따라서 값을 줄마다 보기 좋게 적더라도 다음 예처럼 하나의 연속된 문장으로 합쳐집니다.

   * Return:
   * %0 - OK
   * %-EINVAL - invalid argument
   * %-ENOMEM - out of memory

this will all run together and produce::

   Return: 0 - OK -EINVAL - invalid argument -ENOMEM - out of memory

원하는 줄 구분을 만들려면 ReST 목록을 사용해야 합니다.

* Return:
* * %0                - OK to runtime suspend the device
* * %-EBUSY        - Device should not be runtime suspended

또한 설명 줄이 어떤 구문과 콜론으로 시작하면 그 구문을 새로운 절 제목으로 인식합니다. 의도하지 않은 절이 생기지 않도록 반환값 설명의 문장 구조를 주의해야 합니다.

구조체·공용체·열거형 문서

174-230

`struct`, `union`, `enum`의 일반 형식은 타입 이름과 짧은 설명, `@member` 항목, 선택적인 긴 설명으로 구성합니다.

/**
 * struct struct_name - Brief description.
 * @member1: Description of member1.
 * @member2: Description of member2.
 *           One can provide multiple line descriptions
 *           for members.
 *
 * Description of the structure.
 */

공용체나 열거형을 설명할 때는 예제의 `struct`를 `union` 또는 `enum`으로 바꿉니다. 여기서 member는 구조체·공용체 멤버뿐 아니라 enum의 열거자도 뜻합니다. 타입 이름 뒤의 짧은 설명은 여러 줄일 수 있으며 멤버 설명, 빈 주석 줄, 블록 끝 중 하나에서 종료됩니다.

구조체, 공용체, 열거형의 멤버는 함수 매개변수와 같은 방식으로 문서화합니다. 짧은 설명 바로 뒤에 두며 여러 줄로 작성할 수 있습니다.

구조체나 공용체 설명 안에서는 `private:`와 `public:` 주석 태그를 사용할 수 있습니다. `private:` 영역의 필드는 생성된 출력 문서에 나타나지 않습니다. 두 태그는 `/*` 주석 표식 바로 뒤에서 시작해야 하며 콜론과 닫는 `*/` 사이에 선택적인 설명을 넣을 수 있습니다.

/**
 * struct my_struct - short description
 * @a: first member
 * @b: second member
 * @d: fourth member
 *
 * Longer description
 */
struct my_struct {
    int a;
    int b;
/* private: internal use only */
    int c;
/* public: the next one is public */
    int d;
};

중첩 구조체와 공용체

231-281

중첩 구조체와 공용체의 멤버는 바깥쪽 이름부터 점으로 연결한 경로로 문서화할 수 있습니다. 다음 예는 익명 중첩 타입의 멤버와 이름이 있는 `bar` 공용체 내부의 `st1`, `st2` 구조체 및 그 멤버를 모두 기술합니다.

/**
 * struct nested_foobar - a struct with nested unions and structs
 * @memb1: first member of anonymous union/anonymous struct
 * @memb2: second member of anonymous union/anonymous struct
 * @memb3: third member of anonymous union/anonymous struct
 * @memb4: fourth member of anonymous union/anonymous struct
 * @bar: non-anonymous union
 * @bar.st1: struct st1 inside @bar
 * @bar.st2: struct st2 inside @bar
 * @bar.st1.memb1: first member of struct st1 on union bar
 * @bar.st1.memb2: second member of struct st1 on union bar
 * @bar.st2.memb1: first member of struct st2 on union bar
 * @bar.st2.memb2: second member of struct st2 on union bar
 */
struct nested_foobar {
  /* Anonymous union/struct*/
  union {
    struct {
      int memb1;
      int memb2;
    };
    struct {
      void *memb3;
      int memb4;
    };
  };
  union {
    struct {
      int memb1;
      int memb2;
    } st1;
    struct {
      void *memb1;
      int memb2;
    } st2;
  } bar;
};

중첩 구조체 또는 공용체 `foo`에 이름이 있으면 그 안의 `bar` 멤버를 `@foo.bar:`로 문서화합니다. 중첩 구조체나 공용체가 익명이면 내부 `bar` 멤버를 단순히 `@bar:`로 문서화합니다.

인라인 멤버 문서 주석

282-318

구조체 멤버는 정의 내부에서 인라인으로도 문서화할 수 있습니다. 여는 `/**`와 닫는 `*/`가 같은 줄에 있는 한 줄 형식과, 다른 kernel-doc 주석처럼 두 표식이 각각 별도 줄에 있는 여러 줄 형식을 모두 지원합니다.

/**
 * struct foo - Brief description.
 * @foo: The Foo member.
 */
struct foo {
      int foo;
      /**
       * @bar: The Bar member.
       */
      int bar;
      /**
       * @baz: The Baz member.
       *
       * Here, the member description may contain several paragraphs.
       */
      int baz;
      union {
              /** @foobar: Single line description. */
              int foobar;
      };
      /** @bar2: Description for struct @bar2 inside @foo */
      struct {
              /**
               * @bar2.barbar: Description for @barbar inside @foo.bar2
               */
              int barbar;
      } bar2;
};

인라인 주석에서도 `@bar`, `@baz`, `@foobar`처럼 해당 멤버를 지목합니다. 중첩된 이름 있는 멤버는 `@bar2.barbar`처럼 전체 경로로 표시할 수 있고, 여러 줄 멤버 설명에는 여러 문단을 넣을 수 있습니다.

typedef 문서

319-343

일반 typedef는 `typedef type_name - 짧은 설명` 뒤에 빈 주석 줄과 타입의 긴 설명을 둡니다.

/**
 * typedef type_name - Brief description.
 *
 * Description of the type.
 */

함수 prototype을 담은 typedef도 문서화할 수 있습니다. 함수처럼 인수를 나열하고 긴 설명, `Context`, `Returns`를 추가한 뒤 실제 함수 포인터 typedef 선언을 배치합니다.

/**
 * typedef type_name - Brief description.
 * @arg1: description of arg1
 * @arg2: description of arg2
 *
 * Description of the type.
 *
 * Context: Locking context.
 * Returns: Meaning of the return value.
 */
 typedef void (*type_name)(struct v4l2_ctrl *arg1, void *arg2);

객체형 매크로 문서

344-388

객체형 매크로는 함수형 매크로와 구분됩니다. 매크로 이름 바로 뒤에 왼쪽 괄호 `(`가 있으면 함수형이고, 괄호가 없으면 객체형입니다. `scripts/kernel-doc`는 함수형 매크로를 매개변수 목록을 가질 수 있는 함수처럼 처리하지만 객체형 매크로에는 매개변수 목록이 없습니다.

객체형 매크로의 일반 형식은 `define object_name - 짧은 설명`과 선택적인 긴 설명입니다.

/**
 * define object_name - Brief description.
 *
 * Description of the object.
 */

`MAX_ERRNO` 예제는 지원하는 최대 errno 값과, 커널 포인터의 중복 정보를 이용해 오류 코드와 정상 포인터를 같은 반환값 형식으로 전달하는 이유를 설명합니다.

/**
 * define MAX_ERRNO - maximum errno value that is supported
 *
 * Kernel pointers have redundant information, so we can use a
 * scheme where we can return either an error code or a normal
 * pointer with the same return value.
 */
#define MAX_ERRNO        4095

여러 줄 매크로도 같은 방식으로 문서화합니다. `DRM_GEM_VRAM_PLANE_HELPER_FUNCS` 예제는 VRAM 처리용 `drm_plane_helper_funcs`를 각 helper 함수로 초기화하는 매크로를 설명합니다.

/**
 * define DRM_GEM_VRAM_PLANE_HELPER_FUNCS - \
 *        Initializes struct drm_plane_helper_funcs for VRAM handling
 *
 * This macro initializes struct drm_plane_helper_funcs to use the
 * respective helper functions.
 */
#define DRM_GEM_VRAM_PLANE_HELPER_FUNCS \
      .prepare_fb = drm_gem_vram_plane_helper_prepare_fb, \
      .cleanup_fb = drm_gem_vram_plane_helper_cleanup_fb

강조 표기와 교차 참조

389-437

kernel-doc 주석의 설명 텍스트에서는 다음 특수 패턴을 인식해 적절한 reStructuredText 마크업과 `Sphinx C Domain` 참조로 변환합니다. 이 표기는 일반 reStructuredText 문서에서는 인식되지 않고 kernel-doc 주석 안에서만 동작합니다.

  • `funcname()`은 함수 참조입니다.
  • `@parameter`는 함수 매개변수 이름이며 교차 참조 없이 서식만 적용합니다.
  • `%CONST`는 상수 이름이며 교차 참조 없이 서식만 적용합니다.
  • 이중 backtick 자체를 포함한 ````literal```` 표기는 내용을 그대로 처리하는 literal입니다. 출력은 `monospaced font`를 사용하며 kernel-doc 또는 reStructuredText에서 특별한 의미를 갖는 문자를 안전하게 적을 때 유용합니다. 함수 설명 안의 `%ph` 같은 표기에 특히 유용합니다.
  • `$ENVVAR`는 환경 변수 이름이며 교차 참조 없이 서식만 적용합니다.
  • `&struct name`, `&enum name`, `&typedef name`은 각각 구조체, enum, typedef 참조입니다.
  • `&struct_name->member` 또는 `&struct_name.member`는 구조체·공용체 멤버 참조입니다. 링크 대상은 멤버 자체가 아니라 구조체나 공용체 정의입니다.
  • `&name`은 일반 타입 참조입니다. 주로 오래된 주석을 위한 표기이므로 가능하면 앞에서 설명한 완전한 참조 형식을 사용합니다.

reStructuredText에서 교차 참조하기

438-460

reStructuredText 문서에서 kernel-doc 주석에 정의된 함수와 타입을 참조할 때 추가 구문은 필요하지 않습니다. 함수 이름은 `()`로 끝내고 타입 이름 앞에는 `struct`, `union`, `enum`, `typedef` 중 알맞은 키워드를 씁니다.

See foo().
See struct foo.
See union bar.
See enum baz.
See typedef meh.

교차 참조 링크에 사용자 정의 표시 텍스트가 필요하면 Sphinx C Domain의 `:c:func:` 또는 `:c:type:` 역할을 사용합니다.

See :c:func:`my custom link text for function foo <foo>`.
See :c:type:`my custom link text for struct bar <bar>`.

세부 규칙은 앞에서 연결한 `Sphinx C Domain` 문서를 참고합니다.

개요 문서 주석

461-489

소스 코드와 설명을 가까이 두기 위해 함수, 구조체, 공용체, enum, typedef에 속하지 않는 자유 형식 kernel-doc 블록을 포함할 수 있습니다. 예를 들어 driver 또는 library code의 동작 원리를 설명하는 데 사용할 수 있습니다.

이 형식은 절 제목과 함께 `DOC:` 절 키워드를 사용합니다.

/**
 * DOC: Theory of Operation
 *
 * The whizbang foobar is a dilly of a gizmo. It can do whatever you
 * want it to do, at any time. It reads your mind. Here's how it works.
 *
 * foo bar splat
 *
 * The only drawback to this gizmo is that is can sometimes damage
 * hardware, software, or its subject(s).
 */

`DOC:` 뒤의 제목은 소스 파일 안에서 heading 역할을 하는 동시에 문서 주석을 추출하는 식별자 역할도 합니다. 따라서 제목은 해당 파일 안에서 고유해야 합니다.

kernel-doc 주석 포함과 export 옵션

490-521

전용 kernel-doc Sphinx directive 확장을 사용하면 어느 reStructuredText 문서에서든 소스의 문서 주석을 포함할 수 있습니다.

.. kernel-doc:: source
   :option:

`source`는 커널 소스 트리를 기준으로 한 소스 파일 경로입니다. directive의 `export` 옵션은 `source` 또는 `source-pattern`과 일치하는 파일에서 `EXPORT_SYMBOL`이나 `EXPORT_SYMBOL_GPL`로 내보낸 모든 함수의 문서를 포함합니다.

`source-pattern`은 kernel-doc 주석은 헤더 파일에 있고 `EXPORT_SYMBOL` 또는 `EXPORT_SYMBOL_GPL`은 함수 정의 옆의 구현 파일에 있을 때 유용합니다.

.. kernel-doc:: lib/bitmap.c
   :export:

.. kernel-doc:: include/net/mac80211.h
   :export: net/mac80211/*.c

kernel-doc directive 옵션

522-576

`internal` 옵션은 `source`와 선택적인 `source-pattern` 파일에서 `EXPORT_SYMBOL` 또는 `EXPORT_SYMBOL_GPL`로 내보내지 않은 모든 함수와 타입의 문서를 포함합니다.

.. kernel-doc:: drivers/gpu/drm/i915/intel_audio.c
   :internal:

`identifiers` 옵션은 `source`에서 지정한 각 함수와 타입의 문서를 포함합니다. 함수를 하나도 지정하지 않으면 소스의 모든 함수와 타입을 포함합니다. 타입에는 struct, union, enum, typedef 식별자를 지정할 수 있습니다.

.. kernel-doc:: lib/bitmap.c
   :identifiers: bitmap_parselist bitmap_parselist_user

.. kernel-doc:: lib/idr.c
   :identifiers:

`no-identifiers` 옵션은 지정한 각 함수와 타입의 문서를 제외합니다.

.. kernel-doc:: lib/bitmap.c
   :no-identifiers: bitmap_parselist

`functions`는 `identifiers` directive의 오래된 별칭이며 deprecated 상태입니다.

`doc` 옵션은 `source`에서 지정한 제목의 `DOC:` 문단을 포함합니다. 제목에는 공백을 사용할 수 있지만 따옴표로 감싸지 않습니다. 제목은 문단 식별자로만 쓰이고 출력에는 나타나지 않으므로, 이를 감싸는 reStructuredText 문서에 적절한 heading을 따로 마련해야 합니다.

.. kernel-doc:: drivers/gpu/drm/i915/intel_audio.c
   :doc: High Definition Audio over HDMI and Display Port

옵션을 지정하지 않으면 kernel-doc directive는 소스 파일의 모든 문서 주석을 포함합니다. 확장은 커널 트리의 `Documentation/sphinx/kerneldoc.py`에 있으며 내부적으로 `scripts/kernel-doc` 스크립트를 호출해 문서 주석을 추출합니다.

kernel-doc으로 man page 생성하기

577-598

커널 git tree에서 kernel-doc으로 man page만 생성하려면 `/**`를 포함하는 파일을 찾되 `Documentation`과 `tools` 경로를 제외하고, `scripts/kernel-doc -man`의 출력을 `scripts/split-man.pl /tmp/man`으로 전달합니다.

$ scripts/kernel-doc -man \
  $(git grep -l '/\*\*' -- :^Documentation :^tools) \
  | scripts/split-man.pl /tmp/man

오래된 git 버전 중 일부는 특정 path exclusion 구문을 지원하지 않습니다. 그런 버전에서는 `:!경로` 표기 또는 `:(exclude)경로` 표기를 사용하는 다음 명령 중 하나를 사용할 수 있습니다.

$ scripts/kernel-doc -man \
  $(git grep -l '/\*\*' -- . ':!Documentation' ':!tools') \
  | scripts/split-man.pl /tmp/man

$ scripts/kernel-doc -man \
  $(git grep -l '/\*\*' -- . ":(exclude)Documentation" ":(exclude)tools") \
  | scripts/split-man.pl /tmp/man