Writing kernel-doc comments

The Linux kernel source files may contain structured documentationcomments in the kernel-doc format to describe the functions, typesand design of the code. It is easier to keep documentation up-to-datewhen it is embedded in source files.

Note

The kernel-doc format is deceptively similar to javadoc,gtk-doc or Doxygen, yet distinctively different, for historicalreasons. The kernel source contains tens of thousands of kernel-doccomments. Please stick to the style described here.

Note

kernel-doc does not cover Rust code: please seeGeneral Information instead.

The kernel-doc structure is extracted from the comments, and properSphinx C Domain function and type descriptions with anchors aregenerated from them. The descriptions are filtered for special kernel-dochighlights and cross-references. See below for details.

Every function that is exported to loadable modules usingEXPORT_SYMBOL orEXPORT_SYMBOL_GPL should have a kernel-doccomment. Functions and data structures in header files which are intendedto be used by modules should also have kernel-doc comments.

It is good practice to also provide kernel-doc formatted documentationfor functions externally visible to other kernel files (not markedstatic). We also recommend providing kernel-doc formatteddocumentation for private (filestatic) routines, for consistency ofkernel source code layout. This is lower priority and at the discretionof the maintainer of that kernel source file.

How to format kernel-doc comments

The opening comment mark/** is used for kernel-doc comments. Thekernel-doc tool will extract comments marked this way. The rest ofthe comment is formatted like a normal multi-line comment with a columnof asterisks on the left side, closing with*/ on a line by itself.

The function and type kernel-doc comments should be placed just beforethe function or type being described in order to maximise the chancethat somebody changing the code will also change the documentation. Theoverview kernel-doc comments may be placed anywhere at the top indentationlevel.

Running thekernel-doc tool with increased verbosity and without actualoutput generation may be used to verify proper formatting of thedocumentation comments. For example:

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

The documentation format is verified by the kernel build when it isrequested to perform extra gcc checks:

make W=n

Function documentation

The general format of a function and function-like macro kernel-doc comment is:

/** * 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. */

The brief description following the function name may span multiple lines, andends with an argument description, a blank comment line, or the end of thecomment block.

Function parameters

Each function argument should be described in order, immediately followingthe short function description. Do not leave a blank line between thefunction description and the arguments, nor between the arguments.

Each@argument: description may span multiple lines.

Note

If the@argument description has multiple lines, the continuationof the description should start at the same column as the previous line:

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

or:

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

If a function has a variable number of arguments, its description shouldbe written in kernel-doc notation as:

* @...: description

Function context

The context in which a function can be called should be described in asection namedContext. This should include whether the functionsleeps or can be called from interrupt context, as well as what locksit takes, releases and expects to be held by its caller.

Examples:

* 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 values

The return value, if any, should be described in a dedicated sectionnamedReturn (orReturns).

Note

  1. The multi-line descriptive text you provide doesnot recognizeline breaks, so if you try to format some text nicely, as in:

    * 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

    So, in order to produce the desired line breaks, you need to use aReST list, e. g.:

    * Return:* * %0            - OK to runtime suspend the device* * %-EBUSY       - Device should not be runtime suspended
  2. If the descriptive text you provide has lines that begin withsome phrase followed by a colon, each of those phrases will be takenas a new section heading, which probably won’t produce the desiredeffect.

Structure, union, and enumeration documentation

The general format of a struct, union, andenumkernel-doc comment is:

/** * 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. */

You can replace thestruct in the above example withunion orenum to describe unions or enums.member is used to meanstructandunionmember names as well as enumerations in an enum.

The brief description following the structure name may span multiplelines, and ends with a member description, a blank comment line, or theend of the comment block.

Members

Members of structs, unions and enums should be documented the same wayas function parameters; they immediately succeed the short descriptionand may be multi-line.

Inside astructoruniondescription, you can use theprivate: andpublic: comment tags. Structure fields that are inside aprivate:area are not listed in the generated output documentation.

Theprivate: andpublic: tags must begin immediately following a/* comment marker. They may optionally include comments between the: and the ending*/ marker.

Example:

/** * 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;};

Nested structs/unions

It is possible to document nested structs and unions, like:

/** * 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;};

Note

  1. When documenting nested structs or unions, if the struct/unionfoois named, the memberbar inside it should be documented as@foo.bar:

  2. When the nested struct/unionis anonymous, the memberbar in itshould be documented as@bar:

In-line member documentation comments

The structure members may also be documented in-line within the definition.There are two styles, single-line comments where both the opening/** andclosing*/ are on the same line, and multi-line comments where they are eachon a line of their own, like all other kernel-doc comments:

/** * 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;};

Typedef documentation

The general format of atypedefkernel-doc comment is:

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

Typedefs with function prototypes can also be documented:

/** * 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);

Object-like macro documentation

Object-like macros are distinct from function-like macros. They aredifferentiated by whether the macro name is immediately followed by aleft parenthesis (‘(’) for function-like macros or not followed by onefor object-like macros.

Function-like macros are handled like functions byscripts/kernel-doc.They may have a parameter list. Object-like macros have do not have aparameter list.

The general format of an object-like macro kernel-doc comment is:

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

Example:

/** * 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

Example:

/** * 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

Highlights and cross-references

The following special patterns are recognized in the kernel-doc commentdescriptive text and converted to proper reStructuredText markup andSphinx CDomain references.

Attention

The below areonly recognized within kernel-doc comments,not within normal reStructuredText documents.

funcname()

Function reference.

@parameter

Name of a function parameter. (No cross-referencing, just formatting.)

%CONST

Name of a constant. (No cross-referencing, just formatting.)

Examples:

%0    %NULL    %-1    %-EFAULT    %-EINVAL    %-ENOMEM
``literal``

A literal block that should be handled as-is. The output will use amonospacedfont.

Useful if you need to use special characters that would otherwise have somemeaning either by kernel-doc script or by reStructuredText.

This is particularly useful if you need to use things like%ph insidea function description.

$ENVVAR

Name of an environment variable. (No cross-referencing, just formatting.)

&structname

Structure reference.

&enumname

Enum reference.

&typedefname

Typedef reference.

&struct_name->member or&struct_name.member

Structure orunionmember reference. The cross-reference will be to thestructoruniondefinition, not the member directly.

&name

A generic type reference. Prefer using the full reference described aboveinstead. This is mostly for legacy comments.

Cross-referencing from reStructuredText

No additional syntax is needed to cross-reference the functions and typesdefined in the kernel-doc comments from reStructuredText documents.Just end function names with() and writestruct,union,enumortypedef before types.For example:

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

However, if you want custom text in the cross-reference link, that can be donethrough the following syntax:

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

For further details, please refer to theSphinx C Domain documentation.

Overview documentation comments

To facilitate having source code and comments close together, you can includekernel-doc documentation blocks that are free-form comments instead of beingkernel-doc for functions, structures, unions, enums, or typedefs. This could beused for something like a theory of operation for a driver or library code, forexample.

This is done by using aDOC: section keyword with a section title.

The general format of an overview or high-level documentation comment is:

/** * 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). */

The title followingDOC: acts as a heading within the source file, but alsoas an identifier for extracting the documentation comment. Thus, the title mustbe unique within the file.

Including kernel-doc comments

The documentation comments may be included in any of the reStructuredTextdocuments using a dedicated kernel-doc Sphinx directive extension.

The kernel-doc directive is of the format:

.. kernel-doc:: source   :option:

Thesource is the path to a source file, relative to the kernel sourcetree. The following directive options are supported:

export:[source-pattern ...]

Include documentation for all functions insource that have been exportedusingEXPORT_SYMBOL orEXPORT_SYMBOL_GPL either insource or in anyof the files specified bysource-pattern.

Thesource-pattern is useful when the kernel-doc comments have been placedin header files, whileEXPORT_SYMBOL andEXPORT_SYMBOL_GPL are next tothe function definitions.

Examples:

.. kernel-doc:: lib/bitmap.c   :export:.. kernel-doc:: include/net/mac80211.h   :export: net/mac80211/*.c
internal:[source-pattern ...]

Include documentation for all functions and types insource that havenot been exported usingEXPORT_SYMBOL orEXPORT_SYMBOL_GPL eitherinsource or in any of the files specified bysource-pattern.

Example:

.. kernel-doc:: drivers/gpu/drm/i915/intel_audio.c   :internal:
identifiers:[ function/type ...]

Include documentation for eachfunction andtype insource.If nofunction is specified, the documentation for all functionsand types in thesource will be included.type can be a struct, union, enum, ortypedefidentifier.

Examples:

.. kernel-doc:: lib/bitmap.c   :identifiers: bitmap_parselist bitmap_parselist_user.. kernel-doc:: lib/idr.c   :identifiers:
no-identifiers:[ function/type ...]

Exclude documentation for eachfunction andtype insource.

Example:

.. kernel-doc:: lib/bitmap.c   :no-identifiers: bitmap_parselist
functions:[ function/type ...]

This is an alias of the ‘identifiers’ directive and deprecated.

doc:title

Include documentation for theDOC: paragraph identified bytitle insource. Spaces are allowed intitle; do not quote thetitle. Thetitleis only used as an identifier for the paragraph, and is not included in theoutput. Please make sure to have an appropriate heading in the enclosingreStructuredText document.

Example:

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

Without options, the kernel-doc directive includes all documentation commentsfrom the source file.

The kernel-doc extension is included in the kernel source tree, atDocumentation/sphinx/kerneldoc.py. Internally, it uses thescripts/kernel-doc script to extract the documentation comments from thesource.

How to use kernel-doc to generate man pages

To generate man pages for all files that contain kernel-doc markups, run:

$ make mandocs

Or callingscript-build-wrapper directly:

$ ./tools/docs/sphinx-build-wrapper mandocs

The output will be at/man directory inside the output directory(by default:Documentation/output).

Optionally, it is possible to generate a partial set of man pages byusing SPHINXDIRS:

$ make SPHINXDIRS=driver-api/media mandocs

Note

When SPHINXDIRS={subdir} is used, it will only generate man pages forthe files explicitly inside aDocumentation/{subdir}/.../*.rst file.