Skip to contentSkip to conversation

docs: Fix kernel-doc -Werror and moves it to tools/docs

PATCH In review Mauro Carvalho Chehab 3 participants 13 messages Jan 19 – Jan 20

Subsystems (11)
lore
Share & tools
lore
#0 lore raw

cover docs: Fix kernel-doc -Werror and moves it to tools/docs

Hi Jon,

After a restful weekend and revisiting both yours and my series, I'm opting to send a patch series merging both into one:

- The first 4 patches are from my series (no changes since v5):

    https://lore.kernel.org/linux-doc/[email protected]/T/#m81211c0ff38bbaa82b8b0b6606f242ccc0c2a9ac

- It follows by the 2 patches from your renaming series:

    https://lore.kernel.org/linux-doc/[email protected]/T/#m51099c31a99dccccdb4d17cbaadc818e9e4df8c4

with the fix I proposed for kernel-doc to find its libraries

I added 3 patches afterwards:

- patch 5: move possible return values from docstring to helper message;
- patch 6: improve MsgFormatter description;
- patch 7: moves kerneldoc_bin from conf.py to the sphinx/kerneldoc.py (this is now just a debugging message - no need to pick it from env)

IMO, this series is ready to be merged.

NOTE:
I didn't rename kernel-doc to kernel_doc.py nor added any symlinks. If we want some day to use sphinx autoparse extension, we can do it later. I guess we can also revisit it during -rc period, if needed.

Regards,
Mauro

Jonathan Corbet (2):
docs: kdoc: remove support for an external kernel-doc from sphinx
docs: kdoc: move kernel-doc to tools/docs

Mauro Carvalho Chehab (7):
docs: kdoc: fix logic to handle unissued warnings
docs: kdoc: avoid error_count overflows
docs: kdoc: ensure that comments are using our coding style
docs: kdoc: some fixes to kernel-doc comments
docs: kdoc: move the return values to the helper message
docs: kdoc: improve description of MsgFormatter
docs: conf.py: get rid of the now unused kerneldoc_bin env var

 Documentation/conf.py                         |  4 -
 Documentation/doc-guide/kernel-doc.rst        |  8 +-
 Documentation/kbuild/kbuild.rst               |  2 +-
 Documentation/process/coding-style.rst        |  2 +-
 Documentation/sphinx/kerneldoc.py             | 60 +++----------
 .../it_IT/doc-guide/kernel-doc.rst            |  8 +-
 .../sp_SP/process/coding-style.rst            |  2 +-
 .../zh_CN/doc-guide/kernel-doc.rst            | 10 +--
 .../translations/zh_CN/kbuild/kbuild.rst      |  2 +-
 .../zh_CN/process/coding-style.rst            |  2 +-
 .../zh_TW/process/coding-style.rst            |  2 +-
 MAINTAINERS                                   |  2 -
 Makefile                                      |  2 +-
 drivers/gpu/drm/i915/Makefile                 |  2 +-
 scripts/kernel-doc                            |  1 -
 tools/docs/find-unused-docs.sh                |  2 +-
 .../kernel-doc.py => tools/docs/kernel-doc    | 89 ++++++++++++-------
 tools/docs/sphinx-build-wrapper               |  2 +-
 tools/lib/python/kdoc/kdoc_parser.py          | 35 ++++++--
 19 files changed, 120 insertions(+), 117 deletions(-)
 delete mode 120000 scripts/kernel-doc
 rename scripts/kernel-doc.py => tools/docs/kernel-doc (88%)
Signature · 1 line
2.52.0
#1 lore raw

PATCH 1/9 docs: kdoc: fix logic to handle unissued warnings

Changeset 469c1c9eb6c9 ("kernel-doc: Issue warnings that were silently discarded") didn't properly addressed the missing messages behavior, as
it was calling directly python logger low-level function,
instead of using the expected method to emit warnings.

Basically, there are two methods to log messages:

- self.config.log.warning() - This is the raw level to emit a warning. It just writes the a message at stderr, via python logging, as it is initialized as:

self.config.log = logging.getLogger("kernel-doc")

- self.config.warning() - This is where we actually consider a message as a warning, properly incrementing error count.

Due to that, several parsing error messages are internally considered as success, causing -Werror to not work on such messages.

While here, ensure that the last ignored entry will also be handled by adding an extra check at the end of the parse handler.

Fixes 469c1c9eb6c9 ("kernel-doc: Issue warnings that were silently discarded")
---
 tools/lib/python/kdoc/kdoc_parser.py | 35 ++++++++++++++++++++++------
 1 file changed, 28 insertions(+), 7 deletions(-)
tools/lib/python/kdoc/kdoc_parser.py +28 -7
index a9a37519145d..c03505889dc2 100644
@@ -295,7 +295,7 @@ class KernelEntry:
 
     # TODO: rename to emit_message after removal of kernel-doc.pl
     def emit_msg(self, ln, msg, *, warning=True):
-        """Emit a message"""
+        """Emit a message."""
 
         log_msg = f"{self.fname}:{ln} {msg}"
 
@@ -448,18 +448,37 @@ class KernelDoc:
 
         self.config.log.debug("Output: %s:%s = %s", dtype, name, pformat(args))
 
+    def emit_unused_warnings(self):
+        """
+        When the parser fails to produce a valid entry, it places some
+        warnings under `entry.warnings` that will be discarded when resetting
+        the state.
+
+        Ensure that those warnings are not lost.
+
+        .. note::
+
+              Because we are calling `config.warning()` here, those
+              warnings are not filtered by the `-W` parameters: they will all
+              be produced even when `-Wreturn`, `-Wshort-desc`, and/or
+              `-Wcontents-before-sections` are used.
+
+              Allowing those warnings to be filtered is complex, because it
+              would require storing them in a buffer and then filtering them
+              during the output step of the code, depending on the
+              selected symbols.
+        """
+        if self.entry and self.entry not in self.entries:
+            for log_msg in self.entry.warnings:
+                self.config.warning(log_msg)
+
     def reset_state(self, ln):
         """
         Ancillary routine to create a new entry. It initializes all
         variables used by the state machine.
         """
 
-        #
-        # Flush the warnings out before we proceed further
-        #
-        if self.entry and self.entry not in self.entries:
-            for log_msg in self.entry.warnings:
-                self.config.log.warning(log_msg)
+        self.emit_unused_warnings()
 
         self.entry = KernelEntry(self.config, self.fname, ln)
 
@@ -1741,6 +1760,8 @@ class KernelDoc:
                         # Hand this line to the appropriate state handler
                         self.state_actions[self.state](self, ln, line)
 
+            self.emit_unused_warnings()
+
         except OSError:
             self.config.log.error(f"Error: Cannot open file {self.fname}")
 
Signature · 1 line
2.52.0
#3 lore raw

PATCH 3/9 docs: kdoc: ensure that comments are using our coding style

In reply to Mauro Carvalho Chehab

Along kernel-doc libs, we opted to have all comments starting/ending with a blank comment line. Use the same style here.

---
 scripts/kernel-doc.py | 24 ++++++++++++++++++------
 1 file changed, 18 insertions(+), 6 deletions(-)
scripts/kernel-doc.py +18 -6
index 1ebb16b9bb08..f1f3f56edeb5 100755
@@ -3,7 +3,7 @@
 # Copyright(c) 2025: Mauro Carvalho Chehab <[email protected]>.
 #
 # pylint: disable=C0103,R0912,R0914,R0915
-
+#
 # NOTE: While kernel-doc requires at least version 3.6 to run, the
 #       command line should work with Python 3.2+ (tested with 3.4).
 #       The rationale is that it shall fail gracefully during Kernel
@@ -12,7 +12,7 @@
 #       - no f-strings can be used on this file.
 #       - the libraries that require newer versions can only be included
 #         after Python version is checked.
-
+#
 # Converted from the kernel-doc script originally written in Perl
 # under GPLv2, copyrighted since 1998 by the following authors:
 #
@@ -197,8 +197,9 @@ def main():
     parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter,
                                      description=DESC)
 
+    #
     # Normal arguments
-
+    #
     parser.add_argument("-v", "-verbose", "--verbose", action="store_true",
                         help="Verbose output, more warnings and other information.")
 
@@ -213,8 +214,9 @@ def main():
                         action="store_true",
                         help="Enable line number output (only in ReST mode)")
 
+    #
     # Arguments to control the warning behavior
-
+    #
     parser.add_argument("-Wreturn", "--wreturn", action="store_true",
                         help="Warns about the lack of a return markup on functions.")
 
@@ -235,8 +237,9 @@ def main():
     parser.add_argument("-export-file", "--export-file", action='append',
                         help=EXPORT_FILE_DESC)
 
+    #
     # Output format mutually-exclusive group
-
+    #
     out_group = parser.add_argument_group("Output format selection (mutually exclusive)")
 
     out_fmt = out_group.add_mutually_exclusive_group()
@@ -248,8 +251,9 @@ def main():
     out_fmt.add_argument("-N", "-none", "--none", action="store_true",
                          help="Do not output documentation, only warnings.")
 
+    #
     # Output selection mutually-exclusive group
-
+    #
     sel_group = parser.add_argument_group("Output selection (mutually exclusive)")
     sel_mut = sel_group.add_mutually_exclusive_group()
 
@@ -262,7 +266,9 @@ def main():
     sel_mut.add_argument("-s", "-function", "--symbol", action='append',
                          help=FUNCTION_DESC)
 
+    #
     # Those are valid for all 3 types of filter
+    #
     parser.add_argument("-n", "-nosymbol", "--nosymbol", action='append',
                         help=NOSYMBOL_DESC)
 
@@ -295,9 +301,11 @@ def main():
 
     python_ver = sys.version_info[:2]
     if python_ver < (3,6):
+        #
         # Depending on Kernel configuration, kernel-doc --none is called at
         # build time. As we don't want to break compilation due to the
         # usage of an old Python version, return 0 here.
+        #
         if args.none:
             logger.error("Python 3.6 or later is required by kernel-doc. skipping checks")
             sys.exit(0)
@@ -307,7 +315,9 @@ def main():
     if python_ver < (3,7):
         logger.warning("Python 3.7 or later is required for correct results")
 
+    #
     # Import kernel-doc libraries only after checking Python version
+    #
     from kdoc.kdoc_files import KernelFiles             # pylint: disable=C0415
     from kdoc.kdoc_output import RestFormat, ManFormat  # pylint: disable=C0415
 
@@ -346,6 +356,8 @@ def main():
 
     sys.exit(0)
 
+#
 # Call main method
+#
 if __name__ == "__main__":
     main()
Signature · 1 line
2.52.0
#4 lore raw

PATCH 4/9 docs: kdoc: some fixes to kernel-doc comments

In reply to Mauro Carvalho Chehab

There are some typos and English errors in the comments of kernel‑doc.py.

Locate them with the help of an LLM (gpt‑oss 14B), executed locally with this prompt:

review English grammar and syntax at the comments on the code below:
<cat scripts/kernel-doc.py>

While LLM worked fine for the task of doing an English grammar review for strings, being able to distinguish them from the actual code, it was not is perfect: some things required manual work to fix.

-

While here, replace:

    "/**" with: ``/**``

As, if we ever rename this script to kernel_doc.py and add it to Sphinx ext autodoc, we want to avoid this warning:

scripts/kernel_doc.py:docstring of kernel_doc:10: WARNING: Inline strong start-string without end-string. [docutils]

---
 scripts/kernel-doc.py | 29 +++++++++++++----------------
 1 file changed, 13 insertions(+), 16 deletions(-)
scripts/kernel-doc.py +13 -16
index f1f3f56edeb5..4e3b9cfe3fd7 100755
@@ -9,9 +9,9 @@
 #       The rationale is that it shall fail gracefully during Kernel
 #       compilation with older Kernel versions. Due to that:
 #       - encoding line is needed here;
-#       - no f-strings can be used on this file.
-#       - the libraries that require newer versions can only be included
-#         after Python version is checked.
+#       - f-strings cannot be used in this file.
+#       - libraries that require newer versions can only be included
+#         after the Python version has been checked.
 #
 # Converted from the kernel-doc script originally written in Perl
 # under GPLv2, copyrighted since 1998 by the following authors:
@@ -88,16 +88,13 @@
 #    Yujie Liu <[email protected]>
 
 """
-kernel_doc
-==========
-
-Print formatted kernel documentation to stdout
+Print formatted kernel documentation to stdout.
 
 Read C language source or header FILEs, extract embedded
 documentation comments, and print formatted documentation
 to standard output.
 
-The documentation comments are identified by the "/**"
+The documentation comments are identified by the ``/**``
 opening comment mark.
 
 See Documentation/doc-guide/kernel-doc.rst for the
@@ -134,13 +131,13 @@ May be used multiple times.
 """
 
 EXPORT_DESC = """
-Only output documentation for the symbols that have been
+Only output documentation for symbols that have been
 exported using EXPORT_SYMBOL() and related macros in any input
 FILE or -export-file FILE.
 """
 
 INTERNAL_DESC = """
-Only output documentation for the symbols that have NOT been
+Only output documentation for symbols that have NOT been
 exported using EXPORT_SYMBOL() and related macros in any input
 FILE or -export-file FILE.
 """
@@ -163,7 +160,7 @@ Header and C source files to be parsed.
 """
 
 WARN_CONTENTS_BEFORE_SECTIONS_DESC = """
-Warns if there are contents before sections (deprecated).
+Warn if there are contents before sections (deprecated).
 
 This option is kept just for backward-compatibility, but it does nothing,
 neither here nor at the original Perl script.
@@ -171,7 +168,7 @@ neither here nor at the original Perl script.
 
 
 class MsgFormatter(logging.Formatter):
-    """Helper class to format warnings on a similar way to kernel-doc.pl"""
+    """Helper class to format warnings in a similar way to kernel-doc.pl."""
 
     def format(self, record):
         record.levelname = record.levelname.capitalize()
@@ -273,7 +270,7 @@ def main():
                         help=NOSYMBOL_DESC)
 
     parser.add_argument("-D", "-no-doc-sections", "--no-doc-sections",
-                        action='store_true', help="Don't outputt DOC sections")
+                        action='store_true', help="Don't output DOC sections")
 
     parser.add_argument("files", metavar="FILE",
                         nargs="+", help=FILES_DESC)
@@ -302,12 +299,12 @@ def main():
     python_ver = sys.version_info[:2]
     if python_ver < (3,6):
         #
-        # Depending on Kernel configuration, kernel-doc --none is called at
+        # Depending on the Kernel configuration, kernel-doc --none is called at
         # build time. As we don't want to break compilation due to the
         # usage of an old Python version, return 0 here.
         #
         if args.none:
-            logger.error("Python 3.6 or later is required by kernel-doc. skipping checks")
+            logger.error("Python 3.6 or later is required by kernel-doc. Skipping checks")
             sys.exit(0)
 
         sys.exit("Python 3.6 or later is required by kernel-doc. Aborting.")
@@ -316,7 +313,7 @@ def main():
         logger.warning("Python 3.7 or later is required for correct results")
 
     #
-    # Import kernel-doc libraries only after checking Python version
+    # Import kernel-doc libraries only after checking the Python version
     #
     from kdoc.kdoc_files import KernelFiles             # pylint: disable=C0415
     from kdoc.kdoc_output import RestFormat, ManFormat  # pylint: disable=C0415
Signature · 1 line
2.52.0
#5 lore raw

PATCH 5/9 docs: kdoc: remove support for an external kernel-doc from sphinx

In reply to Mauro Carvalho Chehab

From: Jonathan Corbet <[email protected]>

The ability to build the docs with an external kernel-doc program involves some truly confusing logic and complicates the task of moving kernel-doc out of scripts/. But this feature is not useful for normal documentation builds, and the external kernel-doc can always be run by hand when it needs debugging. So just remove that feature and make life easier.

There is still a bunch of logic to build a command line that we never use; the idea is to be able to output it, but I'm not sure if that is worth keeping.

---
 Documentation/sphinx/kerneldoc.py | 53 ++++---------------------------
 1 file changed, 6 insertions(+), 47 deletions(-)
Documentation/sphinx/kerneldoc.py +6 -47
index d8cdf068ef35..afbab458550a 100644
@@ -190,35 +190,7 @@ class KernelDocDirective(Directive):
 
         return cmd
 
-    def run_cmd(self, cmd):
-        """
-        Execute an external kernel-doc command.
-        """
-
-        env = self.state.document.settings.env
-        node = nodes.section()
-
-        p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
-        out, err = p.communicate()
-
-        out, err = codecs.decode(out, 'utf-8'), codecs.decode(err, 'utf-8')
-
-        if p.returncode != 0:
-            sys.stderr.write(err)
-
-            logger.warning("kernel-doc '%s' failed with return code %d"
-                                % (" ".join(cmd), p.returncode))
-            return [nodes.error(None, nodes.paragraph(text = "kernel-doc missing"))]
-        elif env.config.kerneldoc_verbosity > 0:
-            sys.stderr.write(err)
-
-        filenames = self.parse_args["file_list"]
-        for filename in filenames:
-            self.parse_msg(filename, node, out, cmd)
-
-        return node.children
-
-    def parse_msg(self, filename, node, out, cmd):
+    def parse_msg(self, filename, node, out):
         """
         Handles a kernel-doc output for a given file
         """
@@ -244,7 +216,7 @@ class KernelDocDirective(Directive):
 
         self.do_parse(result, node)
 
-    def run_kdoc(self, cmd, kfiles):
+    def run_kdoc(self, kfiles):
         """
         Execute kernel-doc classes directly instead of running as a separate
         command.
@@ -258,23 +230,17 @@ class KernelDocDirective(Directive):
         filenames = self.parse_args["file_list"]
 
         for filename, out in kfiles.msg(**self.msg_args, filenames=filenames):
-            self.parse_msg(filename, node, out, cmd)
+            self.parse_msg(filename, node, out)
 
         return node.children
 
     def run(self):
-        global kfiles
-
         cmd = self.handle_args()
         if self.verbose >= 1:
             logger.info(cmd_str(cmd))
 
         try:
-            if kfiles:
-                return self.run_kdoc(cmd, kfiles)
-            else:
-                return self.run_cmd(cmd)
-
+            return self.run_kdoc(kfiles)
         except Exception as e:  # pylint: disable=W0703
             logger.warning("kernel-doc '%s' processing failed with: %s" %
                            (cmd_str(cmd), pformat(e)))
@@ -286,15 +252,8 @@ class KernelDocDirective(Directive):
 
 def setup_kfiles(app):
     global kfiles
-
-    kerneldoc_bin = app.env.config.kerneldoc_bin
-
-    if kerneldoc_bin and kerneldoc_bin.endswith("kernel-doc.py"):
-        print("Using Python kernel-doc")
-        out_style = RestFormat()
-        kfiles = KernelFiles(out_style=out_style, logger=logger)
-    else:
-        print(f"Using {kerneldoc_bin}")
+    out_style = RestFormat()
+    kfiles = KernelFiles(out_style=out_style, logger=logger)
 
 
 def setup(app):
Signature · 1 line
2.52.0
#2 lore raw

PATCH 2/9 docs: kdoc: avoid error_count overflows

In reply to Mauro Carvalho Chehab

The glibc library limits the return code to 8 bits. We need to stick to this limit when using sys.exit(error_count).

---
 scripts/kernel-doc.py | 26 +++++++++++++++++++-------
 1 file changed, 19 insertions(+), 7 deletions(-)
scripts/kernel-doc.py +19 -7
index 7a1eaf986bcd..1ebb16b9bb08 100755
@@ -116,6 +116,8 @@ SRC_DIR = os.path.dirname(os.path.realpath(__file__))
 
 sys.path.insert(0, os.path.join(SRC_DIR, LIB_DIR))
 
+WERROR_RETURN_CODE = 3
+
 DESC = """
 Read C language source or header FILEs, extract embedded documentation comments,
 and print formatted documentation to standard output.
@@ -176,7 +178,21 @@ class MsgFormatter(logging.Formatter):
         return logging.Formatter.format(self, record)
 
 def main():
-    """Main program"""
+    """
+    Main program.
+
+    By default, the return value is:
+
+    - 0: success or Python version is not compatible with
+      kernel-doc.  If -Werror is not used, it will also
+      return 0 if there are issues at kernel-doc markups;
+
+    - 1: an abnormal condition happened;
+
+    - 2: argparse issued an error;
+
+    - 3: -Werror is used, and one or more unfiltered parse warnings happened.
+    """
 
     parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter,
                                      description=DESC)
@@ -323,16 +339,12 @@ def main():
 
     if args.werror:
         print("%s warnings as errors" % error_count)    # pylint: disable=C0209
-        sys.exit(error_count)
+        sys.exit(WERROR_RETURN_CODE)
 
     if args.verbose:
         print("%s errors" % error_count)                # pylint: disable=C0209
 
-    if args.none:
-        sys.exit(0)
-
-    sys.exit(error_count)
-
+    sys.exit(0)
 
 # Call main method
 if __name__ == "__main__":
Signature · 1 line
2.52.0
#6 lore raw

PATCH 6/9 docs: kdoc: move kernel-doc to tools/docs

In reply to Mauro Carvalho Chehab

From: Jonathan Corbet <[email protected]>

kernel-doc is the last documentation-related tool still living outside of the tools/docs directory; the time has come to move it over.

[mchehab: fixed kdoc lib location]
---
 Documentation/conf.py                                  |  2 +-
 Documentation/doc-guide/kernel-doc.rst                 |  8 ++++----
 Documentation/kbuild/kbuild.rst                        |  2 +-
 Documentation/process/coding-style.rst                 |  2 +-
 .../translations/it_IT/doc-guide/kernel-doc.rst        |  8 ++++----
 .../translations/sp_SP/process/coding-style.rst        |  2 +-
 .../translations/zh_CN/doc-guide/kernel-doc.rst        | 10 +++++-----
 Documentation/translations/zh_CN/kbuild/kbuild.rst     |  2 +-
 .../translations/zh_CN/process/coding-style.rst        |  2 +-
 .../translations/zh_TW/process/coding-style.rst        |  2 +-
 MAINTAINERS                                            |  2 --
 Makefile                                               |  2 +-
 drivers/gpu/drm/i915/Makefile                          |  2 +-
 scripts/kernel-doc                                     |  1 -
 tools/docs/find-unused-docs.sh                         |  2 +-
 scripts/kernel-doc.py => tools/docs/kernel-doc         |  2 +-
 tools/docs/sphinx-build-wrapper                        |  2 +-
 17 files changed, 25 insertions(+), 28 deletions(-)
 delete mode 120000 scripts/kernel-doc
 rename scripts/kernel-doc.py => tools/docs/kernel-doc (99%)
Documentation/conf.py +1 -1
index 1ea2ae5c6276..383d5e5b9d0a 100644
@@ -582,7 +582,7 @@ pdf_documents = [
 # kernel-doc extension configuration for running Sphinx directly (e.g. by Read
 # the Docs). In a normal build, these are supplied from the Makefile via command
 # line arguments.
-kerneldoc_bin = "../scripts/kernel-doc.py"
+kerneldoc_bin = "../tools/docs/kernel-doc"  # Not used now
 kerneldoc_srctree = ".."
 
 def setup(app):
Documentation/doc-guide/kernel-doc.rst +4 -4
index b56128d7f5c3..8d2c09fb36e4 100644
@@ -54,7 +54,7 @@ Running the ``kernel-doc`` tool with increased verbosity and without actual
 output generation may be used to verify proper formatting of the
 documentation comments. For example::
 
-	scripts/kernel-doc -v -none drivers/foo/bar.c
+	tools/docs/kernel-doc -v -none drivers/foo/bar.c
 
 The documentation format of ``.c`` files is also verified by the kernel build
 when it is requested to perform extra gcc checks::
@@ -365,7 +365,7 @@ differentiated by whether the macro name is immediately followed by a
 left parenthesis ('(') for function-like macros or not followed by one
 for object-like macros.
 
-Function-like macros are handled like functions by ``scripts/kernel-doc``.
+Function-like macros are handled like functions by ``tools/docs/kernel-doc``.
 They may have a parameter list. Object-like macros have do not have a
 parameter list.
 
@@ -596,8 +596,8 @@ from the source file.
 
 The kernel-doc extension is included in the kernel source tree, at
 ``Documentation/sphinx/kerneldoc.py``. Internally, it uses the
-``scripts/kernel-doc`` script to extract the documentation comments from the
-source.
+``tools/docs/kernel-doc`` script to extract the documentation comments from
+the source.
 
 .. _kernel_doc:
 
Documentation/kbuild/kbuild.rst +1 -1
index 82826b0332df..5a9013bacfb7 100644
@@ -180,7 +180,7 @@ architecture.
 KDOCFLAGS
 ---------
 Specify extra (warning/error) flags for kernel-doc checks during the build,
-see scripts/kernel-doc for which flags are supported. Note that this doesn't
+see tools/docs/kernel-doc for which flags are supported. Note that this doesn't
 (currently) apply to documentation builds.
 
 ARCH
Documentation/process/coding-style.rst +1 -1
index 258158637f65..35b381230f6e 100644
@@ -614,7 +614,7 @@ it.
 
 When commenting the kernel API functions, please use the kernel-doc format.
 See the files at :ref:`Documentation/doc-guide/ <doc_guide>` and
-``scripts/kernel-doc`` for details. Note that the danger of over-commenting
+``tools/docs/kernel-doc`` for details. Note that the danger of over-commenting
 applies to kernel-doc comments all the same. Do not add boilerplate
 kernel-doc which simply reiterates what's obvious from the signature
 of the function.
Documentation/translations/it_IT/doc-guide/kernel-doc.rst +4 -4
index aa0e31d353d6..bac959b8b7b9 100644
@@ -80,7 +80,7 @@ Al fine di verificare che i commenti siano formattati correttamente, potete
 eseguire il programma ``kernel-doc`` con un livello di verbosità alto e senza
 che questo produca alcuna documentazione. Per esempio::
 
-	scripts/kernel-doc -v -none drivers/foo/bar.c
+	tools/docs/kernel-doc -v -none drivers/foo/bar.c
 
 Il formato della documentazione è verificato della procedura di generazione
 del kernel quando viene richiesto di effettuare dei controlli extra con GCC::
@@ -378,7 +378,7 @@ distinguono in base al fatto che il nome della macro simile a funzione sia
 immediatamente seguito da una parentesi sinistra ('(') mentre in quelle simili a
 oggetti no.
 
-Le macro simili a funzioni sono gestite come funzioni da ``scripts/kernel-doc``.
+Le macro simili a funzioni sono gestite come funzioni da ``tools/docs/kernel-doc``.
 Possono avere un elenco di parametri. Le macro simili a oggetti non hanno un
 elenco di parametri.
 
@@ -595,7 +595,7 @@ documentazione presenti nel file sorgente (*source*).
 
 L'estensione kernel-doc fa parte dei sorgenti del kernel, la si può trovare
 in ``Documentation/sphinx/kerneldoc.py``. Internamente, viene utilizzato
-lo script ``scripts/kernel-doc`` per estrarre i commenti di documentazione
+lo script ``tools/docs/kernel-doc`` per estrarre i commenti di documentazione
 dai file sorgenti.
 
 Come utilizzare kernel-doc per generare pagine man
@@ -604,4 +604,4 @@ Come utilizzare kernel-doc per generare pagine man
 Se volete utilizzare kernel-doc solo per generare delle pagine man, potete
 farlo direttamente dai sorgenti del kernel::
 
-  $ scripts/kernel-doc -man $(git grep -l '/\*\*' -- :^Documentation :^tools) | scripts/split-man.pl /tmp/man
+  $ tools/docs/kernel-doc -man $(git grep -l '/\*\*' -- :^Documentation :^tools) | scripts/split-man.pl /tmp/man
Documentation/translations/sp_SP/process/coding-style.rst +1 -1
index 025223be9706..7d63aa8426e6 100644
@@ -633,7 +633,7 @@ posiblemente POR QUÉ hace esto.
 
 Al comentar las funciones de la API del kernel, utilice el formato
 kernel-doc. Consulte los archivos en :ref:`Documentation/doc-guide/ <doc_guide>`
-y ``scripts/kernel-doc`` para más detalles.
+y ``tools/docs/kernel-doc`` para más detalles.
 
 El estilo preferido para comentarios largos (de varias líneas) es:
 
Documentation/translations/zh_CN/doc-guide/kernel-doc.rst +5 -5
index ccfb9b8329c2..fb2bbaaa85c1 100644
@@ -43,7 +43,7 @@ kernel-doc注释用 ``/**`` 作为开始标记。 ``kernel-doc`` 工具将提取
 用详细模式和不生成实际输出来运行 ``kernel-doc`` 工具,可以验证文档注释的格式
 是否正确。例如::
 
-	scripts/kernel-doc -v -none drivers/foo/bar.c
+	tools/docs/kernel-doc -v -none drivers/foo/bar.c
 
 当请求执行额外的gcc检查时,内核构建将验证文档格式::
 
@@ -473,7 +473,7 @@ doc: *title*
 如果没有选项,kernel-doc指令将包含源文件中的所有文档注释。
 
 kernel-doc扩展包含在内核源代码树中,位于 ``Documentation/sphinx/kerneldoc.py`` 。
-在内部,它使用 ``scripts/kernel-doc`` 脚本从源代码中提取文档注释。
+在内部,它使用 ``tools/docs/kernel-doc`` 脚本从源代码中提取文档注释。
 
 .. _kernel_doc_zh:
 
@@ -482,18 +482,18 @@ kernel-doc扩展包含在内核源代码树中,位于 ``Documentation/sphinx/k
 
 如果您只想使用kernel-doc生成手册页,可以从内核git树这样做::
 
-  $ scripts/kernel-doc -man \
+  $ tools/docs/kernel-doc -man \
     $(git grep -l '/\*\*' -- :^Documentation :^tools) \
     | scripts/split-man.pl /tmp/man
 
 一些旧版本的git不支持路径排除语法的某些变体。
 以下命令之一可能适用于这些版本::
 
-  $ scripts/kernel-doc -man \
+  $ tools/docs/kernel-doc -man \
     $(git grep -l '/\*\*' -- . ':!Documentation' ':!tools') \
     | scripts/split-man.pl /tmp/man
 
-  $ scripts/kernel-doc -man \
+  $ tools/docs/kernel-doc -man \
     $(git grep -l '/\*\*' -- . ":(exclude)Documentation" ":(exclude)tools") \
     | scripts/split-man.pl /tmp/man
 
Documentation/translations/zh_CN/kbuild/kbuild.rst +1 -1
index 57f5cf5b2cdd..a477b4b08958 100644
@@ -174,7 +174,7 @@ UTS_MACHINE 变量(在某些架构中还包括内核配置)来猜测正确
 KDOCFLAGS
 ---------
 指定在构建过程中用于 kernel-doc 检查的额外(警告/错误)标志,查看
-scripts/kernel-doc 了解支持的标志。请注意,这目前不适用于文档构建。
+tools/docs/kernel-doc 了解支持的标志。请注意,这目前不适用于文档构建。
 
 ARCH
 ----
Documentation/translations/zh_CN/process/coding-style.rst +1 -1
index 0484d0c65c25..5a342a024c01 100644
@@ -545,7 +545,7 @@ Linux 里这是提倡的做法,因为这样可以很简单的给读者提供
 也可以加上它做这些事情的原因。
 
 当注释内核 API 函数时,请使用 kernel-doc 格式。详见
-Documentation/translations/zh_CN/doc-guide/index.rst 和 scripts/kernel-doc 。
+Documentation/translations/zh_CN/doc-guide/index.rst 和 tools/docs/kernel-doc 。
 
 长 (多行) 注释的首选风格是:
 
Documentation/translations/zh_TW/process/coding-style.rst +1 -1
index 311c6f6bad0b..e2ba97b3d8bb 100644
@@ -548,7 +548,7 @@ Linux 裏這是提倡的做法,因爲這樣可以很簡單的給讀者提供
 也可以加上它做這些事情的原因。
 
 當註釋內核 API 函數時,請使用 kernel-doc 格式。詳見
-Documentation/translations/zh_CN/doc-guide/index.rst 和 scripts/kernel-doc 。
+Documentation/translations/zh_CN/doc-guide/index.rst 和 tools/docs/kernel-doc 。
 
 長 (多行) 註釋的首選風格是:
 
MAINTAINERS +0 -2
index 02ec226dd571..d009e2da2215 100644
@@ -7523,7 +7523,6 @@ S:	Maintained
 P:	Documentation/doc-guide/maintainer-profile.rst
 T:	git git://git.lwn.net/linux.git docs-next
 F:	Documentation/
-F:	scripts/kernel-doc*
 F:	tools/lib/python/*
 F:	tools/docs/
 F:	tools/net/ynl/pyynl/lib/doc_generator.py
@@ -7561,7 +7560,6 @@ M:	Mauro Carvalho Chehab <[email protected]>
 L:	[email protected]
 S:	Maintained
 F:	Documentation/sphinx/
-F:	scripts/kernel-doc*
 F:	tools/lib/python/*
 F:	tools/docs/
 
Makefile +1 -1
index 3cd00b62cde9..81a4ab11256c 100644
@@ -460,7 +460,7 @@ HOSTPKG_CONFIG	= pkg-config
 
 # the KERNELDOC macro needs to be exported, as scripts/Makefile.build
 # has a logic to call it
-KERNELDOC       = $(srctree)/scripts/kernel-doc.py
+KERNELDOC       = $(srctree)/tools/docs/kernel-doc
 export KERNELDOC
 
 KBUILD_USERHOSTCFLAGS := -Wall -Wmissing-prototypes -Wstrict-prototypes \
drivers/gpu/drm/i915/Makefile +1 -1
index 4db24050edb0..c979c579de66 100644
@@ -443,7 +443,7 @@ always-$(CONFIG_DRM_I915_WERROR) += \
 
 quiet_cmd_hdrtest = HDRTEST $(patsubst %.hdrtest,%.h,$@)
       cmd_hdrtest = $(CC) $(filter-out $(CFLAGS_GCOV), $(c_flags)) -S -o /dev/null -x c /dev/null -include $<; \
-		$(srctree)/scripts/kernel-doc -none -Werror $<; touch $@
+		$(KERNELDOC) -none -Werror $<; touch $@
 
 $(obj)/%.hdrtest: $(src)/%.h FORCE
 	$(call if_changed_dep,hdrtest)
scripts/kernel-doc deleted +0 -1
deleted file mode 120000
index 3b6ef807791a..000000000000
@@ -1 +0,0 @@
-kernel-doc.py
\ No newline at end of file
tools/docs/find-unused-docs.sh +1 -1
index ca4e607ec3f7..53514c759dc1 100755
@@ -54,7 +54,7 @@ for file in `find $1 -name '*.c'`; do
 	if [[ ${FILES_INCLUDED[$file]+_} ]]; then
 	continue;
 	fi
-	str=$(PYTHONDONTWRITEBYTECODE=1 scripts/kernel-doc -export "$file" 2>/dev/null)
+	str=$(PYTHONDONTWRITEBYTECODE=1 tools/docs/kernel-doc -export "$file" 2>/dev/null)
 	if [[ -n "$str" ]]; then
 	echo "$file"
 	fi
tools/docs/kernel-doc renamed from scripts/kernel-doc.py +1 -1
similarity index 99%
rename from scripts/kernel-doc.py
rename to tools/docs/kernel-doc
index 4e3b9cfe3fd7..a19a92566780 100755
@@ -108,7 +108,7 @@ import sys
 
 # Import Python modules
 
-LIB_DIR = "../tools/lib/python"
+LIB_DIR = "../lib/python"
 SRC_DIR = os.path.dirname(os.path.realpath(__file__))
 
 sys.path.insert(0, os.path.join(SRC_DIR, LIB_DIR))
tools/docs/sphinx-build-wrapper +1 -1
index 7a5fcef25429..cb2a5005e633 100755
@@ -246,7 +246,7 @@ class SphinxBuilder:
         #
         self.sphinxbuild = os.environ.get("SPHINXBUILD", "sphinx-build")
         self.kerneldoc = self.get_path(os.environ.get("KERNELDOC",
-                                                      "scripts/kernel-doc.py"))
+                                                      "tools/docs/kernel-doc"))
         self.builddir = self.get_path(builddir, use_cwd=True, abs_path=True)
 
         #
Signature · 1 line
2.52.0
#7 lore raw

PATCH 7/9 docs: kdoc: move the return values to the helper message

In reply to Mauro Carvalho Chehab

It makes sense to describe what kernel-doc is expected to return on its help message. Move such messages to argparse epilog.

---
 tools/docs/kernel-doc | 27 +++++++++++++++------------
 1 file changed, 15 insertions(+), 12 deletions(-)
tools/docs/kernel-doc +15 -12
index a19a92566780..902397804e80 100755
@@ -166,6 +166,20 @@ This option is kept just for backward-compatibility, but it does nothing,
 neither here nor at the original Perl script.
 """
 
+EPILOG = """
+The return value is:
+
+- 0: success or Python version is not compatible with
+kernel-doc.  If -Werror is not used, it will also
+return 0 if there are issues at kernel-doc markups;
+
+- 1: an abnormal condition happened;
+
+- 2: argparse issued an error;
+
+- 3: When -Werror is used, it means that one or more unfiltered parse
+     warnings happened.
+"""
 
 class MsgFormatter(logging.Formatter):
     """Helper class to format warnings in a similar way to kernel-doc.pl."""
@@ -178,21 +192,10 @@ def main():
     """
     Main program.
 
-    By default, the return value is:
-
-    - 0: success or Python version is not compatible with
-      kernel-doc.  If -Werror is not used, it will also
-      return 0 if there are issues at kernel-doc markups;
-
-    - 1: an abnormal condition happened;
-
-    - 2: argparse issued an error;
-
-    - 3: -Werror is used, and one or more unfiltered parse warnings happened.
     """
 
     parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter,
-                                     description=DESC)
+                                     description=DESC, epilog=EPILOG)
 
     #
     # Normal arguments
Signature · 1 line
2.52.0
#8 lore raw

PATCH 8/9 docs: kdoc: improve description of MsgFormatter

In reply to Mauro Carvalho Chehab

The description there is quite vague. Make it clearer.

---
 tools/docs/kernel-doc | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
tools/docs/kernel-doc +4 -1
index 902397804e80..aed09f9a54dd 100755
@@ -182,7 +182,10 @@ return 0 if there are issues at kernel-doc markups;
 """
 
 class MsgFormatter(logging.Formatter):
-    """Helper class to format warnings in a similar way to kernel-doc.pl."""
+    """
+    Helper class to capitalize errors and warnings, the same way
+    the venerable (now retired) kernel-doc.pl used to do.
+    """
 
     def format(self, record):
         record.levelname = record.levelname.capitalize()
Signature · 1 line
2.52.0
#9 lore raw

PATCH 9/9 docs: conf.py: get rid of the now unused kerneldoc_bin env var

In reply to Mauro Carvalho Chehab

In the past, this contained the location of the binary file to parse kernel-doc. Nowadays, it is used only for debugging purposes, inside kerneldoc.py extension.

Move it to sphinx/kerneldoc.py, to avoid needing to handle with it on several places.

---
 Documentation/conf.py             | 4 ----
 Documentation/sphinx/kerneldoc.py | 7 +++++--
 2 files changed, 5 insertions(+), 6 deletions(-)
Documentation/conf.py +0 -4
index 383d5e5b9d0a..65df81a9e414 100644
@@ -579,10 +579,6 @@ pdf_documents = [
     ("kernel-documentation", "Kernel", "Kernel", "J. Random Bozo"),
 ]
 
-# kernel-doc extension configuration for running Sphinx directly (e.g. by Read
-# the Docs). In a normal build, these are supplied from the Makefile via command
-# line arguments.
-kerneldoc_bin = "../tools/docs/kernel-doc"  # Not used now
 kerneldoc_srctree = ".."
 
 def setup(app):
Documentation/sphinx/kerneldoc.py +5 -2
index afbab458550a..c1cadb4eb099 100644
@@ -47,6 +47,10 @@ sys.path.insert(0, os.path.join(srctree, "tools/lib/python"))
 from kdoc.kdoc_files import KernelFiles
 from kdoc.kdoc_output import RestFormat
 
+# Used when verbose is active to show how to reproduce kernel-doc
+# issues via command line
+kerneldoc_bin = "tools/docs/kernel-doc"
+
 __version__  = '1.0'
 kfiles = None
 logger = logging.getLogger(__name__)
@@ -95,7 +99,7 @@ class KernelDocDirective(Directive):
     def handle_args(self):
 
         env = self.state.document.settings.env
-        cmd = [env.config.kerneldoc_bin, '-rst', '-enable-lineno']
+        cmd = [kerneldoc_bin, '-rst', '-enable-lineno']
 
         filename = env.config.kerneldoc_srctree + '/' + self.arguments[0]
 
@@ -257,7 +261,6 @@ def setup_kfiles(app):
 
 
 def setup(app):
-    app.add_config_value('kerneldoc_bin', None, 'env')
     app.add_config_value('kerneldoc_srctree', None, 'env')
     app.add_config_value('kerneldoc_verbosity', 1, 'env')
 
Signature · 1 line
2.52.0
#10 lore raw

✗ Fi.CI.BUILD: failure for docs: Fix kernel-doc -Werror and moves it to tools/docs

In reply to Mauro Carvalho Chehab
== Series Details ==

== Series Details ==

Series: docs: Fix kernel-doc -Werror and moves it to tools/docs
URL : https://patchwork.freedesktop.org/series/160287/
State : failure

== Summary ==

Error: patch https://patchwork.freedesktop.org/api/1.0/series/160287/revisions/1/mbox/ not applied
Applying: docs: kdoc: fix logic to handle unissued warnings
Applying: docs: kdoc: avoid error_count overflows
Applying: docs: kdoc: ensure that comments are using our coding style
Applying: docs: kdoc: some fixes to kernel-doc comments
Applying: docs: kdoc: remove support for an external kernel-doc from sphinx
Applying: docs: kdoc: move kernel-doc to tools/docs
error: sha1 information is lacking or useless (MAINTAINERS).
error: could not build fake ancestor
hint: Use 'git am --show-current-patch=diff' to see the failed patch
Patch failed at 0006 docs: kdoc: move kernel-doc to tools/docs
When you have resolved this problem, run "git am --continue".
If you prefer to skip this patch, run "git am --skip" instead.
To restore the original branch and stop patching, run "git am --abort".
Build failed, no error log produced

maintainer
#11 lore raw
In reply to Mauro Carvalho Chehab
Quoted 13 lines · Mauro Carvalho Chehab

Hi Jon,

After a restful weekend and revisiting both yours and my series, I'm opting to send a patch series merging both into one:

- The first 4 patches are from my series (no changes since v5):

    https://lore.kernel.org/linux-doc/[email protected]/T/#m81211c0ff38bbaa82b8b0b6606f242ccc0c2a9ac

- It follows by the 2 patches from your renaming series:

    https://lore.kernel.org/linux-doc/[email protected]/T/#m51099c31a99dccccdb4d17cbaadc818e9e4df8c4

with the fix I proposed for kernel-doc to find its libraries

Quoted 8 lines

I added 3 patches afterwards:

- patch 5: move possible return values from docstring to helper message;
- patch 6: improve MsgFormatter description;
- patch 7: moves kerneldoc_bin from conf.py to the sphinx/kerneldoc.py (this is now just a debugging message - no need to pick it from env)

IMO, this series is ready to be merged.

Patch 7 adds a new warning:

WARNING: unknown config value 'kerneldoc_bin' in override, ignoring

It needs to be taken out of sphinx-build-wrapper; I've appended the following patch to the series to deal with it. I think I'll go ahead and tack on a patch putting in the scripts/kernel-doc symlink, then I guess it's ready to go.

Thanks,

jon

From 4a3efd128f7da996b677151790d043ec44a00561 Mon Sep 17 00:00:00 2001
From: Jonathan Corbet <[email protected]>
Date: Tue, 20 Jan 2026 15:50:38 -0700
Subject: [PATCH] docs: sphinx-build-wrapper: stop setting kerneldoc_bin for
Sphinx

Now that the Sphinx build does not use the kerneldoc_bin configuration variable, we shouldn't try to set it in the build wrapper or we get a nifty warning:

WARNING: unknown config value 'kerneldoc_bin' in override, ignoring

---
 tools/docs/sphinx-build-wrapper | 1 -
 1 file changed, 1 deletion(-)
tools/docs/sphinx-build-wrapper +0 -1
index cb2a5005e633..9f1ae1485f84 100755
@@ -750,7 +750,6 @@ class SphinxBuilder:
 
             build_args = args + [
                 "-d", doctree_dir,
-                "-D", f"kerneldoc_bin={kerneldoc}",
                 "-D", f"version={self.kernelversion}",
                 "-D", f"release={self.kernelrelease}",
                 "-D", f"kerneldoc_srctree={self.srctree}",
Signature · 1 line
2.52.0
author Reviewed-by
#12 lore raw

Hi Jon,

Quoted 22 lines · On Tue, 20 Jan 2026 15:56:48 -0700 Jonathan Corbet <[email protected]> wrote:
Quoted 20 lines · Mauro Carvalho Chehab

Hi Jon,

After a restful weekend and revisiting both yours and my series, I'm opting to send a patch series merging both into one:

- The first 4 patches are from my series (no changes since v5):

    https://lore.kernel.org/linux-doc/[email protected]/T/#m81211c0ff38bbaa82b8b0b6606f242ccc0c2a9ac

- It follows by the 2 patches from your renaming series:

    https://lore.kernel.org/linux-doc/[email protected]/T/#m51099c31a99dccccdb4d17cbaadc818e9e4df8c4

with the fix I proposed for kernel-doc to find its libraries

I added 3 patches afterwards:

- patch 5: move possible return values from docstring to helper message;
- patch 6: improve MsgFormatter description;
- patch 7: moves kerneldoc_bin from conf.py to the sphinx/kerneldoc.py (this is now just a debugging message - no need to pick it from env)

Quoted 8 lines
Quoted 1 line

IMO, this series is ready to be merged.

Patch 7 adds a new warning:

WARNING: unknown config value 'kerneldoc_bin' in override, ignoring

It needs to be taken out of sphinx-build-wrapper; I've appended the following patch to the series to deal with it.

True, thanks for checking it!

Quoted 3 lines

I think I'll go ahead
and tack on a patch putting in the scripts/kernel-doc symlink, then I guess it's ready to go.

Go ahead. Yeah, I think that, with such changes, this series is ready to go.

Quoted 11 lines

Thanks,

jon

From 4a3efd128f7da996b677151790d043ec44a00561 Mon Sep 17 00:00:00 2001
From: Jonathan Corbet <[email protected]>
Date: Tue, 20 Jan 2026 15:50:38 -0700
Subject: [PATCH] docs: sphinx-build-wrapper: stop setting kerneldoc_bin for
Sphinx

Quoted 7 lines

Now that the Sphinx build does not use the kerneldoc_bin configuration variable, we shouldn't try to set it in the build wrapper or we get a nifty warning:

WARNING: unknown config value 'kerneldoc_bin' in override, ignoring

Quoted 9 lines
---
 tools/docs/sphinx-build-wrapper | 1 -
 1 file changed, 1 deletion(-)
tools/docs/sphinx-build-wrapper +0 -0
index cb2a5005e633..9f1ae1485f84 100755

tools/docs/sphinx-build-wrapper class SphinxBuilder: · line 755

Quoted 7 lines
tools/docs/sphinx-build-wrapper +0 -1
@@ -750,7 +750,6 @@ class SphinxBuilder:
 
             build_args = args + [
                 "-d", doctree_dir,
-                "-D", f"kerneldoc_bin={kerneldoc}",
                 "-D", f"version={self.kernelversion}",
                 "-D", f"release={self.kernelrelease}",
                 "-D", f"kerneldoc_srctree={self.srctree}",

Thanks,
Mauro