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