Skip to contentSkip to conversation

Add testable code specifications

RFC PATCH In review Gabriele Paoloni 7 participants 25 messages Sep 10, 2025 – Nov 26, 2025

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

v2 cover Add testable code specifications

[1] was an initial proposal defining testable code specifications for some functions in /drivers/char/mem.c.
However a Guideline to write such specifications was missing and test cases tracing to such specifications were missing.
This patchset represents a next step and is organised as follows:
- patch 1/3 contains the Guideline for writing code specifications
- patch 2/3 contains examples of code specfications defined for some functions of drivers/char/mem.c
- patch 3/3 contains examples of selftests that map to some code specifications of patch 2/3

[1] https://lore.kernel.org/all/[email protected]/
---
Changes from v1:
1) Added a Guideline to write code specifications in the Linux Kernel Documentation
2) Addressed Greg KH comments in /drivers/char/mem.c
3) Added example of test cases mapping to the code specifications in /drivers/char/mem.c
---
Alessandro Carminati (1):
selftests/devmem: initial testset

Gabriele Paoloni (2):
Documentation: add guidelines for writing testable code specifications /dev/mem: Add initial documentation of memory_open() and mem_fops

 .../doc-guide/code-specifications.rst         | 208 +++++++
 Documentation/doc-guide/index.rst             |   1 +
 drivers/char/mem.c                            | 231 ++++++-
 tools/testing/selftests/Makefile              |   1 +
 tools/testing/selftests/devmem/Makefile       |  13 +
 tools/testing/selftests/devmem/debug.c        |  25 +
 tools/testing/selftests/devmem/debug.h        |  14 +
 tools/testing/selftests/devmem/devmem.c       | 200 ++++++
 tools/testing/selftests/devmem/ram_map.c      | 250 ++++++++
 tools/testing/selftests/devmem/ram_map.h      |  38 ++
 tools/testing/selftests/devmem/secret.c       |  46 ++
 tools/testing/selftests/devmem/secret.h       |  13 +
 tools/testing/selftests/devmem/tests.c        | 569 ++++++++++++++++++
 tools/testing/selftests/devmem/tests.h        |  45 ++
 tools/testing/selftests/devmem/utils.c        | 379 ++++++++++++
 tools/testing/selftests/devmem/utils.h        | 119 ++++
 16 files changed, 2146 insertions(+), 6 deletions(-)
 create mode 100644 Documentation/doc-guide/code-specifications.rst
 create mode 100644 tools/testing/selftests/devmem/Makefile
 create mode 100644 tools/testing/selftests/devmem/debug.c
 create mode 100644 tools/testing/selftests/devmem/debug.h
 create mode 100644 tools/testing/selftests/devmem/devmem.c
 create mode 100644 tools/testing/selftests/devmem/ram_map.c
 create mode 100644 tools/testing/selftests/devmem/ram_map.h
 create mode 100644 tools/testing/selftests/devmem/secret.c
 create mode 100644 tools/testing/selftests/devmem/secret.h
 create mode 100644 tools/testing/selftests/devmem/tests.c
 create mode 100644 tools/testing/selftests/devmem/tests.h
 create mode 100644 tools/testing/selftests/devmem/utils.c
 create mode 100644 tools/testing/selftests/devmem/utils.h
Signature · 1 line
2.48.1
#1 lore raw

RFC PATCH v2 1/3 Documentation: add guidelines for writing testable code specifications

The Documentation/doc-guide/kernel-doc.rst chapter describes how to document the code using the kernel-doc format, however it does not specify the criteria to be followed for writing testable specifications; i.e. specifications that can be used to for the semantic description of low level requirements.

This patch adds a guideline that defines criteria to formally describe developers’ intent at the function and subfunction level in the form of testable expectations.

---
 .../doc-guide/code-specifications.rst         | 208 ++++++++++++++++++
 Documentation/doc-guide/index.rst             |   1 +
 2 files changed, 209 insertions(+)
 create mode 100644 Documentation/doc-guide/code-specifications.rst
Documentation/doc-guide/code-specifications.rst new file +208 -0
new file mode 100644
index 000000000000..dee1b4f089e1
@@ -0,0 +1,208 @@
+.. title:: How-to write testable code specifications
+
+=========================================
+How-to write testable code specifications
+=========================================
+
+Introduction
+------------
+The Documentation/doc-guide/kernel-doc.rst chapter describes how to document the code using the kernel-doc format, however it does not specify the criteria to be followed for writing testable specifications; i.e. specifications that can be used to for the semantic description of low level requirements.
+
+This chapter defines criteria to formally describe developers’ intent at the function and subfunction level in the form of testable expectations.
+
+A Virtuous Cycle
+----------------
+By adding testable specifications at the function or (where relevant) subfunction level, one enables the creation of a virtuous cycle when testing is supplemented with open source code coverage tools like llvm-cov or Gcov.
+
+As a true reflection of developer intent, code specifications inform the creation of a pass/fail tests which can then be assessed in conjunction with code coverage tools. A failing test may indicate broken code or specifications that fail to capture developer intent. A gap in code coverage may indicate missing specifications, unintended functionalities, or insufficient test procedure.
+
+High level goals
+----------------
+The code specifications:
+
+1. Should be maintainable together with the code.
+2. Should support hierarchical traceability to allow refinement of SW dependencies (i.e. cross reference critical APIs or data structures).
+3. Should describe error conditions and success behaviors.
+4. Should describe conditions to be met by the user to avoid unspecified or unwanted behaviours.
+5. Should allow covering both static and dynamic aspects of the code.
+6. Should be compatible with Documentation/doc-guide/kernel-doc.rst.
+7. Should support the definition of a test plan (i.e. syntax should enforce testability as well as the avoidance of untestable specifications, e.g “function_xyz() shall not do something”).
+
+Format and Syntax
+-----------------
+Testable code specifications must be written according to the syntax already defined in Documentation/doc-guide/kernel-doc.rst with additional rules that are described below.
+
+Function name
+~~~~~~~~~~~~~
+``* function_name() - Brief description of function.``
+
+This field is to be considered informative and is not part of the testable specifications.
+
+Input Arguments
+~~~~~~~~~~~~~~~
+Input arguments should be specified in a way that better supports the function’s expectations and Assumptions of Use described below.
+They must not contradict the function's expectations and the function’s prototype. For example::
+
+ * trace_set_clr_event - enable or disable an event
+ * @system: system name to match (NULL for any system)
+ * @event: event name to match (NULL for all events, within system)
+ * @set: 1 to enable, 0 to disable
+ *
+ [...]
+ *
+ */
+ int trace_set_clr_event(const char *system, const char *event, int set)
+
+Above all the parameters clearly introduce the impact that they have on the code specifications.
+
+However if below we had::
+
+ * trace_set_clr_event - enable or disable an event
+ * @system: system name to match (NULL for any system)
+ * @event: event name to match (NULL for all events, within system)
+ * @set: true to enable, false to disable \
+ [...]
+ */
+ int trace_set_clr_event(const char *system, const char *event, int set)
+
+In this case @set would be a bad definition since it is defined as an integer and not as a boolean.
+
+Longer Description
+~~~~~~~~~~~~~~~~~~
+The `Longer Description` section is where the large part of testable code specifications are defined. The section must be organised as follows::
+
+ * (Summary Description) provides an introduction of the functionalities
+ * provided by the function and any informal note. This text does not
+ * represent any testable code specification.
+ *
+ *
+ * Function's expectations:
+ * [ID1] - [code expectation]
+ *
+ * [ID2] - [code expectation]
+ *
+ * [...]
+ *
+ * [IDn] - [code expectation]
+ *
+ * Assumptions of Use:
+ * [ID1] - [constraint to be met by the caller]
+ *
+ * [ID2] - [constraint to be met by the caller]
+ *
+ * [IDn] - [constraint to be met by the caller]
+ *
+
+When writing the above section the following rules must be followed:
+
+* No rules apply to the text above ``Function’s expectations``; such a text does not constitute testable specifications and it is just informative;
+* Both ``Function’s expectations`` and ``Assumptions of Use`` must be listed prefixing each of them with an ID that is unique within this kernel-doc header. The reason for this is to facilitate cross-referencing and traceability between tests and code specifications.
+* A Function’s expectation is a testable behavior that the function is expected to comply with (i.e. the function is expected to behave as defined in the function’s expectation).
+* An Assumption of Use is  a pre-condition to be met when invoking the function being documented.
+* Testable functional expectations and Assumptions of Use must be constructed according the same rules that apply when writing software requirements:
+    * Statements should include a subject and a verb, together with other elements necessary to adequately express the information content of the specifications.
+    * The verbs are required to use the following keywords:
+        * For mandatory expectations the verb ‘shall’ is to be used;
+        * For descriptive text that do not constitute a testable expectation verbs such as ‘are’, ‘is’, ‘was’ are to be used;
+        * Negative expectations must be avoided (e.g. ‘shall not’ must be avoided).
+* Statements must be constructed according to the following scheme:
+
+    [**Condition**] [**Subject**] [**Verb/Action**] [**Object**] [**Constraint of Action**].
+
+    In this regard [**Condition**] and [**Constraint of Action**] could be omitted respectively if the [**Action**] being specified must always happen or if there are no constraints associated with it.
+
+Function Context
+~~~~~~~~~~~~~~~~
+The function’s context represents an integral part of Function’s expectations and Assumptions of Use, where these can further specify the information contained in this section.
+
+Without further specifications this section is to be interpreted as per example below:
+
+``* Context: Any context.``
+
+The function shall execute in any possible context.
+
+``* Context: Any context. Takes and releases the RCU lock.``
+
+The function shall execute in any possible context.
+The function shall take and release the RCU lock.
+
+``* Context: Any context. Expects <lock> to be held by caller.``
+
+The function shall execute in any possible context.
+<lock> is assumed to be held before this function is called.
+
+``* Context: Process context. May sleep if @gfp flags permit.``
+
+The function shall execute in process context.
+The function shall sleep according to @gfp flags definitions
+
+``* Context: Process context. Takes and releases <mutex>.``
+
+The function shall execute in process context.
+The function shall take and release <mutex>.
+
+``* Context: Softirq or process context. Takes and releases <lock>, BH-safe.``
+
+The function shall execute in process or Softirq context.
+The function shall take and release <lock>.
+The function shall safely execute in bottom half contexts.
+
+``* Context: Interrupt context.``
+
+The function shall execute in interrupt context only.
+
+It is a good practice to further specify the context specifications as part of the Function’s expectation (e.g. at which stage a lock is held and released)
+
+Return values
+~~~~~~~~~~~~~
+Return values must be written as a multiple line list in the following format::
+
+* Return:
+* * [value-1] - [condition-1]
+* * [value-2] - [condition-2]
+* * [...]
+* * [value-n] - [condition-n]
+* * Any value returned by func-1(), func-2(),...,func-n()
+
+In such a format ``[value-i]`` must be a clearly identified value or range of values that is compatible with the function prototype (e.g. for a read() file operation, it is ok to define [value-i] as ``the number of bytes successfully copied to the user space buffer``).
+
+``[condition-i]`` must be a condition that can be unambiguously traced back to the ``Function’s expectations`` or ``Context`` defined above; as part of [condition-i] it is possible to refer to dependencies of invoked functions or of internal SW or HW states.
+
+``Any value returned by func-1(), func-2(),...,func-n()`` defines a scenario where the current function is directly returning the value of an invoked function dependency.
+
+Semantic aspects of testable specifications
+-------------------------------------------
+From a semantic point of view it is important to document the intended or expected behavior (from a developer or integrator point of view respectively) in consideration of the different design aspects impacting it.
+
+Such behavior shall be described in a way that makes it possible to define test cases unambiguously. \
+To this extent it is important to document design elements impacting the expected behavior and the design elements characterizing the expected behavior (and sometimes these can physically overlap); such design elements shall be limited to the scope of the code being documented, that can range from a single function to multiple ones depending on the complexity of the overall code.
+
+**Possible elements impacting the expected behavior** of the code being documented are:
+
+* Input parameters: parameters passed to the API being documented;
+* state variables: global and static data (variables or pointers);
+* software dependencies: external SW APIs invoked by the code under analysis;
+* Hardware dependencies: HW design elements directly impacting the behavior of the code in scope;
+* Firmware dependencies: FW design elements that have an impact on the behavior of the API being documented (e.g. DTB or ACPI tables, or runtime services like SCMI and ACPI AML);
+* Compile time configuration parameters: configuration parameters parsed when compiling the Kernel Image;
+* Runtime configuration parameters (AKA calibration parameters): parameters that can be modified at runtime.
+
+**Design elements characterizing the expected behavior** of the API being documented that are in scope according to the above mentioned granularity:
+
+* API return values, including pointer addresses;
+* Input pointers: pointers passed as input parameter to the API being documented;
+* state variables: global and static data (variable or pointers);
+* Hardware design elements (e.g. HW registers).
+
+**Testability considerations**: the impact of each of the documented “design elements impacting the expected behavior” must be described in terms of effect on the “design element characterizing the expected behavior” and, in doing so, it is important to document allowed or not allowed ranges of values, corner cases and error conditions;  so that it is possible to define a meaningful test plan according to different equivalence classes.
+
+**Scalability and maintainability considerations**: the described expected behavior must be limited to the scope of the code under analysis so for example the Software, Firmware and Hardware dependencies shall be described in terms of possible impact on the invoking code deferring further details to the respective documentation of these.
+
+When deciding the scope of the code being documented, the scalability and maintainability goals must be considered; it does not make sense to embed the documentation of multiple complex functions within the kernel-doc header of the top level function as, doing so, would make it harder to review the code changes against the documented specifications and/or to extend the specifications to new functionalities being added.
+
+The end goal is to build a hierarchical, scalable, maintainable documentation.
+
+**Feasibility considerations**: Only the “meaningful” and “useful” expected behavior, and the design elements impacting it, shall be considered (e.g. a printk() logging some info may be omitted). There are two reasons behind this point:
+
+1. Specifying the expected behaviour of the code should be done, in principle, in a code agnostic way. So it is not about writing a pseudo-code redundant implementation, but rather about defining and documenting the developer intent and the integrator’s expectations.
+2. When the expected behavior is defined before implementing the code, such an activity is done by experts using a level of detail that is more abstract than the code itself and they only refer to aspects that are relevant for the design expectations.
Documentation/doc-guide/index.rst +1 -0
index 24d058faa75c..09e459866442 100644
@@ -9,6 +9,7 @@ How to write kernel documentation
 
    sphinx
    kernel-doc
+   code-specifications
    parse-headers
    contributing
    maintainer-profile
Signature · 1 line
2.48.1
maintainer
#2 lore raw

Re: [RFC v2 PATCH 1/3] Documentation: add guidelines for writing testable code specifications

Gabriele Paoloni <[email protected]> writes:

[Taking a quick look...]

Quoted 25 lines

The Documentation/doc-guide/kernel-doc.rst chapter describes how to document the code using the kernel-doc format, however it does not specify the criteria to be followed for writing testable specifications; i.e. specifications that can be used to for the semantic description of low level requirements.

This patch adds a guideline that defines criteria to formally describe developers’ intent at the function and subfunction level in the form of testable expectations.

---
 .../doc-guide/code-specifications.rst         | 208 ++++++++++++++++++
 Documentation/doc-guide/index.rst             |   1 +
 2 files changed, 209 insertions(+)
 create mode 100644 Documentation/doc-guide/code-specifications.rst
Documentation/doc-guide/code-specifications.rst new file +0 -0
new file mode 100644
index 000000000000..dee1b4f089e1

Documentation/doc-guide/code-specifications.rst line 9

Quoted 9 lines
Documentation/doc-guide/code-specifications.rst new file +9 -0
@@ -0,0 +1,208 @@
+.. title:: How-to write testable code specifications
+
+=========================================
+How-to write testable code specifications
+=========================================
+
+Introduction
+------------
+The Documentation/doc-guide/kernel-doc.rst chapter describes how to document the code using the kernel-doc format, however it does not specify the criteria to be followed for writing testable specifications; i.e. specifications that can be used to for the semantic description of low level requirements.

Please, for any future versions, stick to the 80-column limit; this is especially important for text files that you want humans to read.

As a nit, you don't need to start by saying what other documents don't do, just describe the purpose of *this* document.

More substantially ... I got a way into this document before realizing that you were describing an addition to the format of kerneldoc comments. That would be good to make clear from the outset.

What I still don't really understand is what is the *purpose* of this formalized text? What will be consuming it? You're asking for a fair amount of effort to write and maintain these descriptions; what's in it for the people who do that work?

How does an author determine whether the specifications they have written are correct, both gramatically and semantically?

Thanks,

jon

#3 lore raw

Re: [RFC v2 PATCH 1/3] Documentation: add guidelines for writing testable code specifications

Hi Jonathan

Many thanks for your review

Quoted 34 lines · Jonathan Corbet

Gabriele Paoloni <[email protected]> writes:

[Taking a quick look...]

Quoted 29 lines

The Documentation/doc-guide/kernel-doc.rst chapter describes how to document the code using the kernel-doc format, however it does not specify the criteria to be followed for writing testable specifications; i.e. specifications that can be used to for the semantic description of low level requirements.

This patch adds a guideline that defines criteria to formally describe developers’ intent at the function and subfunction level in the form of testable expectations.

---
 .../doc-guide/code-specifications.rst         | 208 ++++++++++++++++++
 Documentation/doc-guide/index.rst             |   1 +
 2 files changed, 209 insertions(+)
 create mode 100644 Documentation/doc-guide/code-specifications.rst
Documentation/doc-guide/code-specifications.rst new file +4 -0
new file mode 100644
index 000000000000..dee1b4f089e1
@@ -0,0 +1,208 @@
+.. title:: How-to write testable code specifications
+
+=========================================
+How-to write testable code specifications
Quoted 8 lines

Documentation/doc-guide/code-specifications.rst line 9

Quoted 5 lines
Documentation/doc-guide/code-specifications.rst new file +5 -0
+=========================================
+
+Introduction
+------------
+The Documentation/doc-guide/kernel-doc.rst chapter describes how to document the code using the kernel-doc format, however it does not specify the criteria to be followed for writing testable specifications; i.e. specifications that can be used to for the semantic description of low level requirements.

Please, for any future versions, stick to the 80-column limit; this is especially important for text files that you want humans to read.

Thanks I will stick to 80 chars for future submissions

Quoted 3 lines

As a nit, you don't need to start by saying what other documents don't do, just describe the purpose of *this* document.

Yes, my goal was to explain the purpose of this doc, however, re-reading this intro I realize that it uses a negative tone, that is not good. I will rephrase explaining the it expands on top of kernel-doc.rst to further specify the expectations from the code and the assumptions to correctly use it.

Quoted 9 lines

More substantially ... I got a way into this document before realizing that you were describing an addition to the format of kerneldoc comments. That would be good to make clear from the outset.

What I still don't really understand is what is the *purpose* of this formalized text? What will be consuming it? You're asking for a fair amount of effort to write and maintain these descriptions; what's in it for the people who do that work?

The goal is to clearly define what the code is expected to do and how to correctly invoke it so that:
1) A user of the code does not wrongly invoke it
2) A developer or a maintainer can check if code changes are compliant with such expectations (maybe he did wrong changes or the expectations need to change)
3) A tester can verify if test cases are correct WRT such expectations and complete

Quoted 3 lines

How does an author determine whether the specifications they have written are correct, both gramatically and semantically?

For grammatical purpose, probably an automated check could be implemented, for semantic aspects the first level of verification comes from the community and maintainer review process, whereas the second level of verification come from selftests that should be written according to the expectations from the code and should trace to them (as in the example in patch 3)

Thanks
Gab

Quoted 5 lines

Thanks,

jon

#4 lore raw

Re: [RFC v2 PATCH 1/3] Documentation: add guidelines for writing testable code specifications

In reply to Jonathan Corbet
Quoted 9 lines
Quoted 2 lines

+------------
+The Documentation/doc-guide/kernel-doc.rst chapter describes how to document the code using the kernel-doc format, however it does not specify the criteria to be followed for writing testable specifications; i.e. specifications that can be used to for the semantic description of low level requirements.

Please, for any future versions, stick to the 80-column limit; this is especially important for text files that you want humans to read.

As a nit, you don't need to start by saying what other documents don't do, just describe the purpose of *this* document.

Quoted 8 lines

More substantially ... I got a way into this document before realizing that you were describing an addition to the format of kerneldoc comments. That would be good to make clear from the outset.

What I still don't really understand is what is the *purpose* of this formalized text? What will be consuming it? You're asking for a fair amount of effort to write and maintain these descriptions; what's in it for the people who do that work?

I might be wrong, but sounds to me like someone intends to feed this to AI to generate tests or code.

In that case, no thanks.

I'm pretty sure we don't want this.

Signature · 3 lines
Cheers

David / dhildenb
#5 lore raw

Re: [RFC v2 PATCH 1/3] Documentation: add guidelines for writing testable code specifications

Quoted 17 lines · David Hildenbrand
Quoted 2 lines
Quoted 2 lines

+------------
+The Documentation/doc-guide/kernel-doc.rst chapter describes how to

document the code using the kernel-doc format, however it does not specify the criteria to be followed for writing testable specifications; i.e. specifications that can be used to for the semantic description of low level requirements.

Quoted 11 lines

Please, for any future versions, stick to the 80-column limit; this is especially important for text files that you want humans to read.

As a nit, you don't need to start by saying what other documents don't do, just describe the purpose of *this* document.

More substantially ... I got a way into this document before realizing that you were describing an addition to the format of kerneldoc comments. That would be good to make clear from the outset.

Quoted 8 lines
Quoted 4 lines

What I still don't really understand is what is the *purpose* of this formalized text? What will be consuming it? You're asking for a fair amount of effort to write and maintain these descriptions; what's in it for the people who do that work?

I might be wrong, but sounds to me like someone intends to feed this to AI to generate tests or code.

Absolutely not the intent. This is about the lossy process of converting human
ideas to code. Reliably going from code to test requires an understanding of what was lost in translation. This project is about filling that gap.

In that case, no thanks.

Quoted 3 lines

I'm pretty sure we don't want this.

Nor I. If you find any references in our work that amount to a validation of your concerns, please bring them to our attention.

..Ch:W..

#6 lore raw

Re: [RFC v2 PATCH 1/3] Documentation: add guidelines for writing testable code specifications

In reply to David Hildenbrand

[Reposting with apologies for the dup and those inflicted by the broken Gmail defaults. I have migrated away from Gmail, but some threads are still stuck there.]

Quoted 14 lines · David Hildenbrand
Quoted 14 lines
Quoted 3 lines

+------------
+The Documentation/doc-guide/kernel-doc.rst chapter describes how to document the code using the kernel-doc format, however it does not specify the criteria to be followed for writing testable specifications; i.e. specifications that can be used to for the semantic description of low level requirements.

Please, for any future versions, stick to the 80-column limit; this is especially important for text files that you want humans to read.

As a nit, you don't need to start by saying what other documents don't do, just describe the purpose of *this* document.

More substantially ... I got a way into this document before realizing that you were describing an addition to the format of kerneldoc comments. That would be good to make clear from the outset.

Quoted 7 lines
Quoted 4 lines

What I still don't really understand is what is the *purpose* of this formalized text? What will be consuming it? You're asking for a fair amount of effort to write and maintain these descriptions; what's in it for the people who do that work?

I might be wrong, but sounds to me like someone intends to feed this to AI to generate tests or code.

Absolutely not the intent. This is about the lossy process of converting human ideas to code. Reliably going from code to test requires an understanding of what was lost in translation. This project is about filling that gap.

Quoted 3 lines

In that case, no thanks.

I'm pretty sure we don't want this.

Nor I. If you find any references in our work that amount to a validation of your concerns, please bring them to our attention.

..Ch:W..

#7 lore raw

Re: [RFC v2 PATCH 1/3] Documentation: add guidelines for writing testable code specifications

Quoted 24 lines · Chuck Wolber

[Reposting with apologies for the dup and those inflicted by the broken Gmail defaults. I have migrated away from Gmail, but some threads are still stuck there.]

Quoted 19 lines · David Hildenbrand
Quoted 18 lines
Quoted 3 lines

+------------
+The Documentation/doc-guide/kernel-doc.rst chapter describes how to document the code using the kernel-doc format, however it does not specify the criteria to be followed for writing testable specifications; i.e. specifications that can be used to for the semantic description of low level requirements.

Please, for any future versions, stick to the 80-column limit; this is especially important for text files that you want humans to read.

As a nit, you don't need to start by saying what other documents don't do, just describe the purpose of *this* document.

More substantially ... I got a way into this document before realizing that you were describing an addition to the format of kerneldoc comments. That would be good to make clear from the outset.

What I still don't really understand is what is the *purpose* of this formalized text? What will be consuming it? You're asking for a fair amount of effort to write and maintain these descriptions; what's in it for the people who do that work?

Quoted 6 lines
Quoted 2 lines

I might be wrong, but sounds to me like someone intends to feed this to AI to generate tests or code.

Absolutely not the intent. This is about the lossy process of converting human ideas to code. Reliably going from code to test requires an understanding of what was lost in translation. This project is about filling that gap.

Thanks for clarifying. I rang my alarm bells too early :)

I saw the LPC talk on this topic:

https://lpc.events/event/19/contributions/2085/

With things like "a test case can be derived from the testable expectation" one wonders how we get from the the doc to an actual test case.

IIRC, with things like formal verification we usually don't write in natural language, because it's too imprecise. But my formal verification knowledge is a bit rusty.

Quoted 8 lines
Quoted 5 lines

In that case, no thanks.

I'm pretty sure we don't want this.

Nor I. If you find any references in our work that amount to a validation of your concerns, please bring them to our attention.

I guess, as the discussion with me and Jonathan showed, the cover letter is a bit short on the motivation, making people like me speculate a bit too much about the intentions.

Signature · 3 lines
Cheers

David / dhildenb
#8 lore raw

Re: [RFC v2 PATCH 1/3] Documentation: add guidelines for writing testable code specifications

Hi David

Quoted 33 lines · David Hildenbrand
Quoted 24 lines · Chuck Wolber

[Reposting with apologies for the dup and those inflicted by the broken Gmail defaults. I have migrated away from Gmail, but some threads are still stuck there.]

Quoted 19 lines · David Hildenbrand
Quoted 18 lines
Quoted 3 lines

+------------
+The Documentation/doc-guide/kernel-doc.rst chapter describes how to document the code using the kernel-doc format, however it does not specify the criteria to be followed for writing testable specifications; i.e. specifications that can be used to for the semantic description of low level requirements.

Please, for any future versions, stick to the 80-column limit; this is especially important for text files that you want humans to read.

As a nit, you don't need to start by saying what other documents don't do, just describe the purpose of *this* document.

More substantially ... I got a way into this document before realizing that you were describing an addition to the format of kerneldoc comments. That would be good to make clear from the outset.

What I still don't really understand is what is the *purpose* of this formalized text? What will be consuming it? You're asking for a fair amount of effort to write and maintain these descriptions; what's in it for the people who do that work?

Quoted 6 lines
Quoted 2 lines

I might be wrong, but sounds to me like someone intends to feed this to AI to generate tests or code.

Absolutely not the intent. This is about the lossy process of converting human ideas to code. Reliably going from code to test requires an understanding of what was lost in translation. This project is about filling that gap.

Quoted 8 lines

Thanks for clarifying. I rang my alarm bells too early :)

I saw the LPC talk on this topic:

https://lpc.events/event/19/contributions/2085/

With things like "a test case can be derived from the testable expectation" one wonders how we get from the the doc to an actual test case.

Probably it is the term derived that can be a bit misleading. The point is that we need documented expectations that can be used to review and verify the test cases against; so maybe better to say "a test case can be verified against the testable expectation"

Quoted 9 lines

IIRC, with things like formal verification we usually don't write in natural language, because it's too imprecise. But my formal verification knowledge is a bit rusty.

Quoted 4 lines
Quoted 4 lines

In that case, no thanks.

Quoted 8 lines
Quoted 4 lines
Quoted 1 line

I'm pretty sure we don't want this.

Nor I. If you find any references in our work that amount to a validation of your concerns, please bring them to our attention.

I guess, as the discussion with me and Jonathan showed, the cover letter is a bit short on the motivation, making people like me speculate a bit too much about the intentions.

Right, I'll keep this in mind for v2 and I will improve the motivation aspect (also leveraging the response I gave to Jonathan).

Many thanks for your feedbacks!
Gab

Quoted 6 lines

--
Cheers

David / dhildenb

#9 lore raw

Re: [RFC v2 PATCH 1/3] Documentation: add guidelines for writing testable code specifications

Quoted 42 lines · Gabriele Paoloni

Hi David

Quoted 39 lines · David Hildenbrand
Quoted 24 lines · Chuck Wolber

[Reposting with apologies for the dup and those inflicted by the broken Gmail defaults. I have migrated away from Gmail, but some threads are still stuck there.]

Quoted 19 lines · David Hildenbrand
Quoted 18 lines
Quoted 3 lines

+------------
+The Documentation/doc-guide/kernel-doc.rst chapter describes how to document the code using the kernel-doc format, however it does not specify the criteria to be followed for writing testable specifications; i.e. specifications that can be used to for the semantic description of low level requirements.

Please, for any future versions, stick to the 80-column limit; this is especially important for text files that you want humans to read.

As a nit, you don't need to start by saying what other documents don't do, just describe the purpose of *this* document.

More substantially ... I got a way into this document before realizing that you were describing an addition to the format of kerneldoc comments. That would be good to make clear from the outset.

What I still don't really understand is what is the *purpose* of this formalized text? What will be consuming it? You're asking for a fair amount of effort to write and maintain these descriptions; what's in it for the people who do that work?

Quoted 6 lines
Quoted 2 lines

I might be wrong, but sounds to me like someone intends to feed this to AI to generate tests or code.

Absolutely not the intent. This is about the lossy process of converting human ideas to code. Reliably going from code to test requires an understanding of what was lost in translation. This project is about filling that gap.

Thanks for clarifying. I rang my alarm bells too early :)

I saw the LPC talk on this topic:

https://lpc.events/event/19/contributions/2085/

Quoted 7 lines
Quoted 2 lines

With things like "a test case can be derived from the testable expectation" one wonders how we get from the the doc to an actual test case.

Probably it is the term derived that can be a bit misleading. The point is that we need documented expectations that can be used to review and verify the test cases against; so maybe better to say "a test case can be verified against the testable expectation"

On a high level (where we usually test with things like LTP) I would usually expect that the man pages properly describe the semantics of syscalls etc.

That also feels like a better place to maintain such kind of information.

Having that said, man-pages are frequently a bit outdated or imprecise .. or missing.

Anyhow, I guess that will all be discussed in your LPC session I assume, I'll try to attend that one, thanks!

Signature · 3 lines
Cheers

David / dhildenb
#10 lore raw

Re: [RFC v2 PATCH 1/3] Documentation: add guidelines for writing testable code specifications

Quoted 47 lines · David Hildenbrand
Quoted 45 lines · Gabriele Paoloni

Hi David

Quoted 41 lines · David Hildenbrand
Quoted 24 lines · Chuck Wolber

[Reposting with apologies for the dup and those inflicted by the broken Gmail defaults. I have migrated away from Gmail, but some threads are still stuck there.]

Quoted 19 lines · David Hildenbrand
Quoted 18 lines
Quoted 3 lines

+------------
+The Documentation/doc-guide/kernel-doc.rst chapter describes how to document the code using the kernel-doc format, however it does not specify the criteria to be followed for writing testable specifications; i.e. specifications that can be used to for the semantic description of low level requirements.

Please, for any future versions, stick to the 80-column limit; this is especially important for text files that you want humans to read.

As a nit, you don't need to start by saying what other documents don't do, just describe the purpose of *this* document.

More substantially ... I got a way into this document before realizing that you were describing an addition to the format of kerneldoc comments. That would be good to make clear from the outset.

What I still don't really understand is what is the *purpose* of this formalized text? What will be consuming it? You're asking for a fair amount of effort to write and maintain these descriptions; what's in it for the people who do that work?

Quoted 6 lines
Quoted 2 lines

I might be wrong, but sounds to me like someone intends to feed this to AI to generate tests or code.

Absolutely not the intent. This is about the lossy process of converting human ideas to code. Reliably going from code to test requires an understanding of what was lost in translation. This project is about filling that gap.

Thanks for clarifying. I rang my alarm bells too early :)

I saw the LPC talk on this topic:

https://lpc.events/event/19/contributions/2085/

With things like "a test case can be derived from the testable expectation" one wonders how we get from the the doc to an actual test case.

Quoted 8 lines
Quoted 4 lines

Probably it is the term derived that can be a bit misleading. The point is that we need documented expectations that can be used to review and verify the test cases against; so maybe better to say "a test case can be verified against the testable expectation"

On a high level (where we usually test with things like LTP) I would usually expect that the man pages properly describe the semantics of syscalls etc.

On a high level yes however there are two issues:
1) even the Posix standard define the behaviour of certain syscalls as implementation specific
2) if all the details required to write testable specifications were maintained as part of the manpage, these would become unmaintainable

For this reason specification must be broken down over the code in a maintainable way

Quoted 8 lines

That also feels like a better place to maintain such kind of information.

Having that said, man-pages are frequently a bit outdated or imprecise .. or missing.

Anyhow, I guess that will all be discussed in your LPC session I assume, I'll try to attend that one, thanks!

Sure Looking FWD to see you there

Gab

Quoted 6 lines

--
Cheers

David / dhildenb

#11 lore raw

RFC PATCH v2 2/3 /dev/mem: Add initial documentation of memory_open() and mem_fops

In reply to Gabriele Paoloni

This patch proposes initial kernel-doc documentation for memory_open() and most of the functions in the mem_fops structure.
The format used for the specifications follows the guidelines defined in Documentation/doc-guide/code-specifications.rst

---
 drivers/char/mem.c | 231 +++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 225 insertions(+), 6 deletions(-)
drivers/char/mem.c +225 -6
index 48839958b0b1..e69c164e9465 100644
@@ -75,9 +75,54 @@ static inline bool should_stop_iteration(void)
 	return signal_pending(current);
 }
 
-/*
- * This funcion reads the *physical* memory. The f_pos points directly to the
- * memory location.
+/**
+ * read_mem - read from physical memory (/dev/mem).
+ * @file: struct file associated with /dev/mem.
+ * @buf: user-space buffer to copy data to.
+ * @count: number of bytes to read.
+ * @ppos: pointer to the current file position, representing the physical
+ *        address to read from.
+ *
+ * This function checks if the requested physical memory range is valid
+ * and accessible by the user, then it copies data to the input
+ * user-space buffer up to the requested number of bytes.
+ *
+ * Function's expectations:
+ *
+ * 1. This function shall check if the value pointed by ppos exceeds the
+ *    maximum addressable physical address;
+ *
+ * 2. This function shall check if the physical address range to be read
+ *    is valid (i.e. it falls within a memory block and if it can be mapped
+ *    to the kernel address space);
+ *
+ * 3. For each memory page falling in the requested physical range
+ *    [ppos, ppos + count - 1]:
+ *   3.1. this function shall check if user space access is allowed (if
+ *        config STRICT_DEVMEM is not set, access is always granted);
+ *
+ *   3.2. if access is allowed, the memory content from the page range falling
+ *        within the requested physical range shall be copied to the user space
+ *        buffer;
+ *
+ *   3.3. zeros shall be copied to the user space buffer (for the page range
+ *        falling within the requested physical range):
+ *     3.3.1. if access to the memory page is restricted or,
+ *     3.2.2. if the current page is page 0 on HW architectures where page 0 is
+ *            not mapped.
+ *
+ * 4. The file position '*ppos' shall be advanced by the number of bytes
+ *    successfully copied to user space (including zeros).
+ *
+ * Context: process context.
+ *
+ * Return:
+ * * the number of bytes copied to user on success
+ * * %-EFAULT - the requested address range is not valid or a fault happened
+ *   when copying to user-space (i.e. copy_from_kernel_nofault() failed)
+ * * %-EPERM - access to any of the required physical pages is not allowed
+ * * %-ENOMEM - out of memory error for auxiliary kernel buffers supporting
+ *   the operation of copying content from the physical pages
  */
 static ssize_t read_mem(struct file *file, char __user *buf,
 			size_t count, loff_t *ppos)
@@ -166,6 +211,54 @@ static ssize_t read_mem(struct file *file, char __user *buf,
 	return err;
 }
 
+/**
+ * write_mem - write to physical memory (/dev/mem).
+ * @file: struct file associated with /dev/mem.
+ * @buf: user-space buffer containing the data to write.
+ * @count: number of bytes to write.
+ * @ppos: pointer to the current file position, representing the physical
+ *        address to write to.
+ *
+ * This function checks if the target physical memory range is valid
+ * and accessible by the user, then it writes data from the input
+ * user-space buffer up to the requested number of bytes.
+ *
+ * Function's expectations:
+ * 1. This function shall check if the value pointed by ppos exceeds the
+ *    maximum addressable physical address;
+ *
+ * 2. This function shall check if the physical address range to be written
+ *    is valid (i.e. it falls within a memory block and if it can be mapped
+ *    to the kernel address space);
+ *
+ * 3. For each memory page falling in the physical range to be written
+ *    [ppos, ppos + count - 1]:
+ *   3.1. this function shall check if user space access is allowed (if
+ *        config STRICT_DEVMEM is not set, access is always granted);
+ *
+ *   3.2. the content from the user space buffer shall be copied to the page
+ *        range falling within the physical range to be written if access is
+ *        allowed;
+ *
+ *   3.3. the data to be copied from the user space buffer (for the page range
+ *        falling within the range to be written) shall be skipped:
+ *     3.3.1. if access to the memory page is restricted or,
+ *     3.3.2. if the current page is page 0 on HW architectures where page 0
+ *            is not mapped.
+ *
+ * 4. The file position '*ppos' shall be advanced by the number of bytes
+ *    successfully copied from user space (including skipped bytes).
+ *
+ * Context: process context.
+ *
+ * Return:
+ * * the number of bytes copied from user-space on success
+ * * %-EFBIG - the value pointed by ppos exceeds the maximum addressable
+ *   physical address
+ * * %-EFAULT - the physical address range is not valid or no bytes could
+ *   be copied from user-space
+ * * %-EPERM - access to any of the required pages is not allowed
+ */
 static ssize_t write_mem(struct file *file, const char __user *buf,
 			 size_t count, loff_t *ppos)
 {
@@ -322,6 +415,42 @@ static const struct vm_operations_struct mmap_mem_ops = {
 #endif
 };
 
+/**
+ * mmap_mem - map physical memory into user space (/dev/mem).
+ * @file: file structure for the device.
+ * @vma: virtual memory area structure describing the user mapping.
+ *
+ * This function checks if the requested physical memory range is valid
+ * and accessible by the user, then it maps the physical memory range to
+ * user-mode address space.
+ *
+ * Function's expectations:
+ * 1. This function shall check if the requested physical address range to be
+ *    mapped fits within the maximum addressable physical range;
+ *
+ * 2. This function shall check if the requested  physical range corresponds to
+ *    a valid physical range and if access is allowed on it (if config STRICT_DEVMEM
+ *    is not set, access is always allowed);
+ *
+ * 3. This function shall check if the input virtual memory area can be used for
+ *    a private mapping (always OK if there is an MMU);
+ *
+ * 4. This function shall set the virtual memory area operations to
+ *    &mmap_mem_ops;
+ *
+ * 5. This function shall establish a mapping between the user-space
+ *    virtual memory area described by vma and the physical memory
+ *    range specified by vma->vm_pgoff and size;
+ *
+ * Context: process context.
+ *
+ * Return:
+ * * 0 on success
+ * * %-EAGAIN - invalid or unsupported mapping requested (remap_pfn_range()
+ *   fails)
+ * * %-EINVAL - requested physical range to be mapped is not valid
+ * * %-EPERM - no permission to access the requested physical range
+ */
 static int mmap_mem(struct file *file, struct vm_area_struct *vma)
 {
 	size_t size = vma->vm_end - vma->vm_start;
@@ -550,13 +679,47 @@ static loff_t null_lseek(struct file *file, loff_t offset, int orig)
 	return file->f_pos = 0;
 }
 
-/*
+/**
+ * memory_lseek - change the file position.
+ * @file: file structure for the device.
+ * @offset: file offset to seek to.
+ * @orig: where to start seeking from (see whence in the llseek manpage).
+ *
+ * This function changes the file position according to the input offset
+ * and orig parameters.
+ *
+ * Function's expectations:
+ * 1. This function shall lock the semaphore of the inode corresponding to the
+ *    input file before any operation and unlock it before returning.
+ *
+ * 2. This function shall check the orig value and accordingly:
+ *   2.1. if it is equal to SEEK_CUR, the current file position shall be
+ *        incremented by the input offset;
+ *   2.2. if it is equal to SEEK_SET, the current file position shall be
+ *        set to the input offset value;
+ *   2.3. any other value shall result in an error condition.
+ *
+ * 3. Before writing the current file position, the new position value
+ *    shall be checked to not overlap with Linux ERRNO values.
+ *
+ * Assumptions of Use:
+ * 1. the input file pointer is expected to be valid.
+ *
+ * Notes:
  * The memory devices use the full 32/64 bits of the offset, and so we cannot
  * check against negative addresses: they are ok. The return value is weird,
  * though, in that case (0).
  *
- * also note that seeking relative to the "end of file" isn't supported:
- * it has no meaning, so it returns -EINVAL.
+ * Also note that seeking relative to the "end of file" isn't supported:
+ * it has no meaning, so passing orig equal to SEEK_END returns -EINVAL.
+ *
+ * Context: process context, locks/unlocks inode->i_rwsem
+ *
+ * Return:
+ * * the new file position on success
+ * * %-EOVERFLOW - the new position value equals or exceeds
+ *   (unsigned long long) -MAX_ERRNO
+ * * %-EINVAL - the orig parameter is invalid
  */
 static loff_t memory_lseek(struct file *file, loff_t offset, int orig)
 {
@@ -584,6 +747,35 @@ static loff_t memory_lseek(struct file *file, loff_t offset, int orig)
 	return ret;
 }
 
+/**
+ * open_port - open the I/O port device (/dev/port).
+ * @inode: inode of the device file.
+ * @filp: file structure for the device.
+ *
+ * This function checks if the caller can access the port device and sets
+ * the f_mapping pointer of filp to the i_mapping pointer of inode.
+ *
+ * Function's expectations:
+ * 1. This function shall check if the caller has sufficient capabilities to
+ *    perform raw I/O access;
+ *
+ * 2. This function shall check if the kernel is locked down with the
+ *    &LOCKDOWN_DEV_MEM restriction;
+ *
+ * 3. If the input inode corresponds to /dev/mem, the f_mapping pointer
+ *    of the input file structure shall be set to the i_mapping pointer
+ *    of the input inode;
+ *
+ * Assumptions of Use:
+ * 1. The input inode and filp are expected to be valid.
+ *
+ * Context: process context.
+ *
+ * Return:
+ * * 0 on success
+ * * %-EPERM - caller lacks the required capability (CAP_SYS_RAWIO)
+ * * any error returned by securty_locked_down()
+ */
 static int open_port(struct inode *inode, struct file *filp)
 {
 	int rc;
@@ -691,6 +883,33 @@ static const struct memdev {
 #endif
 };
 
+/**
+ * memory_open - set the filp f_op to the memory device fops and invoke open().
+ * @inode: inode of the device file.
+ * @filp: file structure for the device.
+ *
+ * Function's expectations:
+ * 1. This function shall retrieve the minor number associated with the input
+ *   inode and the memory device corresponding to such minor number;
+ *
+ * 2. The file operations pointer shall be set to the memory device file operations;
+ *
+ * 3. The file mode member of the input filp shall be OR'd with the device mode;
+ *
+ * 4. The memory device open() file operation shall be invoked.
+ *
+ * Assumptions of Use:
+ * 1. The input inode and filp are expected to be non-NULL.
+ *
+ * Context: process context.
+ *
+ * Return:
+ * * 0 on success
+ * * %-ENXIO - the minor number corresponding to the input inode cannot be
+ *   associated with any device or the corresponding device has a NULL fops
+ *   pointer
+ * * any error returned by the device specific open function pointer
+ */
 static int memory_open(struct inode *inode, struct file *filp)
 {
 	int minor;
Signature · 1 line
2.48.1
maintainer
#12 lore raw

Re: [RFC v2 PATCH 2/3] /dev/mem: Add initial documentation of memory_open() and mem_fops

Quoted 4 lines · Gabriele Paoloni

This patch proposes initial kernel-doc documentation for memory_open() and most of the functions in the mem_fops structure.
The format used for the specifications follows the guidelines defined in Documentation/doc-guide/code-specifications.rst

I'll repeat my obnoxious question from the first patch: what does that buy for us?

Quoted 44 lines
---
 drivers/char/mem.c | 231 +++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 225 insertions(+), 6 deletions(-)
drivers/char/mem.c +28 -3
index 48839958b0b1..e69c164e9465 100644
@@ -75,9 +75,54 @@ static inline bool should_stop_iteration(void)
 	return signal_pending(current);
 }
 
-/*
- * This funcion reads the *physical* memory. The f_pos points directly to the
- * memory location.
+/**
+ * read_mem - read from physical memory (/dev/mem).
+ * @file: struct file associated with /dev/mem.
+ * @buf: user-space buffer to copy data to.
+ * @count: number of bytes to read.
+ * @ppos: pointer to the current file position, representing the physical
+ *        address to read from.
+ *
+ * This function checks if the requested physical memory range is valid
+ * and accessible by the user, then it copies data to the input
+ * user-space buffer up to the requested number of bytes.
+ *
+ * Function's expectations:
+ *
+ * 1. This function shall check if the value pointed by ppos exceeds the
+ *    maximum addressable physical address;
+ *
+ * 2. This function shall check if the physical address range to be read
+ *    is valid (i.e. it falls within a memory block and if it can be mapped
+ *    to the kernel address space);
+ *
+ * 3. For each memory page falling in the requested physical range
+ *    [ppos, ppos + count - 1]:
+ *   3.1. this function shall check if user space access is allowed (if
+ *        config STRICT_DEVMEM is not set, access is always granted);
+ *
+ *   3.2. if access is allowed, the memory content from the page range falling
+ *        within the requested physical range shall be copied to the user space

drivers/char/mem.c static inline bool should_stop_iteration(void) · line 115

Quoted 10 lines
drivers/char/mem.c +10 -0
+ *        buffer;
+ *
+ *   3.3. zeros shall be copied to the user space buffer (for the page range
+ *        falling within the requested physical range):
+ *     3.3.1. if access to the memory page is restricted or,
+ *     3.2.2. if the current page is page 0 on HW architectures where page 0 is
+ *            not mapped.
+ *
+ * 4. The file position '*ppos' shall be advanced by the number of bytes
+ *    successfully copied to user space (including zeros).

My kneejerk first reaction is: you are repeating the code of the function in a different language. If we are not convinced that the code is correct, how can we be more confident that this set of specifications is correct? And again, what will consume this text? How does going through this effort get us to a better kernel?

Despite having been to a couple of your talks, I'm not fully understanding how this comes together; people who haven't been to the talks are not going to have an easier time getting the full picture.

Thanks,

jon

#13 lore raw

Re: [RFC v2 PATCH 2/3] /dev/mem: Add initial documentation of memory_open() and mem_fops

Quoted 9 lines · Jonathan Corbet
Quoted 4 lines · Gabriele Paoloni

This patch proposes initial kernel-doc documentation for memory_open() and most of the functions in the mem_fops structure. The format used for the specifications follows the guidelines defined in Documentation/doc-guide/code-specifications.rst

I'll repeat my obnoxious question from the first patch: what does that buy for us?

Fair question, and definitely not obnoxious.

It might help to reframe this a bit. The idea is to take an engineering technique from one domain and apply it with modifications to another. The relevant terms of art are "forward engineering" and "reverse engineering".

Quoted 2 lines

My kneejerk first reaction is: you are repeating the code of the function in a different language.

No disagreement on that perception. We have more work to do when it comes to communicating the idea, as well as developing a better implementation.

The design of the Linux kernel is emergent and, in the present state, all forms of testing are an (educated) guess at the intended design. We can demonstrate this by picking a random bit of code from the kernel and assigning ourselves the task of writing a test for it.

Are you certain that your test accurately reflects the true design intent? You can read the code and test what you see. But that does not mean that your test is valid against the intent in someone else's head.

Music instructors see this whenever their students play the right notes but clearly do not yet "feel" the music. The difference is noticeable even by casual listeners.

Quoted 2 lines

If we are not convinced that the code is correct, how can we be more confident that this set of specifications is correct?

We have no reason to be independently convinced of either. When we describe this as importing a technique into a new domain, your question is an example of some of the concessions that have to be made.

The Linux kernel is not a forward engineered system. Therefore it is not possible to develop code and test from the same seed. Our only option is to reverse engineer that seed to the best of our abilities.

At that point we have a few options.

Ideally, the original developer can weigh in and validate that our interpretation is correct. This has the effect of "simulating" a forward engineering scenario, because a test can be created from the validated seed (I am trying valiantly to avoid using the word kernel).

Absent the original developer's validation, we have the option of simply asserting the specification. This is equivalent to the way testing is done today, except a test can be equally opaque with respect to what design it is attempting to validate.

In either case, if a test is developed against the specification, even an initially incorrect specification, we have the ability to bring code, specification, and test into alignment over time.

Quoted 1 line

And again, what will consume this text?

Humans are the consumer. But to be clear - a machine readable template is going to be required in the long run to ensure that code and specification remain aligned. Our intentent was to avoid confusing things with templates, and introduce them once we have made headway on the points you have brought up.

It is probably also worth mentioning, we have already had an "a-ha" moment from one kernel maintainer. I believe the words were something to the effect of, "this is great, I used to have to relearn that code every time I touch it".

Quoted 1 line

How does going through this effort get us to a better kernel?

I am hoping some of the above planted the seed to answer this one. Code must be correct in two ways, it must be valid and it must be verified.

Valid means - the code is doing the right thing. Verified means - the code is doing the thing right.

If code and test accurately reflect the same idea, then we can alleviate maintainers of a large portion of the verification burden. Validation is in the "hearts and minds" of the users, so that burden never goes away.

Quoted 3 lines

Despite having been to a couple of your talks, I'm not fully understanding how this comes together; people who haven't been to the talks are not going to have an easier time getting the full picture.

I agree. And thank you very much for attending those talks and engaging with us. It truly means a lot.

I have submitted a refereed talk to this year's Pumbers conference that is intended to go over these points in detail. My colleague (not on this thread) has also submitted a refereed talk on best practices for developing these specifications. His name is Matthew Whitehead and he is a recognized expert in that area.

..Ch:W..

#14 lore raw

Re: [RFC v2 PATCH 2/3] /dev/mem: Add initial documentation of memory_open() and mem_fops

In reply to Jonathan Corbet

Hi Jonathan

Quoted 10 lines · Jonathan Corbet
Quoted 4 lines · Gabriele Paoloni

This patch proposes initial kernel-doc documentation for memory_open() and most of the functions in the mem_fops structure.
The format used for the specifications follows the guidelines defined in Documentation/doc-guide/code-specifications.rst

I'll repeat my obnoxious question from the first patch: what does that buy for us?

I tried to explain my reply on patch 1

Quoted 53 lines
Quoted 53 lines
---
 drivers/char/mem.c | 231 +++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 225 insertions(+), 6 deletions(-)
drivers/char/mem.c +36 -3
index 48839958b0b1..e69c164e9465 100644
@@ -75,9 +75,54 @@ static inline bool should_stop_iteration(void)
      return signal_pending(current);
 }
 
-/*
- * This funcion reads the *physical* memory. The f_pos points directly to the
- * memory location.
+/**
+ * read_mem - read from physical memory (/dev/mem).
+ * @file: struct file associated with /dev/mem.
+ * @buf: user-space buffer to copy data to.
+ * @count: number of bytes to read.
+ * @ppos: pointer to the current file position, representing the physical
+ *        address to read from.
+ *
+ * This function checks if the requested physical memory range is valid
+ * and accessible by the user, then it copies data to the input
+ * user-space buffer up to the requested number of bytes.
+ *
+ * Function's expectations:
+ *
+ * 1. This function shall check if the value pointed by ppos exceeds the
+ *    maximum addressable physical address;
+ *
+ * 2. This function shall check if the physical address range to be read
+ *    is valid (i.e. it falls within a memory block and if it can be mapped
+ *    to the kernel address space);
+ *
+ * 3. For each memory page falling in the requested physical range
+ *    [ppos, ppos + count - 1]:
+ *   3.1. this function shall check if user space access is allowed (if
+ *        config STRICT_DEVMEM is not set, access is always granted);
+ *
+ *   3.2. if access is allowed, the memory content from the page range falling
+ *        within the requested physical range shall be copied to the user space
+ *        buffer;
+ *
+ *   3.3. zeros shall be copied to the user space buffer (for the page range
+ *        falling within the requested physical range):
+ *     3.3.1. if access to the memory page is restricted or,
+ *     3.2.2. if the current page is page 0 on HW architectures where page 0 is
+ *            not mapped.
+ *
Quoted 8 lines

drivers/char/mem.c static inline bool should_stop_iteration(void) · line 115

Quoted 2 lines
drivers/char/mem.c +2 -0
+ * 4. The file position '*ppos' shall be advanced by the number of bytes
+ *    successfully copied to user space (including zeros).

My kneejerk first reaction is: you are repeating the code of the function in a different language. If we are not convinced that the code is correct, how can we be more confident that this set of specifications is correct? And again, what will consume this text? How does going through this effort get us to a better kernel?

In summary specifications provide the criteria to be used in verifying the code (both when reviewing and testing).
Otherwise:
1) Developers and reviewers have no criteria to evaluate the code, other than their expertise and judgement when they read it;
2) Testers would write test cases based on the code itself (so it is more likely that a wrong code is not detected due to wrong test cases).

WRT your first point, if specifications are wrong, a reviewer or a test would detect a gap between code and associated specs, hence leading to process of scrutiny of both code and specs where such a gap must be resolved. This is the reason why the duality of specification and tests VS the code being verified lead to confidence in code becoming more dependable (also from a user point of view that can now clearly see the assumptions to be met when invoking the code)

Thanks
Gab

Quoted 9 lines

Despite having been to a couple of your talks, I'm not fully understanding how this comes together; people who haven't been to the talks are not going to have an easier time getting the full picture.

Thanks,

jon

#15 lore raw

RFC PATCH v2 3/3 selftests/devmem: initial testset

In reply to Gabriele Paoloni

From: Alessandro Carminati <[email protected]>

This patch introduces a new series of tests for devmem. Test cases are mapped against the tested Function's expectations defined in /drivers/char/mem.c.

---
 tools/testing/selftests/Makefile         |   1 +
 tools/testing/selftests/devmem/Makefile  |  13 +
 tools/testing/selftests/devmem/debug.c   |  25 +
 tools/testing/selftests/devmem/debug.h   |  14 +
 tools/testing/selftests/devmem/devmem.c  | 200 ++++++++
 tools/testing/selftests/devmem/ram_map.c | 250 ++++++++++
 tools/testing/selftests/devmem/ram_map.h |  38 ++
 tools/testing/selftests/devmem/secret.c  |  46 ++
 tools/testing/selftests/devmem/secret.h  |  13 +
 tools/testing/selftests/devmem/tests.c   | 569 +++++++++++++++++++++++
 tools/testing/selftests/devmem/tests.h   |  45 ++
 tools/testing/selftests/devmem/utils.c   | 379 +++++++++++++++
 tools/testing/selftests/devmem/utils.h   | 119 +++++
 13 files changed, 1712 insertions(+)
 create mode 100644 tools/testing/selftests/devmem/Makefile
 create mode 100644 tools/testing/selftests/devmem/debug.c
 create mode 100644 tools/testing/selftests/devmem/debug.h
 create mode 100644 tools/testing/selftests/devmem/devmem.c
 create mode 100644 tools/testing/selftests/devmem/ram_map.c
 create mode 100644 tools/testing/selftests/devmem/ram_map.h
 create mode 100644 tools/testing/selftests/devmem/secret.c
 create mode 100644 tools/testing/selftests/devmem/secret.h
 create mode 100644 tools/testing/selftests/devmem/tests.c
 create mode 100644 tools/testing/selftests/devmem/tests.h
 create mode 100644 tools/testing/selftests/devmem/utils.c
 create mode 100644 tools/testing/selftests/devmem/utils.h
tools/testing/selftests/Makefile +1 -0
index 030da61dbff3..55d228572e37 100644
@@ -16,6 +16,7 @@ TARGETS += cpu-hotplug
 TARGETS += damon
 TARGETS += devices/error_logs
 TARGETS += devices/probe
+TARGETS += devmem/devmem
 TARGETS += dmabuf-heaps
 TARGETS += drivers/dma-buf
 TARGETS += drivers/ntsync
tools/testing/selftests/devmem/Makefile new file +13 -0
new file mode 100644
index 000000000000..8aca8cbe2957
@@ -0,0 +1,13 @@
+# SPDX-License-Identifier: GPL-2.0
+# Kselftest Makefile for devmem test
+
+CFLAGS += -Wall -O2
+
+TEST_GEN_PROGS_EXTENDED := devmem
+
+$(OUTPUT)/devmem: devmem.c $(OUTPUT)/ram_map.o $(OUTPUT)/secret.o  $(OUTPUT)/tests.o $(OUTPUT)/utils.o $(OUTPUT)/debug.o
+	$(CC) $^ -o $@ $(CFLAGS)
+
+EXTRA_CLEAN += $(OUTPUT)/ram_map.o $(OUTPUT)/secret.o  $(OUTPUT)/tests.o $(OUTPUT)/utils.o $(OUTPUT)/debug.o
+
+include ../lib.mk
tools/testing/selftests/devmem/debug.c new file +25 -0
new file mode 100644
index 000000000000..db88a760414d
@@ -0,0 +1,25 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * devmem test debug.c
+ *
+ * Copyright (C) 2025 Red Hat, Inc. All Rights Reserved.
+ * Written by Alessandro Carminati ([email protected])
+ */
+
+#include <stdio.h>
+#include <stdarg.h>
+
+#define DEBUG_FLAG 0
+int pdebug = DEBUG_FLAG;
+
+void deb_printf(const char *fmt, ...)
+{
+	va_list args;
+
+	if (pdebug) {
+		va_start(args, fmt);
+		vprintf(fmt, args);
+		va_end(args);
+	}
+}
+
tools/testing/selftests/devmem/debug.h new file +14 -0
new file mode 100644
index 000000000000..323f44b94aaa
@@ -0,0 +1,14 @@
+/* SPDX-License-Identifier: GPL-2.0+ */
+/*
+ * devmem test debug.h
+ *
+ * Copyright (C) 2025 Red Hat, Inc. All Rights Reserved.
+ * Written by Alessandro Carminati ([email protected])
+ */
+
+#ifndef DEBUG_H
+#define DEBUG_H
+extern int pdebug;
+void deb_printf(const char *fmt, ...);
+#endif
+
tools/testing/selftests/devmem/devmem.c new file +200 -0

200 lines not on this page · raw message

tools/testing/selftests/devmem/ram_map.c new file +250 -0

250 lines not on this page · raw message

tools/testing/selftests/devmem/ram_map.h new file +38 -0
new file mode 100644
index 000000000000..8b1bd976b0b9
@@ -0,0 +1,38 @@
+/* SPDX-License-Identifier: GPL-2.0+ */
+/* devmem test ram_map.h
+ *
+ * Copyright (C) 2025 Red Hat, Inc. All Rights Reserved.
+ * Written by Alessandro Carminati ([email protected])
+ */
+
+#ifndef RAM_MAP_H
+#define RAM_MAP_H
+
+#define _GNU_SOURCE
+#define SAFE_OFFSET (512ULL * 1024ULL)
+#define LOW_MEM_LIMIT 0x100000ULL
+#define LEGACY_MEM_START 0x10000
+
+struct ram_region {
+	uint64_t start;
+	uint64_t end;
+	char *name;
+};
+
+struct ram_map {
+	struct ram_region *regions;
+	size_t count;
+};
+
+uint64_t get_highest_ram_addr(const struct ram_map *map);
+struct ram_map *parse_iomem(void);
+void free_ram_map(struct ram_map *map);
+uint64_t find_last_linear_byte(int fd, uint64_t low_start, uint64_t max_addr);
+void dump_ram_map(const struct ram_map *map);
+void report_physical_memory(const struct ram_map *map);
+uint64_t find_high_system_ram_addr(const struct ram_map *map);
+uint64_t pick_restricted_address(const struct ram_map *map);
+uint64_t pick_outside_address(const struct ram_map *map);
+uint64_t pick_valid_ram_address(const struct ram_map *map);
+
+#endif
tools/testing/selftests/devmem/secret.c new file +46 -0

46 lines not on this page · raw message

tools/testing/selftests/devmem/secret.h new file +13 -0
new file mode 100644
index 000000000000..07d263fc05e3
@@ -0,0 +1,13 @@
+/* SPDX-License-Identifier: GPL-2.0+ */
+/* devmem test secret.h
+ *
+ * Copyright (C) 2025 Red Hat, Inc. All Rights Reserved.
+ * Written by Alessandro Carminati ([email protected])
+ */
+
+#ifndef SECRET_H
+#define SECRET_H
+
+void *secret_alloc(size_t size);
+void secret_free(void *p, size_t size);
+#endif
tools/testing/selftests/devmem/tests.c new file +569 -0

569 lines not on this page · raw message

tools/testing/selftests/devmem/tests.h new file +45 -0

45 lines not on this page · raw message

tools/testing/selftests/devmem/utils.c new file +379 -0

379 lines not on this page · raw message

tools/testing/selftests/devmem/utils.h new file +119 -0

119 lines not on this page · raw message

Signature · 1 line
2.48.1
maintainer
#16 lore raw

Re: [RFC v2 PATCH 3/3] selftests/devmem: initial testset

Quoted 5 lines · Gabriele Paoloni

From: Alessandro Carminati <[email protected]>

This patch introduces a new series of tests for devmem. Test cases are mapped against the tested Function's expectations defined in /drivers/char/mem.c.

Cool, but:

Quoted 16 lines
---
 tools/testing/selftests/Makefile         |   1 +
 tools/testing/selftests/devmem/Makefile  |  13 +
 tools/testing/selftests/devmem/debug.c   |  25 +
 tools/testing/selftests/devmem/debug.h   |  14 +
 tools/testing/selftests/devmem/devmem.c  | 200 ++++++++
 tools/testing/selftests/devmem/ram_map.c | 250 ++++++++++
 tools/testing/selftests/devmem/ram_map.h |  38 ++
 tools/testing/selftests/devmem/secret.c  |  46 ++
 tools/testing/selftests/devmem/secret.h  |  13 +
 tools/testing/selftests/devmem/tests.c   | 569 +++++++++++++++++++++++
 tools/testing/selftests/devmem/tests.h   |  45 ++
 tools/testing/selftests/devmem/utils.c   | 379 +++++++++++++++
 tools/testing/selftests/devmem/utils.h   | 119 +++++

That's a lot of files for a "simple" test. Doesn't LTP have tests for this api already? Why not use that here instead?

Also, this is userspace testing, not kunit testing, right, is that intentional? You are documenting internal apis and then writing userspace tests for those apis, which feels a bit odd.

Also /dev/mem should not be used on "modern" systems, so how was this tested?

Quoted 1 line

+// SPDX-License-Identifier: GPL-2.0+

Are you _sure_ you want GPLv2+? I have to ask, sorry.

tools/testing/selftests/devmem/debug.c line 13

Quoted 12 lines
tools/testing/selftests/devmem/debug.c new file +12 -0
+/*
+ * devmem test debug.c
+ *
+ * Copyright (C) 2025 Red Hat, Inc. All Rights Reserved.
+ * Written by Alessandro Carminati ([email protected])
+ */
+
+#include <stdio.h>
+#include <stdarg.h>
+
+#define DEBUG_FLAG 0
+int pdebug = DEBUG_FLAG;

That's a funny define that is never used elsewhere. I'm guessing this was cut/pasted from some other userspace code somewhere?

Review

Quoted 2 lines
(quoted diff) +2 -0
+
+void deb_printf(const char *fmt, ...)

Who is "deb"? You have more letters, always use them :)

Also, why debugging for just this one set of tests? Don't kselftests already have debugging logic? if not, why is this unique to require it?

And am I missing something, or does this new tool not tie into the kselftest framework properly? I see lots of printing to output, but not in the proper test framework format, am I just missing that somewhere?

thanks,

greg k-h

#17 lore raw

Re: [RFC v2 PATCH 3/3] selftests/devmem: initial testset

Hi Greg,

Quoted 27 lines · Greg KH
Quoted 5 lines · Gabriele Paoloni

From: Alessandro Carminati <[email protected]>

This patch introduces a new series of tests for devmem. Test cases are mapped against the tested Function's expectations defined in /drivers/char/mem.c.

Cool, but:

Quoted 16 lines
---
 tools/testing/selftests/Makefile         |   1 +
 tools/testing/selftests/devmem/Makefile  |  13 +
 tools/testing/selftests/devmem/debug.c   |  25 +
 tools/testing/selftests/devmem/debug.h   |  14 +
 tools/testing/selftests/devmem/devmem.c  | 200 ++++++++
 tools/testing/selftests/devmem/ram_map.c | 250 ++++++++++
 tools/testing/selftests/devmem/ram_map.h |  38 ++
 tools/testing/selftests/devmem/secret.c  |  46 ++
 tools/testing/selftests/devmem/secret.h  |  13 +
 tools/testing/selftests/devmem/tests.c   | 569 +++++++++++++++++++++++
 tools/testing/selftests/devmem/tests.h   |  45 ++
 tools/testing/selftests/devmem/utils.c   | 379 +++++++++++++++
 tools/testing/selftests/devmem/utils.h   | 119 +++++
Quoted 2 lines

That's a lot of files for a "simple" test. Doesn't LTP have tests for this api already? Why not use that here instead?

Indeed, at first glance the test may look simple.
However, despite the high-level concept being straightforward, there are several corner cases and peculiar aspects that needed to be covered, that’s why the test grew larger than expected.
For this RFC, my intent was mainly to share the full picture of what I had in mind.
I fully agree that it can be refined and streamlined in the next iterations. When I started working on this, I wasn’t aware of any existing LTP tests for this interface.
After your comment, I double-checked, but I couldn’t find any relevant coverage. As far as I can tell, neither LTP nor the upstream kernel selftests (kselftest or KUnit) currently include tests specifically targeting /dev/mem.

Quoted 4 lines

Also, this is userspace testing, not kunit testing, right, is that intentional? You are documenting internal apis and then writing userspace tests for those apis, which feels a bit odd.

Yes, that’s intentional.
The main reason is that all the interactions happen from userspace, and the internal helper functions aren’t meant to be consumed by other kernel components.
So I chose a kselftest-style approach.
That said, this is still an RFC, I’m happy to adapt it based on community feedback and direction.

Quoted 3 lines

Also /dev/mem should not be used on "modern" systems, so how was this tested?

That’s indeed one of the nuances I mentioned earlier. Access to /dev/mem is often restricted for security reasons, so the test is designed to detect and adapt to the environment, only performing operations that are actually allowed.

Quoted 4 lines
Quoted 2 lines

+// SPDX-License-Identifier: GPL-2.0+

Are you _sure_ you want GPLv2+? I have to ask, sorry.

Yes, I used GPLv2+ deliberately, but I’m open to changing it if the consensus is that GPLv2-only is more appropriate here.

Quoted 16 lines

tools/testing/selftests/devmem/debug.c line 13

Quoted 13 lines
tools/testing/selftests/devmem/debug.c new file +12 -0
+/*
+ * devmem test debug.c
+ *
+ * Copyright (C) 2025 Red Hat, Inc. All Rights Reserved.
+ * Written by Alessandro Carminati ([email protected])
+ */
+
+#include <stdio.h>
+#include <stdarg.h>
+
+#define DEBUG_FLAG 0
+int pdebug = DEBUG_FLAG;

That's a funny define that is never used elsewhere. I'm guessing this was cut/pasted from some other userspace code somewhere?

It wasn’t copied, but I agree it looks unnecessary in its current form. I can remove or rework it in the next version.

Quoted 6 lines

Review

Quoted 3 lines
(quoted diff) +2 -0
+
+void deb_printf(const char *fmt, ...)

Who is "deb"? You have more letters, always use them :)

Quoted 6 lines

Also, why debugging for just this one set of tests? Don't kselftests already have debugging logic? if not, why is this unique to require it?

And am I missing something, or does this new tool not tie into the kselftest framework properly? I see lots of printing to output, but not in the proper test framework format, am I just missing that somewhere?

You’re right, this was a small custom debug I left in place, mainly because I needed a way to include additional information that isn’t normally part of the standard selftest output, such as references to specific requirements in the code.
My intent was to make it easier to correlate test results with those requirements.
That said, I fully agree that the implementation isn’t aligned with the kselftest framework style, and I’ll look into integrating this need in a more standardized and consistent way in the next iteration.

Quoted 5 lines

thanks,

greg k-h

Thanks a lot for the detailed feedback, it’s very helpful. I’ll revise the test accordingly for the next round.

Best regards,
Alessandro

--
---
172

maintainer
#18 lore raw
In reply to Gabriele Paoloni
Quoted 11 lines · Gabriele Paoloni

[1] was an initial proposal defining testable code specifications for some functions in /drivers/char/mem.c.
However a Guideline to write such specifications was missing and test cases tracing to such specifications were missing.
This patchset represents a next step and is organised as follows:
- patch 1/3 contains the Guideline for writing code specifications
- patch 2/3 contains examples of code specfications defined for some functions of drivers/char/mem.c
- patch 3/3 contains examples of selftests that map to some code specifications of patch 2/3

Quoted 1 line

[1] https://lore.kernel.org/all/[email protected]/

"RFC" implies there is a request. I don't see that here, am I missing that? Or is this "good to go" and want us to seriously consider accepting this?

thanks,

greg k-h

#19 lore raw

Hi Greg

Quoted 13 lines · Greg KH
Quoted 11 lines · Gabriele Paoloni

[1] was an initial proposal defining testable code specifications for some functions in /drivers/char/mem.c.
However a Guideline to write such specifications was missing and test cases tracing to such specifications were missing.
This patchset represents a next step and is organised as follows:
- patch 1/3 contains the Guideline for writing code specifications
- patch 2/3 contains examples of code specfications defined for some functions of drivers/char/mem.c
- patch 3/3 contains examples of selftests that map to some code specifications of patch 2/3

Quoted 5 lines
Quoted 1 line

[1] https://lore.kernel.org/all/[email protected]/

"RFC" implies there is a request. I don't see that here, am I missing that? Or is this "good to go" and want us to seriously consider accepting this?

I assumed that an RFC (as in request for comments) that comes with proposed changes to upstream files would be interpreted as a request for feedbacks associated with the proposed changes (what is wrong or what is missing); next time I will communicate the request explicitly.

WRT this specific patchset, the intent is to introduce formalism in specifying code behavior (so that the same formalism can also be used to write and review test cases), so my high level asks would be:

1) In the first part of patch 1/3 we explain why we are doing this and the high level goals. Do you agree with these? Are these clear?

2) In the rest of the patchset we introduce the formalism, we propose some specs (in patch 2) and associated selftests (in patch 3). Please let us know if there is something wrong, missing or to be improved.

Thanks and kind regards
Gab

Quoted 5 lines

thanks,

greg k-h

maintainer
#20 lore raw
Quoted 27 lines · Gabriele Paoloni

Hi Greg

Quoted 13 lines · Greg KH
Quoted 11 lines · Gabriele Paoloni

[1] was an initial proposal defining testable code specifications for some functions in /drivers/char/mem.c.
However a Guideline to write such specifications was missing and test cases tracing to such specifications were missing.
This patchset represents a next step and is organised as follows:
- patch 1/3 contains the Guideline for writing code specifications
- patch 2/3 contains examples of code specfications defined for some functions of drivers/char/mem.c
- patch 3/3 contains examples of selftests that map to some code specifications of patch 2/3

Quoted 5 lines
Quoted 1 line

[1] https://lore.kernel.org/all/[email protected]/

"RFC" implies there is a request. I don't see that here, am I missing that? Or is this "good to go" and want us to seriously consider accepting this?

I assumed that an RFC (as in request for comments) that comes with proposed changes to upstream files would be interpreted as a request for feedbacks associated with the proposed changes (what is wrong or what is missing); next time I will communicate the request explicitly.

Quoted 6 lines

WRT this specific patchset, the intent is to introduce formalism in specifying code behavior (so that the same formalism can also be used to write and review test cases), so my high level asks would be:

1) In the first part of patch 1/3 we explain why we are doing this and the high level goals. Do you agree with these? Are these clear?

No, and no.

I think this type of thing is, sadly, folly. You are entering into a path that never ends with no clear goal that you are conveying here to us.

I might be totally wrong, but I fail to see what you want to have happen in the end.

Every in-kernel api documented in a "formal" way like this? Or a subset? If a subset, which ones specifically? How many? And who is going to do that? And who is going to maintain it? And most importantly, why is it needed at all?

For some reason Linux has succeeded in pretty much every place an operating system is needed for cpus that it can run on (zephyr for those others that it can not.) So why are we suddenly now, after many decades, requiring basic user/kernel stuff to be formally documented like this?

In the past, when we have had "validating bodies" ask for stuff like this, the solution is to provide it in a big thick book, outside of the kernel, by the company that wishes to sell such a product to that organization to justify the cost of doing that labor. In every instance that I know of, that book sits on a shelf and gathers dust, while Linux is just updated over the years in those sites to new versions and the book goes quickly out of date as no one really cares about it, except it having been a check-box for a purchase order requirement.

That's business craziness, no need to get us involved in all of that. Heck, look at the stuff around FIPS certification for more insanity. That's a check-box that is required by organizations and then totally ignored and never actually run at all by the user. I feel this is much the same.

So step back, and tell us exactly what files and functions and apis are needed to be documented in this stilted and formal way, who exactly is going to be doing all of that work, and why we should even consider reviewing and accepting and most importantly, maintaining such a thing for the next 40+ years.

Quoted 3 lines

2) In the rest of the patchset we introduce the formalism, we propose some specs (in patch 2) and associated selftests (in patch 3). Please let us know if there is something wrong, missing or to be improved.

I made many comments on patch 3, the most important one being that the tests created do not seem to follow any of the standards we have for Linux kernel tests for no documented reason.

The irony of submitting tests for formal specifications that do not follow documented policies is rich :)

thanks,

greg k-h

#21 lore raw

Hi Greg

Quoted 50 lines · Greg KH
Quoted 27 lines · Gabriele Paoloni

Hi Greg

Quoted 13 lines · Greg KH
Quoted 11 lines · Gabriele Paoloni

[1] was an initial proposal defining testable code specifications for some functions in /drivers/char/mem.c.
However a Guideline to write such specifications was missing and test cases tracing to such specifications were missing.
This patchset represents a next step and is organised as follows:
- patch 1/3 contains the Guideline for writing code specifications
- patch 2/3 contains examples of code specfications defined for some functions of drivers/char/mem.c
- patch 3/3 contains examples of selftests that map to some code specifications of patch 2/3

Quoted 5 lines
Quoted 1 line

[1] https://lore.kernel.org/all/[email protected]/

"RFC" implies there is a request. I don't see that here, am I missing that? Or is this "good to go" and want us to seriously consider accepting this?

I assumed that an RFC (as in request for comments) that comes with proposed changes to upstream files would be interpreted as a request for feedbacks associated with the proposed changes (what is wrong or what is missing); next time I will communicate the request explicitly.

Quoted 6 lines

WRT this specific patchset, the intent is to introduce formalism in specifying code behavior (so that the same formalism can also be used to write and review test cases), so my high level asks would be:

1) In the first part of patch 1/3 we explain why we are doing this and the high level goals. Do you agree with these? Are these clear?

No, and no.

I think this type of thing is, sadly, folly. You are entering into a path that never ends with no clear goal that you are conveying here to us.

I might be totally wrong, but I fail to see what you want to have happen in the end.

Every in-kernel api documented in a "formal" way like this? Or a subset? If a subset, which ones specifically? How many? And who is going to do that? And who is going to maintain it? And most importantly, why is it needed at all?

Quoted 5 lines

For some reason Linux has succeeded in pretty much every place an operating system is needed for cpus that it can run on (zephyr for those others that it can not.) So why are we suddenly now, after many decades, requiring basic user/kernel stuff to be formally documented like this?

Let me try to answer starting from the "why".
IMO There are 2 aspects to consider.
The first one is that requirements/specification and associated tests are valuable in claiming that Linux can be used in safety critical industries (like automotive or aerospace).
The second one (that goes beyond the business need) is that the duality of specifications and tests VS code increases the dependability of the code itself so that its expected behaviour and associated constraints are clear to the user and there is evidence of the code behaving as specified (I already tried to address this point in [1]).
Some evidence of improvements can be found in the experiments we did. E.g.:
- this [2] is a bug found in __ftrace_event_enable_disable()
- this [3] is a code optimization that came as we looked at the specifications of
__ftrace_event_enable_disable()
- here [4] we have documented assumptions of use that must be met when invoking event_enable_read(), otherwise there could be a wrong event status being reported to the user.

Finally the need for having specifications/requirements associated with Kernel code has been already discussed at LPC'24 last year ([5]) and we got a thumb up from some key maintainers with initial directions (hence we started this activity).

[1] https://lore.kernel.org/all/CA+wEVJatTLKt-3HxyExtXf4M+fmD6pXcmmCuhd+3-n2J_2Tw8A@mail.gmail.com/
[2] https://lore.kernel.org/all/[email protected]/
[3] https://lore.kernel.org/all/[email protected]/
[4] https://lore.kernel.org/all/[email protected]/
[5] https://lpc.events/event/18/contributions/1894/

Now I'll try to answer about the goals.
I do not expect to have all Kernel APIs to be specified according to the format that we are proposing; my initial goal is to have such a formalism to be available in the Kernel so that developers that need to write such specifications have a guideline available. For example today we have a guideline to write kernel-doc comments, however (AFAIK) patch acceptance is not gated by these being present or not.
I think that developers having a direct interest can write such specifications and associated tests and these could be reviewed and eventually accepted by maintainers.

Quoted 9 lines

In the past, when we have had "validating bodies" ask for stuff like this, the solution is to provide it in a big thick book, outside of the kernel, by the company that wishes to sell such a product to that organization to justify the cost of doing that labor. In every instance that I know of, that book sits on a shelf and gathers dust, while Linux is just updated over the years in those sites to new versions and the book goes quickly out of date as no one really cares about it, except it having been a check-box for a purchase order requirement.

I agree and in fact a key ask from maintainers, as we discussed at LPC'24 in [5], was to have the code specifications sitting next to the code so that they could be maintainable as the code evolves (and they would be even more maintainable if specs come with tests that can flag regressions as the code evolves).

Quoted 7 lines

That's business craziness, no need to get us involved in all of that. Heck, look at the stuff around FIPS certification for more insanity. That's a check-box that is required by organizations and then totally ignored and never actually run at all by the user. I feel this is much the same.

Quoted 5 lines

So step back, and tell us exactly what files and functions and apis are needed to be documented in this stilted and formal way, who exactly is going to be doing all of that work, and why we should even consider reviewing and accepting and most importantly, maintaining such a thing for the next 40+ years.

Putting business needs aside, I would expect maintainers, today, to happily accept kernel-doc compliant code documentation as well as kunit or selftests associated with the code; simply because they add technical value.
If my assumption here is correct, having these kernel-doc specifications clearly formalised should be an improvement for the maintainers (since it would be easier to verify incoming patches when specs and tests are in place and also it would be easier for a developer to write such patches).

WRT the scope of code to be documented, I expect that to depend on the vested interest of companies contributing to it.
The directions from the LPC24 session were to start with some pilot drivers/subsystems first to define 'how' to specify the code and later focus on what and scale...

Quoted 11 lines
Quoted 4 lines

2) In the rest of the patchset we introduce the formalism, we propose some specs (in patch 2) and associated selftests (in patch 3). Please let us know if there is something wrong, missing or to be improved.

I made many comments on patch 3, the most important one being that the tests created do not seem to follow any of the standards we have for Linux kernel tests for no documented reason.

The irony of submitting tests for formal specifications that do not follow documented policies is rich :)

Thanks for your comments and sorry for the mistakes, I see that Alessandro replied so we'll pay more attention in writing tests in the next revision.

Kind Regards
Gab

Quoted 5 lines

thanks,

greg k-h

maintainer
#22 lore raw
Quoted 5 lines · Gabriele Paoloni
Quoted 5 lines

Every in-kernel api documented in a "formal" way like this? Or a subset? If a subset, which ones specifically? How many? And who is going to do that? And who is going to maintain it? And most importantly, why is it needed at all?

Quoted 7 lines
Quoted 5 lines

For some reason Linux has succeeded in pretty much every place an operating system is needed for cpus that it can run on (zephyr for those others that it can not.) So why are we suddenly now, after many decades, requiring basic user/kernel stuff to be formally documented like this?

Let me try to answer starting from the "why".

Let's ignore the "why" for now, and get to the "how" and "what" which you skipped from my questions above.

_Exactly_ how many in-kernel functions are you claiming is needed to be documented in this type of way before Linux would become "acceptable" to these regulatory agencies, and which ones _specifically_ are they?

Without knowing that, we could argue about the format all day long, and yet have nothing to show for it.

And then, I have to ask, exactly "who" is going to do that work.

I'll point at another "you must do this for reasons" type of request we have had in the past, SPDX. Sadly that task was never actually finished as it looks like no one really cared to do the real work involved. We got other benefits out of that effort, but the "goal" that people started that effort with was never met. Part of that is me not pushing back hard enough on the "who is going to do the work" part of that question, which is important in stuff like this.

If you never complete the effort, your end goal of passing Linux off to those customers will never happen.

So, try to answer that, with lots and lots of specifics, and then, if we agree that it is a sane thing to attempt (i.e. you are going to do all the work and it actually would be possible to complete), then we can argue about the format of the text :)

thanks,

greg k-h

#23 lore raw
Quoted 6 lines · Greg KH
Quoted 4 lines · Gabriele Paoloni
Quoted 4 lines

Every in-kernel api documented in a "formal" way like this? Or a subset? If a subset, which ones specifically? How many? And who is going to do that? And who is going to maintain it? And most importantly, why is it needed at all?

I appreciate the questions. I sense there may be some confusion over who this is intended to benefit.

The design of the Linux kernel is emergent. This is a fundamental property of the way it is developed, and the source of its greatest strength. But it has some shortcomings that place a burden on kernel maintainers, all kernel testing, and even people who wish to contribute.

We intend this as a tool to address those areas.

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

For some reason Linux has succeeded in pretty much every place an operating system is needed for cpus that it can run on (zephyr for those others that it can not.) So why are we suddenly now, after many decades, requiring basic user/kernel stuff to be formally documented like this?

You are correct, the kernel has succeeded over many decades, and will continue succeeding for many decades to come.

With the exception of some very narrow situations, the emergent design (or "nuanced complexity" if you prefer that term) of the Linux kernel is not communicated in a broadly consistent way. This affects the way the kernel is tested, and also the way it is developed. Even veteran kernel maintainers are tripping over nuance and complexity.

Quoted 8 lines
Quoted 1 line

Let me try to answer starting from the "why".

Let's ignore the "why" for now, and get to the "how" and "what" which you skipped from my questions above.

_Exactly_ how many in-kernel functions are you claiming is needed to be documented in this type of way before Linux would become "acceptable" to these regulatory agencies, and which ones _specifically_ are they?

Exactly zero. This is not for regulators.

Quoted 2 lines

Without knowing that, we could argue about the format all day long, and yet have nothing to show for it.

As this is not intended for regulators, it is not clear to me that catering to their desires would be a good use of anyone's time.

I say this as a software engineer who works in a _highly_ regulated industry, and who knows the relevant regulations quite well. There are good ideas buried in those regulations, but (in their default form) they are _not_ appropriate for the Linux kernel development process.

Quoted 1 line

And then, I have to ask, exactly "who" is going to do that work.

The intent is to allow for a separate maintainer path. There is more to it than that, but I do not want to bury the lede here.

Quoted 7 lines

I'll point at another "you must do this for reasons" type of request we have had in the past, SPDX. Sadly that task was never actually finished as it looks like no one really cared to do the real work involved. We got other benefits out of that effort, but the "goal" that people started that effort with was never met. Part of that is me not pushing back hard enough on the "who is going to do the work" part of that question, which is important in stuff like this.

Well, I am sorry for that. I am not quite sure how to respond, but I certainly sympathize with past frustrations. I have plenty of my own.

We are not offering a silver bullet here, and the work to describe the kernel's design will be finished when the work of development is finished. This is just an attempt to fill in a semantic gap that is responsible for a great deal of technical debt and maintainer burnout.

Quoted 2 lines

If you never complete the effort, your end goal of passing Linux off to those customers will never happen.

It is not clear to me what customers you are talking about. That is certainly not a goal in the mind of anyone working on this project that I am aware of.

Quoted 4 lines

So, try to answer that, with lots and lots of specifics, and then, if we agree that it is a sane thing to attempt (i.e. you are going to do all the work and it actually would be possible to complete), then we can argue about the format of the text :)

I respect what you are saying here, and perhaps the point of confusion came from the safety related source? As is often the case in science and engineering, we are borrowing (and _heavily_ modifying) a technique that is found in a different domain.

The intent is to target technical debt and maintainer burnout by filling in a semantic gap that occurs when a human idea is turned into code. Ironically, this is why the safety regulations were written in the first place, but little consideration was given to development methodology during that process.

Thank you,

..Ch:W..

maintainer
#24 lore raw
Quoted 8 lines · Chuck Wolber
Quoted 6 lines · Greg KH
Quoted 4 lines · Gabriele Paoloni
Quoted 4 lines

Every in-kernel api documented in a "formal" way like this? Or a subset? If a subset, which ones specifically? How many? And who is going to do that? And who is going to maintain it? And most importantly, why is it needed at all?

Quoted 7 lines

I appreciate the questions. I sense there may be some confusion over who this is intended to benefit.

The design of the Linux kernel is emergent. This is a fundamental property of the way it is developed, and the source of its greatest strength. But it has some shortcomings that place a burden on kernel maintainers, all kernel testing, and even people who wish to contribute.

What specific burden? A lack of documentation? Something else? How are we surviving without this "standardized" interface so far? Are you a maintainer that runs into this issue in the past?

Quoted 1 line

We intend this as a tool to address those areas.

What tool exactly? And who is asking for this?

Quoted 5 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

For some reason Linux has succeeded in pretty much every place an operating system is needed for cpus that it can run on (zephyr for those others that it can not.) So why are we suddenly now, after many decades, requiring basic user/kernel stuff to be formally documented like this?

Quoted 8 lines

You are correct, the kernel has succeeded over many decades, and will continue succeeding for many decades to come.

With the exception of some very narrow situations, the emergent design (or "nuanced complexity" if you prefer that term) of the Linux kernel is not communicated in a broadly consistent way. This affects the way the kernel is tested, and also the way it is developed. Even veteran kernel maintainers are tripping over nuance and complexity.

We all trip over nuance and complexity, but I do not belive that adding more formal comments is going to solve that (hint, the proof is on you...)

Quoted 10 lines
Quoted 8 lines
Quoted 1 line

Let me try to answer starting from the "why".

Let's ignore the "why" for now, and get to the "how" and "what" which you skipped from my questions above.

_Exactly_ how many in-kernel functions are you claiming is needed to be documented in this type of way before Linux would become "acceptable" to these regulatory agencies, and which ones _specifically_ are they?

Exactly zero. This is not for regulators.

Great! Then we don't have to do anything and you all can stop it with the "we need this to pass certification reviews" nonsense. :)

Quoted 5 lines
Quoted 2 lines

Without knowing that, we could argue about the format all day long, and yet have nothing to show for it.

As this is not intended for regulators, it is not clear to me that catering to their desires would be a good use of anyone's time.

Agreed!

Quoted 4 lines
Quoted 1 line

And then, I have to ask, exactly "who" is going to do that work.

The intent is to allow for a separate maintainer path. There is more to it than that, but I do not want to bury the lede here.

But that's the real issue. We've seen loads of proposals in the past that have gone no where as no one actually does the real work.

Heck, look at SPDX, that "simple" work isn't yet done because no one actually funded it, they just "demanded" that we implement SPDX tags for all files, and when the work got hard, everyone ran away.

What makes you believe that documenting something that is orders of magnitude more complex than something as "simple" as SPDX is going to actually happen to our codebase?

Quoted 10 lines
Quoted 4 lines

So, try to answer that, with lots and lots of specifics, and then, if we agree that it is a sane thing to attempt (i.e. you are going to do all the work and it actually would be possible to complete), then we can argue about the format of the text :)

I respect what you are saying here, and perhaps the point of confusion came from the safety related source? As is often the case in science and engineering, we are borrowing (and _heavily_ modifying) a technique that is found in a different domain.

Quoted 4 lines

The intent is to target technical debt and maintainer burnout by filling in a semantic gap that occurs when a human idea is turned into code. Ironically, this is why the safety regulations were written in the first place, but little consideration was given to development methodology during that process.

So I don't see the real goal here. You all for some reason want to "formalize" a documentation process of all kernel apis internally, for the sole reason of making developer's and maintainer's lives easier?

Again, who is actually going to do that work? And if you are, great, just start sending out patches today using the format that we already have for kerneldoc and the like. No need for formal language requirements here as obviously no tool is going to be parsing this, nor as you said, any regulator is going to be reading this.

So let's just stick with the style that we have already, no need to change anything, just start sending documentation patches!

thanks,

greg k-h