Peios Learn
Documentation

Peios

Peios Peios Kernel Universal Directory Project

Developer Tools

Trail Acta Provium clackatoo CAF GCSL Pekit

Applications

Framewright

Standards and Conventions

Standards and Conventions Peios Specifications
Peios Kernel

Development tools

Single-page view · as markdown

Development tools for the kernel

Peios Kernel / Kernel development / Development tools

This document is a collection of documents about development tools that can be used to work on the kernel. For now, the documents have been pulled together without any significant effort to integrate them into a coherent whole; patches welcome!

A brief overview of testing-specific tools can be found in Documentation/dev-tools/testing-overview.rst

Tools that are specific to debugging can be found in Documentation/process/debugging/index.rst

Table of contents

  • Kernel Testing Guide
  • Checkpatch
  • clang-format
  • Coccinelle
  • Compiler-Based Context Analysis
  • Sparse
  • KCOV: code coverage for fuzzing
  • Using gcov with the Linux kernel
  • Kernel Address Sanitizer (KASAN)
  • Kernel Memory Sanitizer (KMSAN)
  • Undefined Behavior Sanitizer - UBSAN
  • Kernel Memory Leak Detector
  • Kernel Concurrency Sanitizer (KCSAN)
  • Linux Kernel Memory Consistency Model (LKMM)
  • Kernel Electric-Fence (KFENCE)
  • Linux Kernel Selftests
  • KUnit - Linux Kernel Unit Testing
  • The Kernel Test Anything Protocol (KTAP), version 1
  • UAPI Checker
  • Linux Kernel GPIO based sloppy logic analyzer
  • Using AutoFDO with the Linux kernel
  • Using Propeller with the Linux kernel
  • Containerized Builds

Using AutoFDO with the Linux kernel

Peios Kernel / Kernel development / Development tools

This enables AutoFDO build support for the kernel when using the Clang compiler. AutoFDO (Auto-Feedback-Directed Optimization) is a type of profile-guided optimization (PGO) used to enhance the performance of binary executables. It gathers information about the frequency of execution of various code paths within a binary using hardware sampling. This data is then used to guide the compiler's optimization decisions, resulting in a more efficient binary. AutoFDO is a powerful optimization technique, and data indicates that it can significantly improve kernel performance. It's especially beneficial for workloads affected by front-end stalls.

For AutoFDO builds, unlike non-FDO builds, the user must supply a profile. Acquiring an AutoFDO profile can be done in several ways. AutoFDO profiles are created by converting hardware sampling using the "perf" tool. It is crucial that the workload used to create these perf files is representative; they must exhibit runtime characteristics similar to the workloads that are intended to be optimized. Failure to do so will result in the compiler optimizing for the wrong objective.

The AutoFDO profile often encapsulates the program's behavior. If the performance-critical codes are architecture-independent, the profile can be applied across platforms to achieve performance gains. For instance, using the profile generated on Intel architecture to build a kernel for AMD architecture can also yield performance improvements.

There are two methods for acquiring a representative profile: (1) Sample real workloads using a production environment. (2) Generate the profile using a representative load test. When enabling the AutoFDO build configuration without providing an AutoFDO profile, the compiler only modifies the dwarf information in the kernel without impacting runtime performance. It's advisable to use a kernel binary built with the same AutoFDO configuration to collect the perf profile. While it's possible to use a kernel built with different options, it may result in inferior performance.

One can collect profiles using AutoFDO build for the previous kernel. AutoFDO employs relative line numbers to match the profiles, offering some tolerance for source changes. This mode is commonly used in a production environment for profile collection.

In a profile collection based on a load test, the AutoFDO collection process consists of the following steps:

  1. Initial build: The kernel is built with AutoFDO options without a profile.

  2. Profiling: The above kernel is then run with a representative workload to gather execution frequency data. This data is collected using hardware sampling, via perf. AutoFDO is most effective on platforms supporting advanced PMU features like LBR on Intel machines.

  3. AutoFDO profile generation: Perf output file is converted to the AutoFDO profile via offline tools.

The support requires a Clang compiler LLVM 17 or later.

Preparation #

Configure the kernel with:

CONFIG_AUTOFDO_CLANG=y

Customization #

The default CONFIG_AUTOFDO_CLANG setting covers kernel space objects for AutoFDO builds. One can, however, enable or disable AutoFDO build for individual files and directories by adding a line similar to the following to the respective kernel Makefile:

  • For enabling a single file (e.g. foo.o)

    AUTOFDO_PROFILE_foo.o := y
    
  • For enabling all files in one directory

    AUTOFDO_PROFILE := y
    
  • For disabling one file

    AUTOFDO_PROFILE_foo.o := n
    
  • For disabling all files in one directory

    AUTOFDO_PROFILE := n
    

Workflow #

Here is an example workflow for AutoFDO kernel:

  1. Build the kernel on the host machine with LLVM enabled, for example,

    $ make menuconfig LLVM=1
    

    Turn on AutoFDO build config:

    CONFIG_AUTOFDO_CLANG=y
    

    With a configuration that with LLVM enabled, use the following command:

    $ scripts/config -e AUTOFDO_CLANG
    

    After getting the config, build with

    $ make LLVM=1
    
  2. Install the kernel on the test machine.

  3. Run the load tests. The '-c' option in perf specifies the sample event period. We suggest using a suitable prime number, like 500009, for this purpose.

    • For Intel platforms:

      $ perf record -e BR_INST_RETIRED.NEAR_TAKEN:k -a -N -b -c <count> -o <perf_file> -- <loadtest>
      
    • For AMD platforms:

      The supported systems are: Zen3 with BRS, or Zen4 with amd_lbr_v2. To check,

      For Zen3:

      $ cat /proc/cpuinfo | grep " brs"
      

      For Zen4:

      $ cat /proc/cpuinfo | grep amd_lbr_v2
      

      The following command generated the perf data file:

      $ perf record --pfm-events RETIRED_TAKEN_BRANCH_INSTRUCTIONS:k -a -N -b -c <count> -o <perf_file> -- <loadtest>
      
  4. (Optional) Download the raw perf file to the host machine.

  5. To generate an AutoFDO profile, two offline tools are available: create_llvm_prof and llvm_profgen. The create_llvm_prof tool is part of the AutoFDO project and can be found on GitHub (https://github.com/google/autofdo), version v0.30.1 or later. The llvm_profgen tool is included in the LLVM compiler itself. It's important to note that the version of llvm_profgen doesn't need to match the version of Clang. It needs to be the LLVM 19 release of Clang or later, or just from the LLVM trunk.

    $ llvm-profgen --kernel --binary=<vmlinux> --perfdata=<perf_file> -o <profile_file>
    

    or

    $ create_llvm_prof --binary=<vmlinux> --profile=<perf_file> --format=extbinary --out=<profile_file>
    

    Note that multiple AutoFDO profile files can be merged into one via:

    $ llvm-profdata merge -o <profile_file> <profile_1> <profile_2> ... <profile_n>
    
  6. Rebuild the kernel using the AutoFDO profile file with the same config as step 1, (Note CONFIG_AUTOFDO_CLANG needs to be enabled):

    $ make LLVM=1 CLANG_AUTOFDO_PROFILE=<profile_file>
    

Checkpatch

Peios Kernel / Kernel development / Development tools

Checkpatch (scripts/checkpatch.pl) is a perl script which checks for trivial style violations in patches and optionally corrects them. Checkpatch can also be run on file contexts and without the kernel tree.

Checkpatch is not always right. Your judgement takes precedence over checkpatch messages. If your code looks better with the violations, then its probably best left alone.

Options #

This section will describe the options checkpatch can be run with.

Usage:

./scripts/checkpatch.pl [OPTION]... [FILE]...

Available options:

  • -q, --quiet

    Enable quiet mode.

  • -v, --verbose Enable verbose mode. Additional verbose test descriptions are output so as to provide information on why that particular message is shown.

  • --no-tree

    Run checkpatch without the kernel tree.

  • --no-signoff

    Disable the 'Signed-off-by' line check. The sign-off is a simple line at the end of the explanation for the patch, which certifies that you wrote it or otherwise have the right to pass it on as an open-source patch.

    Example:

    Signed-off-by: Random J Developer <random@developer.example.org>
    

    Setting this flag effectively stops a message for a missing signed-off-by line in a patch context.

  • --patch

    Treat FILE as a patch. This is the default option and need not be explicitly specified.

  • --emacs

    Set output to emacs compile window format. This allows emacs users to jump from the error in the compile window directly to the offending line in the patch.

  • --terse

    Output only one line per report.

  • --showfile

    Show the diffed file position instead of the input file position.

  • -g, --git

    Treat FILE as a single commit or a git revision range.

    Single commit with:

    • <rev>

    • <rev>^

    • <rev>~n

    Multiple commits with:

    • <rev1>..<rev2>

    • <rev1>...<rev2>

    • <rev>-<count>

  • -f, --file

    Treat FILE as a regular source file. This option must be used when running checkpatch on source files in the kernel.

  • --subjective, --strict

    Enable stricter tests in checkpatch. By default the tests emitted as CHECK do not activate by default. Use this flag to activate the CHECK tests.

  • --list-types

    Every message emitted by checkpatch has an associated TYPE. Add this flag to display all the types in checkpatch.

    Note that when this flag is active, checkpatch does not read the input FILE, and no message is emitted. Only a list of types in checkpatch is output.

  • --types TYPE(,TYPE2...)

    Only display messages with the given types.

    Example:

    ./scripts/checkpatch.pl mypatch.patch --types EMAIL_SUBJECT,BRACES
    
  • --ignore TYPE(,TYPE2...)

    Checkpatch will not emit messages for the specified types.

    Example:

    ./scripts/checkpatch.pl mypatch.patch --ignore EMAIL_SUBJECT,BRACES
    
  • --show-types

    By default checkpatch doesn't display the type associated with the messages. Set this flag to show the message type in the output.

  • --max-line-length=n

    Set the max line length (default 100). If a line exceeds the specified length, a LONG_LINE message is emitted.

    The message level is different for patch and file contexts. For patches, a WARNING is emitted. While a milder CHECK is emitted for files. So for file contexts, the --strict flag must also be enabled.

  • --min-conf-desc-length=n

    Set the Kconfig entry minimum description length, if shorter, warn.

  • --tab-size=n

    Set the number of spaces for tab (default 8).

  • --root=PATH

    PATH to the kernel tree root.

    This option must be specified when invoking checkpatch from outside the kernel root.

  • --no-summary

    Suppress the per file summary.

  • --mailback

    Only produce a report in case of Warnings or Errors. Milder Checks are excluded from this.

  • --summary-file

    Include the filename in summary.

  • --debug KEY=[0|1]

    Turn on/off debugging of KEY, where KEY is one of 'values', 'possible', 'type', and 'attr' (default is all off).

  • --fix

    This is an EXPERIMENTAL feature. If correctable errors exist, a file <inputfile>.EXPERIMENTAL-checkpatch-fixes is created which has the automatically fixable errors corrected.

  • --fix-inplace

    EXPERIMENTAL - Similar to --fix but input file is overwritten with fixes.

    DO NOT USE this flag unless you are absolutely sure and you have a backup in place.

  • --ignore-perl-version

    Override checking of perl version. Runtime errors may be encountered after enabling this flag if the perl version does not meet the minimum specified.

  • --codespell

    Use the codespell dictionary for checking spelling errors.

  • --codespellfile

    Use the specified codespell file. Default is '/usr/share/codespell/dictionary.txt'.

  • --typedefsfile

    Read additional types from this file.

  • --color[=WHEN]

    Use colors 'always', 'never', or only when output is a terminal ('auto'). Default is 'auto'.

  • --kconfig-prefix=WORD

    Use WORD as a prefix for Kconfig symbols (default is CONFIG_).

  • -h, --help, --version

    Display the help text.

Message Levels #

Messages in checkpatch are divided into three levels. The levels of messages in checkpatch denote the severity of the error. They are:

  • ERROR

    This is the most strict level. Messages of type ERROR must be taken seriously as they denote things that are very likely to be wrong.

  • WARNING

    This is the next stricter level. Messages of type WARNING requires a more careful review. But it is milder than an ERROR.

  • CHECK

    This is the mildest level. These are things which may require some thought.

Type Descriptions #

This section contains a description of all the message types in checkpatch.

Allocation style #

  • ALLOC_ARRAY_ARGS

    The first argument for kcalloc or kmalloc_array should be the number of elements. sizeof() as the first argument is generally wrong.

    See: https://www.kernel.org/doc/html/latest/core-api/memory-allocation.html

  • ALLOC_SIZEOF_STRUCT

    The allocation style is bad. In general for family of allocation functions using sizeof() to get memory size, constructs like:

    p = alloc(sizeof(struct foo), ...)
    

    should be:

    p = alloc(sizeof(*p), ...)
    

    See: https://www.kernel.org/doc/html/latest/process/coding-style.html#allocating-memory

  • ALLOC_WITH_MULTIPLY

    Prefer kmalloc_array/kcalloc over kmalloc/kzalloc with a sizeof multiply.

    See: https://www.kernel.org/doc/html/latest/core-api/memory-allocation.html

API usage #

  • ARCH_DEFINES

    Architecture specific defines should be avoided wherever possible.

  • ARCH_INCLUDE_LINUX

    Whenever asm/file.h is included and linux/file.h exists, a conversion can be made when linux/file.h includes asm/file.h. However this is not always the case (See signal.h). This message type is emitted only for includes from arch/.

  • AVOID_BUG

    BUG() or BUG_ON() should be avoided totally. Use WARN() and WARN_ON() instead, and handle the "impossible" error condition as gracefully as possible.

    See: https://www.kernel.org/doc/html/latest/process/deprecated.html#bug-and-bug-on

  • CONSIDER_KSTRTO

    The simple_strtol(), simple_strtoll(), simple_strtoul(), and simple_strtoull() functions explicitly ignore overflows, which may lead to unexpected results in callers. The respective kstrtol(), kstrtoll(), kstrtoul(), and kstrtoull() functions tend to be the correct replacements.

    See: https://www.kernel.org/doc/html/latest/process/deprecated.html#simple-strtol-simple-strtoll-simple-strtoul-simple-strtoull

  • CONSTANT_CONVERSION

    Use of __constant_<foo> form is discouraged for the following functions:

    __constant_cpu_to_be[x]
    __constant_cpu_to_le[x]
    __constant_be[x]_to_cpu
    __constant_le[x]_to_cpu
    __constant_htons
    __constant_ntohs
    

    Using any of these outside of include/uapi/ is not preferred as using the function without __constant_ is identical when the argument is a constant.

    In big endian systems, the macros like __constant_cpu_to_be32(x) and cpu_to_be32(x) expand to the same expression:

    #define __constant_cpu_to_be32(x) ((__force __be32)(__u32)(x))
    #define __cpu_to_be32(x)          ((__force __be32)(__u32)(x))
    

    In little endian systems, the macros __constant_cpu_to_be32(x) and cpu_to_be32(x) expand to __constant_swab32 and __swab32. __swab32 has a __builtin_constant_p check:

    #define __swab32(x)                               \
      (__builtin_constant_p((__u32)(x)) ?     \
      ___constant_swab32(x) :                 \
      __fswab32(x))
    

    So ultimately they have a special case for constants. Similar is the case with all of the macros in the list. Thus using the __constant_... forms are unnecessarily verbose and not preferred outside of include/uapi.

    See: https://lore.kernel.org/lkml/1400106425.12666.6.camel@joe-AO725/

  • DEPRECATED_API

    Usage of a deprecated RCU API is detected. It is recommended to replace old flavourful RCU APIs by their new vanilla-RCU counterparts.

    The full list of available RCU APIs can be viewed from the kernel docs.

    See: https://www.kernel.org/doc/html/latest/RCU/whatisRCU.html#full-list-of-rcu-apis

  • DEVICE_ATTR_FUNCTIONS

    The function names used in DEVICE_ATTR is unusual. Typically, the store and show functions are used with <attr>_store and <attr>_show, where <attr> is a named attribute variable of the device.

    Consider the following examples:

    static DEVICE_ATTR(type, 0444, type_show, NULL);
    static DEVICE_ATTR(power, 0644, power_show, power_store);
    

    The function names should preferably follow the above pattern.

    See: https://www.kernel.org/doc/html/latest/driver-api/driver-model/device.html#attributes

  • DEVICE_ATTR_RO

    The DEVICE_ATTR_RO(name) helper macro can be used instead of DEVICE_ATTR(name, 0444, name_show, NULL);

    Note that the macro automatically appends _show to the named attribute variable of the device for the show method.

    See: https://www.kernel.org/doc/html/latest/driver-api/driver-model/device.html#attributes

  • DEVICE_ATTR_RW

    The DEVICE_ATTR_RW(name) helper macro can be used instead of DEVICE_ATTR(name, 0644, name_show, name_store);

    Note that the macro automatically appends _show and _store to the named attribute variable of the device for the show and store methods.

    See: https://www.kernel.org/doc/html/latest/driver-api/driver-model/device.html#attributes

  • DEVICE_ATTR_WO

    The DEVICE_AATR_WO(name) helper macro can be used instead of DEVICE_ATTR(name, 0200, NULL, name_store);

    Note that the macro automatically appends _store to the named attribute variable of the device for the store method.

    See: https://www.kernel.org/doc/html/latest/driver-api/driver-model/device.html#attributes

  • DUPLICATED_SYSCTL_CONST

    Commit d91bff3011cf ("proc/sysctl: add shared variables for range check") added some shared const variables to be used instead of a local copy in each source file.

    Consider replacing the sysctl range checking value with the shared one in include/linux/sysctl.h. The following conversion scheme may be used:

    &zero     ->  SYSCTL_ZERO
    &one      ->  SYSCTL_ONE
    &int_max  ->  SYSCTL_INT_MAX
    

    See:

    1. https://lore.kernel.org/lkml/20190430180111.10688-1-mcroce@redhat.com/

    2. https://lore.kernel.org/lkml/20190531131422.14970-1-mcroce@redhat.com/

  • ENOSYS

    ENOSYS means that a nonexistent system call was called. Earlier, it was wrongly used for things like invalid operations on otherwise valid syscalls. This should be avoided in new code.

    See: https://lore.kernel.org/lkml/5eb299021dec23c1a48fa7d9f2c8b794e967766d.1408730669.git.luto@amacapital.net/

  • ENOTSUPP

    ENOTSUPP is not a standard error code and should be avoided in new patches. EOPNOTSUPP should be used instead.

    See: https://lore.kernel.org/netdev/20200510182252.GA411829@lunn.ch/

  • EXPORT_SYMBOL

    EXPORT_SYMBOL should immediately follow the symbol to be exported.

  • IN_ATOMIC

    in_atomic() is not for driver use so any such use is reported as an ERROR. Also in_atomic() is often used to determine if sleeping is permitted, but it is not reliable in this use model. Therefore its use is strongly discouraged.

    However, in_atomic() is ok for core kernel use.

    See: https://lore.kernel.org/lkml/20080320201723.b87b3732.akpm@linux-foundation.org/

  • LOCKDEP

    The lockdep_no_validate class was added as a temporary measure to prevent warnings on conversion of device->sem to device->mutex. It should not be used for any other purpose.

    See: https://lore.kernel.org/lkml/1268959062.9440.467.camel@laptop/

  • MALFORMED_INCLUDE

    The #include statement has a malformed path. This has happened because the author has included a double slash "//" in the pathname accidentally.

  • USE_LOCKDEP

    lockdep_assert_held() annotations should be preferred over assertions based on spin_is_locked()

    See: https://www.kernel.org/doc/html/latest/locking/lockdep-design.html#annotations

  • UAPI_INCLUDE

    No #include statements in include/uapi should use a uapi/ path.

  • USLEEP_RANGE

    usleep_range() should be preferred over udelay(). The proper way of using usleep_range() is mentioned in the kernel docs.

Comments #

  • BLOCK_COMMENT_STYLE

    The comment style is incorrect. The preferred style for multi- line comments is:

    /*
     * This is the preferred style
     * for multi line comments.
     */
    

    See: https://www.kernel.org/doc/html/latest/process/coding-style.html#commenting

  • C99_COMMENTS

    C99 style single line comments (//) should not be used. Prefer the block comment style instead.

    See: https://www.kernel.org/doc/html/latest/process/coding-style.html#commenting

  • DATA_RACE

    Applications of data_race() should have a comment so as to document the reasoning behind why it was deemed safe.

    See: https://lore.kernel.org/lkml/20200401101714.44781-1-elver@google.com/

  • FSF_MAILING_ADDRESS

    Kernel maintainers reject new instances of the GPL boilerplate paragraph directing people to write to the FSF for a copy of the GPL, since the FSF has moved in the past and may do so again. So do not write paragraphs about writing to the Free Software Foundation's mailing address.

    See: https://lore.kernel.org/lkml/20131006222342.GT19510@leaf/

  • UNCOMMENTED_RGMII_MODE

    Historically, the RGMII PHY modes specified in Device Trees have been used inconsistently, often referring to the usage of delays on the PHY side rather than describing the board.

    PHY modes "rgmii", "rgmii-rxid" and "rgmii-txid" modes require the clock signal to be delayed on the PCB; this unusual configuration should be described in a comment. If they are not (meaning that the delay is realized internally in the MAC or PHY), "rgmii-id" is the correct PHY mode.

Commit message #

  • BAD_SIGN_OFF

    The signed-off-by line does not fall in line with the standards specified by the community.

    See: https://www.kernel.org/doc/html/latest/process/submitting-patches.html#developer-s-certificate-of-origin-1-1

  • BAD_STABLE_ADDRESS_STYLE

    The email format for stable is incorrect. Some valid options for stable address are:

    1. stable@vger.kernel.org
    2. stable@kernel.org
    

    For adding version info, the following comment style should be used:

    stable@vger.kernel.org # version info
    
  • COMMIT_COMMENT_SYMBOL

    Commit log lines starting with a '#' are ignored by git as comments. To solve this problem addition of a single space infront of the log line is enough.

  • COMMIT_MESSAGE

    The patch is missing a commit description. A brief description of the changes made by the patch should be added.

    See: https://www.kernel.org/doc/html/latest/process/submitting-patches.html#describe-your-changes

  • EMAIL_SUBJECT

    Naming the tool that found the issue is not very useful in the subject line. A good subject line summarizes the change that the patch brings.

    See: https://www.kernel.org/doc/html/latest/process/submitting-patches.html#describe-your-changes

  • FROM_SIGN_OFF_MISMATCH

    The author's email does not match with that in the Signed-off-by: line(s). This can be sometimes caused due to an improperly configured email client.

    This message is emitted due to any of the following reasons:

    - The email names do not match.
    - The email addresses do not match.
    - The email subaddresses do not match.
    - The email comments do not match.
    
  • MISSING_SIGN_OFF

    The patch is missing a Signed-off-by line. A signed-off-by line should be added according to Developer's certificate of Origin.

    See: https://www.kernel.org/doc/html/latest/process/submitting-patches.html#sign-your-work-the-developer-s-certificate-of-origin

  • NO_AUTHOR_SIGN_OFF

    The author of the patch has not signed off the patch. It is required that a simple sign off line should be present at the end of explanation of the patch to denote that the author has written it or otherwise has the rights to pass it on as an open source patch.

    See: https://www.kernel.org/doc/html/latest/process/submitting-patches.html#sign-your-work-the-developer-s-certificate-of-origin

  • DIFF_IN_COMMIT_MSG

    Avoid having diff content in commit message. This causes problems when one tries to apply a file containing both the changelog and the diff because patch(1) tries to apply the diff which it found in the changelog.

    See: https://lore.kernel.org/lkml/20150611134006.9df79a893e3636019ad2759e@linux-foundation.org/

  • GERRIT_CHANGE_ID

    To be picked up by gerrit, the footer of the commit message might have a Change-Id like:

    Change-Id: Ic8aaa0728a43936cd4c6e1ed590e01ba8f0fbf5b
    Signed-off-by: A. U. Thor <author@example.com>
    

    The Change-Id line must be removed before submitting.

  • GIT_COMMIT_ID

    The proper way to reference a commit id is: commit <12+ chars of sha1> ("<title line>")

    An example may be:

    Commit e21d2170f36602ae2708 ("video: remove unnecessary
    platform_set_drvdata()") removed the unnecessary
    platform_set_drvdata(), but left the variable "dev" unused,
    delete it.
    

    See: https://www.kernel.org/doc/html/latest/process/submitting-patches.html#describe-your-changes

  • BAD_FIXES_TAG

    The Fixes: tag is malformed or does not follow the community conventions. This can occur if the tag have been split into multiple lines (e.g., when pasted in an email program with word wrapping enabled).

    See: https://www.kernel.org/doc/html/latest/process/submitting-patches.html#describe-your-changes

  • BAD_COMMIT_SEPARATOR

    The commit separator is a single line with 3 dashes. The regex match is '^---$' Lines that start with 3 dashes and have more content on the same line may confuse tools that apply patches.

Comparison style #

  • ASSIGN_IN_IF

    Do not use assignments in if condition. Example:

    if ((foo = bar(...)) < BAZ) {
    

    should be written as:

    foo = bar(...);
    if (foo < BAZ) {
    
  • BOOL_COMPARISON

    Comparisons of A to true and false are better written as A and !A.

    See: https://lore.kernel.org/lkml/1365563834.27174.12.camel@joe-AO722/

  • COMPARISON_TO_NULL

    Comparisons to NULL in the form (foo == NULL) or (foo != NULL) are better written as (!foo) and (foo).

  • CONSTANT_COMPARISON

    Comparisons with a constant or upper case identifier on the left side of the test should be avoided.

Indentation and Line Breaks #

  • CODE_INDENT

    Code indent should use tabs instead of spaces. Outside of comments, documentation and Kconfig, spaces are never used for indentation.

    See: https://www.kernel.org/doc/html/latest/process/coding-style.html#indentation

  • DEEP_INDENTATION

    Indentation with 6 or more tabs usually indicate overly indented code.

    It is suggested to refactor excessive indentation of if/else/for/do/while/switch statements.

    See: https://lore.kernel.org/lkml/1328311239.21255.24.camel@joe2Laptop/

  • SWITCH_CASE_INDENT_LEVEL

    switch should be at the same indent as case. Example:

    switch (suffix) {
    case 'G':
    case 'g':
            mem <<= 30;
            break;
    case 'M':
    case 'm':
            mem <<= 20;
            break;
    case 'K':
    case 'k':
            mem <<= 10;
            fallthrough;
    default:
            break;
    }
    

    See: https://www.kernel.org/doc/html/latest/process/coding-style.html#indentation

  • LONG_LINE

    The line has exceeded the specified maximum length. To use a different maximum line length, the --max-line-length=n option may be added while invoking checkpatch.

    Earlier, the default line length was 80 columns. Commit bdc48fa11e46 ("checkpatch/coding-style: deprecate 80-column warning") increased the limit to 100 columns. This is not a hard limit either and it's preferable to stay within 80 columns whenever possible.

    See: https://www.kernel.org/doc/html/latest/process/coding-style.html#breaking-long-lines-and-strings

  • LONG_LINE_STRING

    A string starts before but extends beyond the maximum line length. To use a different maximum line length, the --max-line-length=n option may be added while invoking checkpatch.

    See: https://www.kernel.org/doc/html/latest/process/coding-style.html#breaking-long-lines-and-strings

  • LONG_LINE_COMMENT

    A comment starts before but extends beyond the maximum line length. To use a different maximum line length, the --max-line-length=n option may be added while invoking checkpatch.

    See: https://www.kernel.org/doc/html/latest/process/coding-style.html#breaking-long-lines-and-strings

  • SPLIT_STRING

    Quoted strings that appear as messages in userspace and can be grepped, should not be split across multiple lines.

    See: https://lore.kernel.org/lkml/20120203052727.GA15035@leaf/

  • MULTILINE_DEREFERENCE

    A single dereferencing identifier spanned on multiple lines like:

    struct_identifier->member[index].
    member = <foo>;
    

    is generally hard to follow. It can easily lead to typos and so makes the code vulnerable to bugs.

    If fixing the multiple line dereferencing leads to an 80 column violation, then either rewrite the code in a more simple way or if the starting part of the dereferencing identifier is the same and used at multiple places then store it in a temporary variable, and use that temporary variable only at all the places. For example, if there are two dereferencing identifiers:

    member1->member2->member3.foo1;
    member1->member2->member3.foo2;
    

    then store the member1->member2->member3 part in a temporary variable. It not only helps to avoid the 80 column violation but also reduces the program size by removing the unnecessary dereferences.

    But if none of the above methods work then ignore the 80 column violation because it is much easier to read a dereferencing identifier on a single line.

  • TRAILING_STATEMENTS

    Trailing statements (for example after any conditional) should be on the next line. Statements, such as:

    if (x == y) break;
    

    should be:

    if (x == y)
            break;
    

Macros, Attributes and Symbols #

  • ARRAY_SIZE

    The ARRAY_SIZE(foo) macro should be preferred over sizeof(foo)/sizeof(foo[0]) for finding number of elements in an array.

    The macro is defined in include/linux/array_size.h:

    #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
    
  • AVOID_EXTERNS

    Function prototypes don't need to be declared extern in .h files. It's assumed by the compiler and is unnecessary.

  • AVOID_L_PREFIX

    Local symbol names that are prefixed with .L should be avoided, as this has special meaning for the assembler; a symbol entry will not be emitted into the symbol table. This can prevent objtool from generating correct unwind info.

    Symbols with STB_LOCAL binding may still be used, and .L prefixed local symbol names are still generally usable within a function, but .L prefixed local symbol names should not be used to denote the beginning or end of code regions via SYM_CODE_START_LOCAL/SYM_CODE_END

  • BIT_MACRO

    Defines like: 1 << <digit> could be BIT(digit). The BIT() macro is defined via include/linux/bits.h:

    #define BIT(nr)         (1UL << (nr))
    
  • CONST_READ_MOSTLY

    When a variable is tagged with the __read_mostly annotation, it is a signal to the compiler that accesses to the variable will be mostly reads and rarely(but NOT never) a write.

    const __read_mostly does not make any sense as const data is already read-only. The __read_mostly annotation thus should be removed.

  • DATE_TIME

    It is generally desirable that building the same source code with the same set of tools is reproducible, i.e. the output is always exactly the same.

    The kernel does not use the __DATE__ and __TIME__ macros, and enables warnings if they are used as they can lead to non-deterministic builds.

    See: https://www.kernel.org/doc/html/latest/kbuild/reproducible-builds.html#timestamps

  • DEFINE_ARCH_HAS

    The ARCH_HAS_xyz and ARCH_HAVE_xyz patterns are wrong.

    For big conceptual features use Kconfig symbols instead. And for smaller things where we have compatibility fallback functions but want architectures able to override them with optimized ones, we should either use weak functions (appropriate for some cases), or the symbol that protects them should be the same symbol we use.

    See: https://lore.kernel.org/lkml/CA+55aFycQ9XJvEOsiM3txHL5bjUc8CeKWJNR_H+MiicaddB42Q@mail.gmail.com/

  • DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON

    do {} while(0) macros should not have a trailing semicolon.

  • INIT_ATTRIBUTE

    Const init definitions should use __initconst instead of __initdata.

    Similarly init definitions without const require a separate use of const.

  • INLINE_LOCATION

    The inline keyword should sit between storage class and type.

    For example, the following segment:

    inline static int example_function(void)
    {
            ...
    }
    

    should be:

    static inline int example_function(void)
    {
            ...
    }
    
  • MISPLACED_INIT

    It is possible to use section markers on variables in a way which gcc doesn't understand (or at least not the way the developer intended):

    static struct __initdata samsung_pll_clock exynos4_plls[nr_plls] = {
    

    does not put exynos4_plls in the .initdata section. The __initdata marker can be virtually anywhere on the line, except right after "struct". The preferred location is before the "=" sign if there is one, or before the trailing ";" otherwise.

    See: https://lore.kernel.org/lkml/1377655732.3619.19.camel@joe-AO722/

  • MULTISTATEMENT_MACRO_USE_DO_WHILE

    Macros with multiple statements should be enclosed in a do - while block. Same should also be the case for macros starting with if to avoid logic defects:

    #define macrofun(a, b, c)                 \
      do {                                    \
              if (a == 5)                     \
                      do_this(b, c);          \
      } while (0)
    

    See: https://www.kernel.org/doc/html/latest/process/coding-style.html#macros-enums-and-rtl

  • PREFER_FALLTHROUGH

    Use the fallthrough; pseudo keyword instead of /* fallthrough */ like comments.

  • TRAILING_SEMICOLON

    Macro definition should not end with a semicolon. The macro invocation style should be consistent with function calls. This can prevent any unexpected code paths:

    #define MAC do_something;
    

    If this macro is used within a if else statement, like:

    if (some_condition)
            MAC;
    
    else
            do_something;
    

    Then there would be a compilation error, because when the macro is expanded there are two trailing semicolons, so the else branch gets orphaned.

    See: https://lore.kernel.org/lkml/1399671106.2912.21.camel@joe-AO725/

  • MACRO_ARG_UNUSED

    If function-like macros do not utilize a parameter, it might result in a build warning. We advocate for utilizing static inline functions to replace such macros. For example, for a macro such as the one below:

    #define test(a) do { } while (0)
    

    there would be a warning like below:

    WARNING: Argument 'a' is not used in function-like macro.
    

    See: https://www.kernel.org/doc/html/latest/process/coding-style.html#macros-enums-and-rtl

  • SINGLE_STATEMENT_DO_WHILE_MACRO

    For the multi-statement macros, it is necessary to use the do-while loop to avoid unpredictable code paths. The do-while loop helps to group the multiple statements into a single one so that a function-like macro can be used as a function only.

    But for the single statement macros, it is unnecessary to use the do-while loop. Although the code is syntactically correct but using the do-while loop is redundant. So remove the do-while loop for single statement macros.

  • WEAK_DECLARATION

    Using weak declarations like __attribute__((weak)) or __weak can have unintended link defects. Avoid using them.

Functions and Variables #

  • CAMELCASE

    Avoid CamelCase Identifiers.

    See: https://www.kernel.org/doc/html/latest/process/coding-style.html#naming

  • CONST_CONST

    Using const <type> const * is generally meant to be written const <type> * const.

  • CONST_STRUCT

    Using const is generally a good idea. Checkpatch reads a list of frequently used structs that are always or almost always constant.

    The existing structs list can be viewed from scripts/const_structs.checkpatch.

    See: https://lore.kernel.org/lkml/alpine.DEB.2.10.1608281509480.3321@hadrien/

  • EMBEDDED_FUNCTION_NAME

    Embedded function names are less appropriate to use as refactoring can cause function renaming. Prefer the use of "%s", __func__ to embedded function names.

    Note that this does not work with -f (--file) checkpatch option as it depends on patch context providing the function name.

  • FUNCTION_ARGUMENTS

    This warning is emitted due to any of the following reasons:

    1. Arguments for the function declaration do not follow the identifier name. Example:

      void foo
      (int bar, int baz)
      

      This should be corrected to:

      void foo(int bar, int baz)
      
    2. Some arguments for the function definition do not have an identifier name. Example:

      void foo(int)
      

      All arguments should have identifier names.

  • FUNCTION_WITHOUT_ARGS

    Function declarations without arguments like:

    int foo()
    

    should be:

    int foo(void)
    
  • GLOBAL_INITIALISERS

    Global variables should not be initialized explicitly to 0 (or NULL, false, etc.). Your compiler (or rather your loader, which is responsible for zeroing out the relevant sections) automatically does it for you.

  • INITIALISED_STATIC

    Static variables should not be initialized explicitly to zero. Your compiler (or rather your loader) automatically does it for you.

  • MULTIPLE_ASSIGNMENTS

    Multiple assignments on a single line makes the code unnecessarily complicated. So on a single line assign value to a single variable only, this makes the code more readable and helps avoid typos.

  • RETURN_PARENTHESES

    return is not a function and as such doesn't need parentheses:

    return (bar);
    

    can simply be:

    return bar;
    
  • UNINITIALIZED_PTR_WITH_FREE

    Pointers with __free attribute should be declared at the place of use and initialized (see include/linux/cleanup.h). In this case declarations at the top of the function rule can be relaxed. Not doing so may lead to undefined behavior as the memory assigned (garbage, in case not initialized) to the pointer is freed automatically when the pointer goes out of scope.

    Also see: https://lore.kernel.org/lkml/58fd478f408a34b578ee8d949c5c4b4da4d4f41d.camel@HansenPartnership.com/

    Example:

    type var __free(free_func);
    ... // var not used, but, in future someone might add a return here
    var = malloc(var_size);
    ...
    

    should be initialized as:

    ...
    type var __free(free_func) = malloc(var_size);
    ...
    

Permissions #

  • DEVICE_ATTR_PERMS

    The permissions used in DEVICE_ATTR are unusual. Typically only three permissions are used - 0644 (RW), 0444 (RO) and 0200 (WO).

    See: https://www.kernel.org/doc/html/latest/filesystems/sysfs.html#attributes

  • EXECUTE_PERMISSIONS

    There is no reason for source files to be executable. The executable bit can be removed safely.

  • EXPORTED_WORLD_WRITABLE

    Exporting world writable sysfs/debugfs files is usually a bad thing. When done arbitrarily they can introduce serious security bugs. In the past, some of the debugfs vulnerabilities would seemingly allow any local user to write arbitrary values into device registers - a situation from which little good can be expected to emerge.

    See: https://lore.kernel.org/linux-arm-kernel/cover.1296818921.git.segoon@openwall.com/

  • NON_OCTAL_PERMISSIONS

    Permission bits should use 4 digit octal permissions (like 0700 or 0444). Avoid using any other base like decimal.

  • SYMBOLIC_PERMS

    Permission bits in the octal form are more readable and easier to understand than their symbolic counterparts because many command-line tools use this notation. Experienced kernel developers have been using these traditional Unix permission bits for decades and so they find it easier to understand the octal notation than the symbolic macros. For example, it is harder to read S_IWUSR|S_IRUGO than 0644, which obscures the developer's intent rather than clarifying it.

    See: https://lore.kernel.org/lkml/CA+55aFw5v23T-zvDZp-MmD_EYxF8WbafwwB59934FV7g21uMGQ@mail.gmail.com/

Spacing and Brackets #

  • ASSIGNMENT_CONTINUATIONS

    Assignment operators should not be written at the start of a line but should follow the operand at the previous line.

  • BRACES

    The placement of braces is stylistically incorrect. The preferred way is to put the opening brace last on the line, and put the closing brace first:

    if (x is true) {
            we do y
    }
    

    This applies for all non-functional blocks. However, there is one special case, namely functions: they have the opening brace at the beginning of the next line, thus:

    int function(int x)
    {
            body of function
    }
    

    See: https://www.kernel.org/doc/html/latest/process/coding-style.html#placing-braces-and-spaces

  • BRACKET_SPACE

    Whitespace before opening bracket '[' is prohibited. There are some exceptions:

    1. With a type on the left:

      int [] a;
      
    2. At the beginning of a line for slice initialisers:

      [0...10] = 5,
      
    3. Inside a curly brace:

      = { [0...10] = 5 }
      
  • CONCATENATED_STRING

    Concatenated elements should have a space in between. Example:

    printk(KERN_INFO"bar");
    

    should be:

    printk(KERN_INFO "bar");
    
  • ELSE_AFTER_BRACE

    else { should follow the closing block } on the same line.

    See: https://www.kernel.org/doc/html/latest/process/coding-style.html#placing-braces-and-spaces

  • LINE_SPACING

    Vertical space is wasted given the limited number of lines an editor window can display when multiple blank lines are used.

    See: https://www.kernel.org/doc/html/latest/process/coding-style.html#spaces

  • OPEN_BRACE

    The opening brace should be following the function definitions on the next line. For any non-functional block it should be on the same line as the last construct.

    See: https://www.kernel.org/doc/html/latest/process/coding-style.html#placing-braces-and-spaces

  • POINTER_LOCATION

    When using pointer data or a function that returns a pointer type, the preferred use of * is adjacent to the data name or function name and not adjacent to the type name. Examples:

    char *linux_banner;
    unsigned long long memparse(char *ptr, char **retptr);
    char *match_strdup(substring_t *s);
    

    See: https://www.kernel.org/doc/html/latest/process/coding-style.html#spaces

  • SPACING

    Whitespace style used in the kernel sources is described in kernel docs.

    See: https://www.kernel.org/doc/html/latest/process/coding-style.html#spaces

  • TRAILING_WHITESPACE

    Trailing whitespace should always be removed. Some editors highlight the trailing whitespace and cause visual distractions when editing files.

    See: https://www.kernel.org/doc/html/latest/process/coding-style.html#spaces

  • UNNECESSARY_PARENTHESES

    Parentheses are not required in the following cases:

    1. Function pointer uses:

      (foo->bar)();
      

    could be:

    foo->bar();
    
    1. Comparisons in if:

      if ((foo->bar) && (foo->baz))
      if ((foo == bar))
      

    could be:

    if (foo->bar && foo->baz)
    if (foo == bar)
    
    1. addressof/dereference single Lvalues:

      &(foo->bar)
      *(foo->bar)
      

    could be:

    &foo->bar
    *foo->bar
    
  • WHILE_AFTER_BRACE

    while should follow the closing bracket on the same line:

    do {
            ...
    } while(something);
    

    See: https://www.kernel.org/doc/html/latest/process/coding-style.html#placing-braces-and-spaces

Others #

  • CONFIG_DESCRIPTION

    Kconfig symbols should have a help text which fully describes it.

  • CORRUPTED_PATCH

    The patch seems to be corrupted or lines are wrapped. Please regenerate the patch file before sending it to the maintainer.

  • CVS_KEYWORD

    Since linux moved to git, the CVS markers are no longer used. So, CVS style keywords ($Id$, $Revision$, $Log$) should not be added.

  • DEFAULT_NO_BREAK

    switch default case is sometimes written as "default:;". This can cause new cases added below default to be defective.

    A "break;" should be added after empty default statement to avoid unwanted fallthrough.

  • DOS_LINE_ENDINGS

    For DOS-formatted patches, there are extra ^M symbols at the end of the line. These should be removed.

  • DT_SCHEMA_BINDING_PATCH

    DT bindings moved to a json-schema based format instead of freeform text.

    See: https://www.kernel.org/doc/html/latest/devicetree/bindings/writing-schema.html

  • DT_SPLIT_BINDING_PATCH

    Devicetree bindings should be their own patch. This is because bindings are logically independent from a driver implementation, they have a different maintainer (even though they often are applied via the same tree), and it makes for a cleaner history in the DT only tree created with git-filter-branch.

    See: https://www.kernel.org/doc/html/latest/devicetree/bindings/submitting-patches.html#i-for-patch-submitters

  • EMBEDDED_FILENAME

    Embedding the complete filename path inside the file isn't particularly useful as often the path is moved around and becomes incorrect.

  • FILE_PATH_CHANGES

    Whenever files are added, moved, or deleted, the MAINTAINERS file patterns can be out of sync or outdated.

    So MAINTAINERS might need updating in these cases.

  • MEMSET

    The memset use appears to be incorrect. This may be caused due to badly ordered parameters. Please recheck the usage.

  • NOT_UNIFIED_DIFF

    The patch file does not appear to be in unified-diff format. Please regenerate the patch file before sending it to the maintainer.

  • PLACEHOLDER_USE

    Detects unhandled placeholder text left in cover letters or commit headers/logs. Common placeholders include lines like:

    *** SUBJECT HERE ***
    *** BLURB HERE ***
    

    These typically come from autogenerated templates. Replace them with a proper subject and description before sending.

  • PRINTF_0XDECIMAL

    Prefixing 0x with decimal output is defective and should be corrected.

  • SPDX_LICENSE_TAG

    The source file is missing or has an improper SPDX identifier tag. The Linux kernel requires the precise SPDX identifier in all source files, and it is thoroughly documented in the kernel docs.

    See: https://www.kernel.org/doc/html/latest/process/license-rules.html

  • TYPO_SPELLING

    Some words may have been misspelled. Consider reviewing them.

UAPI Checker

Peios Kernel / Kernel development / Development tools

The UAPI checker (scripts/check-uapi.sh) is a shell script which checks UAPI header files for userspace backwards-compatibility across the git tree.

Options #

This section will describe the options with which check-uapi.sh can be run.

Usage:

check-uapi.sh [-b BASE_REF] [-p PAST_REF] [-j N] [-l ERROR_LOG] [-i] [-q] [-v]

Available options:

-b BASE_REF    Base git reference to use for comparison. If unspecified or empty,
               will use any dirty changes in tree to UAPI files. If there are no
               dirty changes, HEAD will be used.
-p PAST_REF    Compare BASE_REF to PAST_REF (e.g. -p v6.1). If unspecified or empty,
               will use BASE_REF^1. Must be an ancestor of BASE_REF. Only headers
               that exist on PAST_REF will be checked for compatibility.
-j JOBS        Number of checks to run in parallel (default: number of CPU cores).
-l ERROR_LOG   Write error log to file (default: no error log is generated).
-i             Ignore ambiguous changes that may or may not break UAPI compatibility.
-q             Quiet operation.
-v             Verbose operation (print more information about each header being checked).

Environmental args:

ABIDIFF  Custom path to abidiff binary
CC       C compiler (default is "gcc")
ARCH     Target architecture of C compiler (default is host arch)

Exit codes:

0) Success
1) ABI difference detected
2) Prerequisite not met

Examples #

Basic Usage #

First, let's try making a change to a UAPI header file that obviously won't break userspace:

cat << 'EOF' | patch -l -p1
--- a/include/uapi/linux/acct.h
+++ b/include/uapi/linux/acct.h
@@ -21,7 +21,9 @@
 #include <asm/param.h>
 #include <asm/byteorder.h>

-/*
+#define FOO
+
+/*
  *  comp_t is a 16-bit "floating" point number with a 3-bit base 8
  *  exponent and a 13-bit fraction.
  *  comp2_t is 24-bit with 5-bit base 2 exponent and 20 bit fraction
diff --git a/include/uapi/linux/bpf.h b/include/uapi/linux/bpf.h
EOF

Now, let's use the script to validate:

% ./scripts/check-uapi.sh
Installing user-facing UAPI headers from dirty tree... OK
Installing user-facing UAPI headers from HEAD... OK
Checking changes to UAPI headers between HEAD and dirty tree...
All 912 UAPI headers compatible with x86 appear to be backwards compatible

Let's add another change that might break userspace:

cat << 'EOF' | patch -l -p1
--- a/include/uapi/linux/bpf.h
+++ b/include/uapi/linux/bpf.h
@@ -74,7 +74,7 @@ struct bpf_insn {
        __u8    dst_reg:4;      /* dest register */
        __u8    src_reg:4;      /* source register */
        __s16   off;            /* signed offset */
-       __s32   imm;            /* signed immediate constant */
+       __u32   imm;            /* unsigned immediate constant */
 };

 /* Key of an a BPF_MAP_TYPE_LPM_TRIE entry */
EOF

The script will catch this:

% ./scripts/check-uapi.sh
Installing user-facing UAPI headers from dirty tree... OK
Installing user-facing UAPI headers from HEAD... OK
Checking changes to UAPI headers between HEAD and dirty tree...
==== ABI differences detected in include/linux/bpf.h from HEAD -> dirty tree ====
    [C] 'struct bpf_insn' changed:
      type size hasn't changed
      1 data member change:
        type of '__s32 imm' changed:
          typedef name changed from __s32 to __u32 at int-ll64.h:27:1
          underlying type 'int' changed:
            type name changed from 'int' to 'unsigned int'
            type size hasn't changed
==================================================================================

error - 1/912 UAPI headers compatible with x86 appear _not_ to be backwards compatible

In this case, the script is reporting the type change because it could break a userspace program that passes in a negative number. Now, let's say you know that no userspace program could possibly be using a negative value in imm, so changing to an unsigned type there shouldn't hurt anything. You can pass the -i flag to the script to ignore changes in which the userspace backwards compatibility is ambiguous:

% ./scripts/check-uapi.sh -i
Installing user-facing UAPI headers from dirty tree... OK
Installing user-facing UAPI headers from HEAD... OK
Checking changes to UAPI headers between HEAD and dirty tree...
All 912 UAPI headers compatible with x86 appear to be backwards compatible

Now, let's make a similar change that will break userspace:

cat << 'EOF' | patch -l -p1
--- a/include/uapi/linux/bpf.h
+++ b/include/uapi/linux/bpf.h
@@ -71,8 +71,8 @@ enum {

 struct bpf_insn {
        __u8    code;           /* opcode */
-       __u8    dst_reg:4;      /* dest register */
        __u8    src_reg:4;      /* source register */
+       __u8    dst_reg:4;      /* dest register */
        __s16   off;            /* signed offset */
        __s32   imm;            /* signed immediate constant */
 };
EOF

Since we're re-ordering an existing struct member, there's no ambiguity, and the script will report the breakage even if you pass -i:

% ./scripts/check-uapi.sh -i
Installing user-facing UAPI headers from dirty tree... OK
Installing user-facing UAPI headers from HEAD... OK
Checking changes to UAPI headers between HEAD and dirty tree...
==== ABI differences detected in include/linux/bpf.h from HEAD -> dirty tree ====
    [C] 'struct bpf_insn' changed:
      type size hasn't changed
      2 data member changes:
        '__u8 dst_reg' offset changed from 8 to 12 (in bits) (by +4 bits)
        '__u8 src_reg' offset changed from 12 to 8 (in bits) (by -4 bits)
==================================================================================

error - 1/912 UAPI headers compatible with x86 appear _not_ to be backwards compatible

Let's commit the breaking change, then commit the innocuous change:

% git commit -m 'Breaking UAPI change' include/uapi/linux/bpf.h
[detached HEAD f758e574663a] Breaking UAPI change
 1 file changed, 1 insertion(+), 1 deletion(-)
% git commit -m 'Innocuous UAPI change' include/uapi/linux/acct.h
[detached HEAD 2e87df769081] Innocuous UAPI change
 1 file changed, 3 insertions(+), 1 deletion(-)

Now, let's run the script again with no arguments:

% ./scripts/check-uapi.sh
Installing user-facing UAPI headers from HEAD... OK
Installing user-facing UAPI headers from HEAD^1... OK
Checking changes to UAPI headers between HEAD^1 and HEAD...
All 912 UAPI headers compatible with x86 appear to be backwards compatible

It doesn't catch any breaking change because, by default, it only compares HEAD to HEAD^1. The breaking change was committed on HEAD~2. If we wanted the search scope to go back further, we'd have to use the -p option to pass a different past reference. In this case, let's pass -p HEAD~2 to the script so it checks UAPI changes between HEAD~2 and HEAD:

% ./scripts/check-uapi.sh -p HEAD~2
Installing user-facing UAPI headers from HEAD... OK
Installing user-facing UAPI headers from HEAD~2... OK
Checking changes to UAPI headers between HEAD~2 and HEAD...
==== ABI differences detected in include/linux/bpf.h from HEAD~2 -> HEAD ====
    [C] 'struct bpf_insn' changed:
      type size hasn't changed
      2 data member changes:
        '__u8 dst_reg' offset changed from 8 to 12 (in bits) (by +4 bits)
        '__u8 src_reg' offset changed from 12 to 8 (in bits) (by -4 bits)
==============================================================================

error - 1/912 UAPI headers compatible with x86 appear _not_ to be backwards compatible

Alternatively, we could have also run with -b HEAD~. This would set the base reference to HEAD~ so then the script would compare it to HEAD~^1.

Architecture-specific Headers #

Consider this change:

cat << 'EOF' | patch -l -p1
--- a/arch/arm64/include/uapi/asm/sigcontext.h
+++ b/arch/arm64/include/uapi/asm/sigcontext.h
@@ -70,6 +70,7 @@ struct sigcontext {
 struct _aarch64_ctx {
        __u32 magic;
        __u32 size;
+       __u32 new_var;
 };

 #define FPSIMD_MAGIC   0x46508001
EOF

This is a change to an arm64-specific UAPI header file. In this example, I'm running the script from an x86 machine with an x86 compiler, so, by default, the script only checks x86-compatible UAPI header files:

% ./scripts/check-uapi.sh
Installing user-facing UAPI headers from dirty tree... OK
Installing user-facing UAPI headers from HEAD... OK
No changes to UAPI headers were applied between HEAD and dirty tree

With an x86 compiler, we can't check header files in arch/arm64, so the script doesn't even try.

If we want to check the header file, we'll have to use an arm64 compiler and set ARCH accordingly:

% CC=aarch64-linux-gnu-gcc ARCH=arm64 ./scripts/check-uapi.sh
Installing user-facing UAPI headers from dirty tree... OK
Installing user-facing UAPI headers from HEAD... OK
Checking changes to UAPI headers between HEAD and dirty tree...
==== ABI differences detected in include/asm/sigcontext.h from HEAD -> dirty tree ====
    [C] 'struct _aarch64_ctx' changed:
      type size changed from 64 to 96 (in bits)
      1 data member insertion:
        '__u32 new_var', at offset 64 (in bits) at sigcontext.h:73:1
    -- snip --
    [C] 'struct zt_context' changed:
      type size changed from 128 to 160 (in bits)
      2 data member changes (1 filtered):
        '__u16 nregs' offset changed from 64 to 96 (in bits) (by +32 bits)
        '__u16 __reserved[3]' offset changed from 80 to 112 (in bits) (by +32 bits)
=======================================================================================

error - 1/884 UAPI headers compatible with arm64 appear _not_ to be backwards compatible

We can see with ARCH and CC set properly for the file, the ABI change is reported properly. Also notice that the total number of UAPI header files checked by the script changes. This is because the number of headers installed for arm64 platforms is different than x86.

Cross-Dependency Breakages #

Consider this change:

cat << 'EOF' | patch -l -p1
--- a/include/uapi/linux/types.h
+++ b/include/uapi/linux/types.h
@@ -52,7 +52,7 @@ typedef __u32 __bitwise __wsum;
 #define __aligned_be64 __be64 __attribute__((aligned(8)))
 #define __aligned_le64 __le64 __attribute__((aligned(8)))

-typedef unsigned __bitwise __poll_t;
+typedef unsigned short __bitwise __poll_t;

 #endif /*  __ASSEMBLY__ */
 #endif /* _UAPI_LINUX_TYPES_H */
EOF

Here, we're changing a typedef in types.h. This doesn't break a UAPI in types.h, but other UAPIs in the tree may break due to this change:

% ./scripts/check-uapi.sh
Installing user-facing UAPI headers from dirty tree... OK
Installing user-facing UAPI headers from HEAD... OK
Checking changes to UAPI headers between HEAD and dirty tree...
==== ABI differences detected in include/linux/eventpoll.h from HEAD -> dirty tree ====
    [C] 'struct epoll_event' changed:
      type size changed from 96 to 80 (in bits)
      2 data member changes:
        type of '__poll_t events' changed:
          underlying type 'unsigned int' changed:
            type name changed from 'unsigned int' to 'unsigned short int'
            type size changed from 32 to 16 (in bits)
        '__u64 data' offset changed from 32 to 16 (in bits) (by -16 bits)
========================================================================================
include/linux/eventpoll.h did not change between HEAD and dirty tree...
It's possible a change to one of the headers it includes caused this error:
#include <linux/fcntl.h>
#include <linux/types.h>

Note that the script noticed the failing header file did not change, so it assumes one of its includes must have caused the breakage. Indeed, we can see linux/types.h is used from eventpoll.h.

UAPI Header Removals #

Consider this change:

cat << 'EOF' | patch -l -p1
diff --git a/include/uapi/asm-generic/Kbuild b/include/uapi/asm-generic/Kbuild
index ebb180aac74e..a9c88b0a8b3b 100644
--- a/include/uapi/asm-generic/Kbuild
+++ b/include/uapi/asm-generic/Kbuild
@@ -31,6 +31,6 @@ mandatory-y += stat.h
 mandatory-y += statfs.h
 mandatory-y += swab.h
 mandatory-y += termbits.h
-mandatory-y += termios.h
+#mandatory-y += termios.h
 mandatory-y += types.h
 mandatory-y += unistd.h
EOF

This script removes a UAPI header file from the install list. Let's run the script:

% ./scripts/check-uapi.sh
Installing user-facing UAPI headers from dirty tree... OK
Installing user-facing UAPI headers from HEAD... OK
Checking changes to UAPI headers between HEAD and dirty tree...
==== UAPI header include/asm/termios.h was removed between HEAD and dirty tree ====

error - 1/912 UAPI headers compatible with x86 appear _not_ to be backwards compatible

Removing a UAPI header is considered a breaking change, and the script will flag it as such.

Checking Historic UAPI Compatibility #

You can use the -b and -p options to examine different chunks of your git tree. For example, to check all changed UAPI header files between tags v6.0 and v6.1, you'd run:

% ./scripts/check-uapi.sh -b v6.1 -p v6.0
Installing user-facing UAPI headers from v6.1... OK
Installing user-facing UAPI headers from v6.0... OK
Checking changes to UAPI headers between v6.0 and v6.1...

--- snip ---
error - 37/907 UAPI headers compatible with x86 appear _not_ to be backwards compatible

Note: Before v5.3, a header file needed by the script is not present, so the script is unable to check changes before then.

You'll notice that the script detected many UAPI changes that are not backwards compatible. Knowing that kernel UAPIs are supposed to be stable forever, this is an alarming result. This brings us to the next section: caveats.

Caveats #

The UAPI checker makes no assumptions about the author's intention, so some types of changes may be flagged even though they intentionally break UAPI.

Removals For Refactoring or Deprecation #

Sometimes drivers for very old hardware are removed, such as in this example:

% ./scripts/check-uapi.sh -b ba47652ba655
Installing user-facing UAPI headers from ba47652ba655... OK
Installing user-facing UAPI headers from ba47652ba655^1... OK
Checking changes to UAPI headers between ba47652ba655^1 and ba47652ba655...
==== UAPI header include/linux/meye.h was removed between ba47652ba655^1 and ba47652ba655 ====

error - 1/910 UAPI headers compatible with x86 appear _not_ to be backwards compatible

The script will always flag removals (even if they're intentional).

Struct Expansions #

Depending on how a structure is handled in kernelspace, a change which expands a struct could be non-breaking.

If a struct is used as the argument to an ioctl, then the kernel driver must be able to handle ioctl commands of any size. Beyond that, you need to be careful when copying data from the user. Say, for example, that struct foo is changed like this:

struct foo {
    __u64 a; /* added in version 1 */
+   __u32 b; /* added in version 2 */
+   __u32 c; /* added in version 2 */
}

By default, the script will flag this kind of change for further review:

[C] 'struct foo' changed:
  type size changed from 64 to 128 (in bits)
  2 data member insertions:
    '__u32 b', at offset 64 (in bits)
    '__u32 c', at offset 96 (in bits)

However, it is possible that this change was made safely.

If a userspace program was built with version 1, it will think sizeof(struct foo) is 8. That size will be encoded in the ioctl value that gets sent to the kernel. If the kernel is built with version 2, it will think the sizeof(struct foo) is 16.

The kernel can use the _IOC_SIZE macro to get the size encoded in the ioctl code that the user passed in and then use copy_struct_from_user() to safely copy the value:

int handle_ioctl(unsigned long cmd, unsigned long arg)
{
    switch _IOC_NR(cmd) {
    0x01: {
        struct foo my_cmd;  /* size 16 in the kernel */

        ret = copy_struct_from_user(&my_cmd, arg, sizeof(struct foo), _IOC_SIZE(cmd));
        ...

copy_struct_from_user will zero the struct in the kernel and then copy only the bytes passed in from the user (leaving new members zeroized). If the user passed in a larger struct, the extra members are ignored.

If you know this situation is accounted for in the kernel code, you can pass -i to the script, and struct expansions like this will be ignored.

Flex Array Migration #

While the script handles expansion into an existing flex array, it does still flag initial migration to flex arrays from 1-element fake flex arrays. For example:

struct foo {
      __u32 x;
-     __u32 flex[1]; /* fake flex */
+     __u32 flex[];  /* real flex */
};

This change would be flagged by the script:

[C] 'struct foo' changed:
  type size changed from 64 to 32 (in bits)
  1 data member change:
    type of '__u32 flex[1]' changed:
      type name changed from '__u32[1]' to '__u32[]'
      array type size changed from 32 to 'unknown'
      array type subrange 1 changed length from 1 to 'unknown'

At this time, there's no way to filter these types of changes, so be aware of this possible false positive.

Summary #

While many types of false positives are filtered out by the script, it's possible there are some cases where the script flags a change which does not break UAPI. It's also possible a change which does break userspace would not be flagged by this script. While the script has been run on much of the kernel history, there could still be corner cases that are not accounted for.

The intention is for this script to be used as a quick check for maintainers or automated tooling, not as the end-all authority on patch compatibility. It's best to remember: use your best judgment (and ideally a unit test in userspace) to make sure your UAPI changes are backwards-compatible!

clang-format

Peios Kernel / Kernel development / Development tools

clang-format is a tool to format C/C++/... code according to a set of rules and heuristics. Like most tools, it is not perfect nor covers every single case, but it is good enough to be helpful.

clang-format can be used for several purposes:

  • Quickly reformat a block of code to the kernel style. Specially useful when moving code around and aligning/sorting. See clangformatreformat.

  • Spot style mistakes, typos and possible improvements in files you maintain, patches you review, diffs, etc. See clangformatreview.

  • Help you follow the coding style rules, specially useful for those new to kernel development or working at the same time in several projects with different coding styles.

Its configuration file is .clang-format in the root of the kernel tree. The rules contained there try to approximate the most common kernel coding style. They also try to follow Documentation/process/coding-style.rst as much as possible. Since not all the kernel follows the same style, it is possible that you may want to tweak the defaults for a particular subsystem or folder. To do so, you can override the defaults by writing another .clang-format file in a subfolder.

The tool itself has already been included in the repositories of popular Linux distributions for a long time. Search for clang-format in your repositories. Otherwise, you can either download pre-built LLVM/clang binaries or build the source code from:

https://releases.llvm.org/download.html

See more information about the tool at:

https://clang.llvm.org/docs/ClangFormat.html

https://clang.llvm.org/docs/ClangFormatStyleOptions.html

Review files and patches for coding style #

By running the tool in its inline mode, you can review full subsystems, folders or individual files for code style mistakes, typos or improvements.

To do so, you can run something like:

# Make sure your working directory is clean!
clang-format -i kernel/*.[ch]

And then take a look at the git diff.

Counting the lines of such a diff is also useful for improving/tweaking the style options in the configuration file; as well as testing new clang-format features/versions.

clang-format also supports reading unified diffs, so you can review patches and git diffs easily. See the documentation at:

https://clang.llvm.org/docs/ClangFormat.html#script-for-patch-reformatting

To avoid clang-format formatting some portion of a file, you can do:

int formatted_code;
// clang-format off
    void    unformatted_code  ;
// clang-format on
void formatted_code_again;

While it might be tempting to use this to keep a file always in sync with clang-format, specially if you are writing new files or if you are a maintainer, please note that people might be running different clang-format versions or not have it available at all. Therefore, you should probably refrain yourself from using this in kernel sources; at least until we see if clang-format becomes commonplace.

Reformatting blocks of code #

By using an integration with your text editor, you can reformat arbitrary blocks (selections) of code with a single keystroke. This is specially useful when moving code around, for complex code that is deeply indented, for multi-line macros (and aligning their backslashes), etc.

Remember that you can always tweak the changes afterwards in those cases where the tool did not do an optimal job. But as a first approximation, it can be very useful.

There are integrations for many popular text editors. For some of them, like vim, emacs, BBEdit and Visual Studio you can find support built-in. For instructions, read the appropriate section at:

https://clang.llvm.org/docs/ClangFormat.html

For Atom, Eclipse, Sublime Text, Visual Studio Code, XCode and other editors and IDEs you should be able to find ready-to-use plugins.

For this use case, consider using a secondary .clang-format so that you can tweak a few options. See clangformatextra.

Missing support #

clang-format is missing support for some things that are common in kernel code. They are easy to remember, so if you use the tool regularly, you will quickly learn to avoid/ignore those.

In particular, some very common ones you will notice are:

  • Aligned blocks of one-line #defines, e.g.:

    #define TRACING_MAP_BITS_DEFAULT       11
    #define TRACING_MAP_BITS_MAX           17
    #define TRACING_MAP_BITS_MIN           7
    

    vs.:

    #define TRACING_MAP_BITS_DEFAULT 11
    #define TRACING_MAP_BITS_MAX 17
    #define TRACING_MAP_BITS_MIN 7
    
  • Aligned designated initializers, e.g.:

    static const struct file_operations uprobe_events_ops = {
            .owner          = THIS_MODULE,
            .open           = probes_open,
            .read           = seq_read,
            .llseek         = seq_lseek,
            .release        = seq_release,
            .write          = probes_write,
    };
    

    vs.:

    static const struct file_operations uprobe_events_ops = {
            .owner = THIS_MODULE,
            .open = probes_open,
            .read = seq_read,
            .llseek = seq_lseek,
            .release = seq_release,
            .write = probes_write,
    };
    

Extra features/options #

Some features/style options are not enabled by default in the configuration file in order to minimize the differences between the output and the current code. In other words, to make the difference as small as possible, which makes reviewing full-file style, as well diffs and patches as easy as possible.

In other cases (e.g. particular subsystems/folders/files), the kernel style might be different and enabling some of these options may approximate better the style there.

For instance:

  • Aligning assignments (AlignConsecutiveAssignments).

  • Aligning declarations (AlignConsecutiveDeclarations).

  • Reflowing text in comments (ReflowComments).

  • Sorting #includes (SortIncludes).

They are typically useful for block re-formatting, rather than full-file. You might want to create another .clang-format file and use that one from your editor/IDE instead.

Coccinelle

Peios Kernel / Kernel development / Development tools

Coccinelle is a tool for pattern matching and text transformation that has many uses in kernel development, including the application of complex, tree-wide patches and detection of problematic programming patterns.

Getting Coccinelle #

The semantic patches included in the kernel use features and options which are provided by Coccinelle version 1.0.0-rc11 and above. Using earlier versions will fail as the option names used by the Coccinelle files and coccicheck have been updated.

Coccinelle is available through the package manager of many distributions, e.g. :

  • Debian

  • Fedora

  • Ubuntu

  • OpenSUSE

  • Arch Linux

  • NetBSD

  • FreeBSD

Some distribution packages are obsolete and it is recommended to use the latest version released from the Coccinelle homepage at http://coccinelle.lip6.fr/

Or from Github at:

https://github.com/coccinelle/coccinelle

Once you have it, run the following commands:

./autogen
./configure
make

as a regular user, and install it with:

sudo make install

More detailed installation instructions to build from source can be found at:

https://github.com/coccinelle/coccinelle/blob/master/install.txt

Supplemental documentation #

For supplemental documentation refer to the wiki:

https://bottest.wiki.kernel.org/coccicheck

The wiki documentation always refers to the linux-next version of the script.

For Semantic Patch Language(SmPL) grammar documentation refer to:

https://coccinelle.gitlabpages.inria.fr/website/docs/main_grammar.html

Using Coccinelle on the Linux kernel #

A Coccinelle-specific target is defined in the top level Makefile. This target is named coccicheck and calls the coccicheck front-end in the scripts directory.

Four basic modes are defined: patch, report, context, and org. The mode to use is specified by setting the MODE variable with MODE=<mode>.

  • patch proposes a fix, when possible.

  • report generates a list in the following format: file:line:column-column: message

  • context highlights lines of interest and their context in a diff-like style. Lines of interest are indicated with -.

  • org generates a report in the Org mode format of Emacs.

Note that not all semantic patches implement all modes. For easy use of Coccinelle, the default mode is "report".

Two other modes provide some common combinations of these modes.

  • chain tries the previous modes in the order above until one succeeds.

  • rep+ctxt runs successively the report mode and the context mode. It should be used with the C option (described later) which checks the code on a file basis.

Examples #

To make a report for every semantic patch, run the following command:

make coccicheck MODE=report

To produce patches, run:

make coccicheck MODE=patch

The coccicheck target applies every semantic patch available in the sub-directories of scripts/coccinelle to the entire Linux kernel.

For each semantic patch, a commit message is proposed. It gives a description of the problem being checked by the semantic patch, and includes a reference to Coccinelle.

As with any static code analyzer, Coccinelle produces false positives. Thus, reports must be carefully checked, and patches reviewed.

To enable verbose messages set the V= variable, for example:

make coccicheck MODE=report V=1

By default, coccicheck will print debug logs to stdout and redirect stderr to /dev/null. This can make coccicheck output difficult to read and understand. Debug and error messages can instead be written to a debug file instead by setting the DEBUG_FILE variable:

make coccicheck MODE=report DEBUG_FILE="cocci.log"

Coccinelle cannot overwrite a debug file. Instead of repeatedly deleting a log file, you could include the datetime in the debug file name:

make coccicheck MODE=report DEBUG_FILE="cocci-$(date -Iseconds).log"

Coccinelle parallelization #

By default, coccicheck tries to run as parallel as possible. To change the parallelism, set the J= variable. For example, to run across 4 CPUs:

make coccicheck MODE=report J=4

As of Coccinelle 1.0.2 Coccinelle uses Ocaml parmap for parallelization; if support for this is detected you will benefit from parmap parallelization.

When parmap is enabled coccicheck will enable dynamic load balancing by using --chunksize 1 argument. This ensures we keep feeding threads with work one by one, so that we avoid the situation where most work gets done by only a few threads. With dynamic load balancing, if a thread finishes early we keep feeding it more work.

When parmap is enabled, if an error occurs in Coccinelle, this error value is propagated back, and the return value of the make coccicheck command captures this return value.

Using Coccinelle with a single semantic patch #

The optional make variable COCCI can be used to check a single semantic patch. In that case, the variable must be initialized with the name of the semantic patch to apply.

For instance:

make coccicheck COCCI=<my_SP.cocci> MODE=patch

or:

make coccicheck COCCI=<my_SP.cocci> MODE=report

Controlling Which Files are Processed by Coccinelle #

By default the entire kernel source tree is checked.

To apply Coccinelle to a specific directory, M= can be used. For example, to check drivers/net/wireless/ one may write:

make coccicheck M=drivers/net/wireless/

To apply Coccinelle on a file basis, instead of a directory basis, the C variable is used by the makefile to select which files to work with. This variable can be used to run scripts for the entire kernel, a specific directory, or for a single file.

For example, to check drivers/bluetooth/bfusb.c, the value 1 is passed to the C variable to check files that make considers need to be compiled.:

make C=1 CHECK=scripts/coccicheck drivers/bluetooth/bfusb.o

The value 2 is passed to the C variable to check files regardless of whether they need to be compiled or not.:

make C=2 CHECK=scripts/coccicheck drivers/bluetooth/bfusb.o

In these modes, which work on a file basis, there is no information about semantic patches displayed, and no commit message proposed.

This runs every semantic patch in scripts/coccinelle by default. The COCCI variable may additionally be used to only apply a single semantic patch as shown in the previous section.

The "report" mode is the default. You can select another one with the MODE variable explained above.

Debugging Coccinelle SmPL patches #

Using coccicheck is best as it provides in the spatch command line include options matching the options used when we compile the kernel. You can learn what these options are by using V=1; you could then manually run Coccinelle with debug options added.

An easier approach to debug running Coccinelle against SmPL patches is to ask coccicheck to redirect stderr to a debug file. As mentioned in the examples, by default stderr is redirected to /dev/null; if you'd like to capture stderr you can specify the DEBUG_FILE="file.txt" option to coccicheck. For instance:

rm -f cocci.err
make coccicheck COCCI=scripts/coccinelle/free/kfree.cocci MODE=report DEBUG_FILE=cocci.err
cat cocci.err

You can use SPFLAGS to add debugging flags; for instance you may want to add both --profile --show-trying to SPFLAGS when debugging. For example you may want to use:

rm -f err.log
export COCCI=scripts/coccinelle/misc/irqf_oneshot.cocci
make coccicheck DEBUG_FILE="err.log" MODE=report SPFLAGS="--profile --show-trying" M=./drivers/mfd

err.log will now have the profiling information, while stdout will provide some progress information as Coccinelle moves forward with work.

NOTE:

DEBUG_FILE support is only supported when using coccinelle >= 1.0.2.

Currently, DEBUG_FILE support is only available to check folders, and not single files. This is because checking a single file requires spatch to be called twice leading to DEBUG_FILE being set both times to the same value, giving rise to an error.

.cocciconfig support #

Coccinelle supports reading .cocciconfig for default Coccinelle options that should be used every time spatch is spawned. The order of precedence for variables for .cocciconfig is as follows:

  • Your current user's home directory is processed first

  • Your directory from which spatch is called is processed next

  • The directory provided with the --dir option is processed last, if used

make coccicheck also supports using M= targets. If you do not supply any M= target, it is assumed you want to target the entire kernel. The kernel coccicheck script has:

OPTIONS="--dir $srcroot $COCCIINCLUDE"

Here, $srcroot refers to the source directory of the target: it points to the external module's source directory when M= used, and otherwise, to the kernel source directory. The third rule ensures the spatch reads the .cocciconfig from the target directory, allowing external modules to have their own .cocciconfig file.

If not using the kernel's coccicheck target, keep the above precedence order logic of .cocciconfig reading. If using the kernel's coccicheck target, override any of the kernel's .coccicheck's settings using SPFLAGS.

We help Coccinelle when used against Linux with a set of sensible default options for Linux with our own Linux .cocciconfig. This hints to coccinelle that git can be used for git grep queries over coccigrep. A timeout of 200 seconds should suffice for now.

The options picked up by coccinelle when reading a .cocciconfig do not appear as arguments to spatch processes running on your system. To confirm what options will be used by Coccinelle run:

spatch --print-options-only

You can override with your own preferred index option by using SPFLAGS. Take note that when there are conflicting options Coccinelle takes precedence for the last options passed. Using .cocciconfig is possible to use idutils, however given the order of precedence followed by Coccinelle, since the kernel now carries its own .cocciconfig, you will need to use SPFLAGS to use idutils if desired. See below section "Additional flags" for more details on how to use idutils.

Additional flags #

Additional flags can be passed to spatch through the SPFLAGS variable. This works as Coccinelle respects the last flags given to it when options are in conflict.

make SPFLAGS=--use-glimpse coccicheck

Coccinelle supports idutils as well but requires coccinelle >= 1.0.6. When no ID file is specified coccinelle assumes your ID database file is in the file .id-utils.index on the top level of the kernel. Coccinelle carries a script scripts/idutils_index.sh which creates the database with:

mkid -i C --output .id-utils.index

If you have another database filename you can also just symlink with this name.

make SPFLAGS=--use-idutils coccicheck

Alternatively you can specify the database filename explicitly, for instance:

make SPFLAGS="--use-idutils /full-path/to/ID" coccicheck

See spatch --help to learn more about spatch options.

Note that the --use-glimpse and --use-idutils options require external tools for indexing the code. None of them is thus active by default. However, by indexing the code with one of these tools, and according to the cocci file used, spatch could proceed the entire code base more quickly.

SmPL patch specific options #

SmPL patches can have their own requirements for options passed to Coccinelle. SmPL patch-specific options can be provided by providing them at the top of the SmPL patch, for instance:

// Options: --no-includes --include-headers

SmPL patch Coccinelle requirements #

As Coccinelle features get added some more advanced SmPL patches may require newer versions of Coccinelle. If an SmPL patch requires a minimum version of Coccinelle, this can be specified as follows, as an example if requiring at least Coccinelle >= 1.0.5:

// Requires: 1.0.5

Proposing new semantic patches #

New semantic patches can be proposed and submitted by kernel developers. For sake of clarity, they should be organized in the sub-directories of scripts/coccinelle/.

Detailed description of the report mode #

report generates a list in the following format:

file:line:column-column: message

Example #

Running:

make coccicheck MODE=report COCCI=scripts/coccinelle/api/err_cast.cocci

will execute the following part of the SmPL script:

<smpl>
@r depends on !context && !patch && (org || report)@
expression x;
position p;
@@

  ERR_PTR@p(PTR_ERR(x))

@script:python depends on report@
p << r.p;
x << r.x;
@@

msg="ERR_CAST can be used with %s" % (x)
coccilib.report.print_report(p[0], msg)
</smpl>

This SmPL excerpt generates entries on the standard output, as illustrated below:

/home/user/linux/crypto/ctr.c:188:9-16: ERR_CAST can be used with alg
/home/user/linux/crypto/authenc.c:619:9-16: ERR_CAST can be used with auth
/home/user/linux/crypto/xts.c:227:9-16: ERR_CAST can be used with alg

Detailed description of the patch mode #

When the patch mode is available, it proposes a fix for each problem identified.

Example #

Running:

make coccicheck MODE=patch COCCI=scripts/coccinelle/api/err_cast.cocci

will execute the following part of the SmPL script:

<smpl>
@ depends on !context && patch && !org && !report @
expression x;
@@

- ERR_PTR(PTR_ERR(x))
+ ERR_CAST(x)
</smpl>

This SmPL excerpt generates patch hunks on the standard output, as illustrated below:

diff -u -p a/crypto/ctr.c b/crypto/ctr.c
--- a/crypto/ctr.c 2010-05-26 10:49:38.000000000 +0200
+++ b/crypto/ctr.c 2010-06-03 23:44:49.000000000 +0200
@@ -185,7 +185,7 @@ static struct crypto_instance *crypto_ct
    alg = crypto_attr_alg(tb[1], CRYPTO_ALG_TYPE_CIPHER,
                              CRYPTO_ALG_TYPE_MASK);
    if (IS_ERR(alg))
-           return ERR_PTR(PTR_ERR(alg));
+           return ERR_CAST(alg);

    /* Block size must be >= 4 bytes. */
    err = -EINVAL;

Detailed description of the context mode #

context highlights lines of interest and their context in a diff-like style.

NOTE: The diff-like output generated is NOT an applicable patch. The intent of the context mode is to highlight the important lines (annotated with minus, -) and gives some surrounding context lines around. This output can be used with the diff mode of Emacs to review the code.

Example #

Running:

make coccicheck MODE=context COCCI=scripts/coccinelle/api/err_cast.cocci

will execute the following part of the SmPL script:

<smpl>
@ depends on context && !patch && !org && !report@
expression x;
@@

* ERR_PTR(PTR_ERR(x))
</smpl>

This SmPL excerpt generates diff hunks on the standard output, as illustrated below:

diff -u -p /home/user/linux/crypto/ctr.c /tmp/nothing
--- /home/user/linux/crypto/ctr.c   2010-05-26 10:49:38.000000000 +0200
+++ /tmp/nothing
@@ -185,7 +185,6 @@ static struct crypto_instance *crypto_ct
    alg = crypto_attr_alg(tb[1], CRYPTO_ALG_TYPE_CIPHER,
                              CRYPTO_ALG_TYPE_MASK);
    if (IS_ERR(alg))
-           return ERR_PTR(PTR_ERR(alg));

    /* Block size must be >= 4 bytes. */
    err = -EINVAL;

Detailed description of the org mode #

org generates a report in the Org mode format of Emacs.

Example #

Running:

make coccicheck MODE=org COCCI=scripts/coccinelle/api/err_cast.cocci

will execute the following part of the SmPL script:

<smpl>
@r depends on !context && !patch && (org || report)@
expression x;
position p;
@@

  ERR_PTR@p(PTR_ERR(x))

@script:python depends on org@
p << r.p;
x << r.x;
@@

msg="ERR_CAST can be used with %s" % (x)
msg_safe=msg.replace("[","@(").replace("]",")")
coccilib.org.print_todo(p[0], msg_safe)
</smpl>

This SmPL excerpt generates Org entries on the standard output, as illustrated below:

* TODO [[view:/home/user/linux/crypto/ctr.c::face=ovl-face1::linb=188::colb=9::cole=16][ERR_CAST can be used with alg]]
* TODO [[view:/home/user/linux/crypto/authenc.c::face=ovl-face1::linb=619::colb=9::cole=16][ERR_CAST can be used with auth]]
* TODO [[view:/home/user/linux/crypto/xts.c::face=ovl-face1::linb=227::colb=9::cole=16][ERR_CAST can be used with alg]]

Containerized Builds

Peios Kernel / Kernel development / Development tools

The container tool can be used to run any command in the kernel source tree from within a container. Doing so facilitates reproducing builds across various platforms, for example when a test bot has reported an issue which requires a specific version of a compiler or an external test suite. While this can already be done by users who are familiar with containers, having a dedicated tool in the kernel tree lowers the barrier to entry by solving common problems once and for all (e.g. user id management). It also makes it easier to share an exact command line leading to a particular result. The main use case is likely to be kernel builds but virtually anything can be run: KUnit, checkpatch etc. provided a suitable image is available.

Options #

Command line syntax:

scripts/container -i IMAGE [OPTION]... CMD...

Available options:

-e, --env-file ENV_FILE

Path to an environment file to load in the container.

-g, --gid GID

Group id to use inside the container.

-i, --image IMAGE

Container image name (required).

-r, --runtime RUNTIME

Container runtime name. Supported runtimes: docker, podman.

If not specified, the first one found on the system will be used i.e. Podman if present, otherwise Docker.

-s, --shell

Run the container in an interactive shell.

-u, --uid UID

User id to use inside the container.

If the -g option is not specified, the user id will also be used for the group id.

-v, --verbose

Enable verbose output.

-h, --help

Show the help message and exit.

Usage #

It's entirely up to the user to choose which image to use and the CMD arguments are passed directly as an arbitrary command line to run in the container. The tool will take care of mounting the source tree as the current working directory and adjust the user and group id as needed.

The container image which would typically include a compiler toolchain is provided by the user and selected via the -i option. The container runtime can be selected with the -r option, which can be either docker or podman. If none is specified, the first one found on the system will be used while giving priority to Podman. Support for other runtimes may be added later depending on their popularity among users.

By default, commands are run non-interactively. The user can abort a running container with SIGINT (Ctrl-C). To run commands interactively with a TTY, the --shell or -s option can be used. Signals will then be received by the shell directly rather than the parent container process. To exit an interactive shell, use Ctrl-D or exit.

Note

The only host requirement aside from a container runtime is Python 3.10 or later.

Note

Out-of-tree builds are not fully supported yet. The O= option can however already be used with a relative path inside the source tree to keep separate build outputs. A workaround to build outside the tree is to use mount --bind, see the examples section further down.

Environment Variables #

Environment variables are not propagated to the container so they have to be either defined in the image itself or via the -e option using an environment file. In some cases it makes more sense to have them defined in the Containerfile used to create the image. For example, a Clang-only compiler toolchain image may have LLVM=1 defined.

The local environment file is more useful for user-specific variables added during development. It is passed as-is to the container runtime so its format may vary. Typically, it will look like the output of env. For example:

INSTALL_MOD_STRIP=1
SOME_RANDOM_TEXT=One upon a time

Please also note that make options can still be passed on the command line, so while this can't be done since the first argument needs to be the executable:

scripts/container -i docker.io/tuxmake/korg-clang LLVM=1 make  # won't work

this will work:

scripts/container -i docker.io/tuxmake/korg-clang make LLVM=1

User IDs #

This is an area where the behaviour will vary slightly depending on the container runtime. The goal is to run commands as the user invoking the tool. With Podman, a namespace is created to map the current user id to a different one in the container (1000 by default). With Docker, while this is also possible with recent versions it requires a special feature to be enabled in the daemon so it's not used here for simplicity. Instead, the container is run with the current user id directly. In both cases, this will provide the same file permissions for the kernel source tree mounted as a volume. The only difference is that when using Docker without a namespace, the user id may not be the same as the default one set in the image.

Say, we're using an image which sets up a default user with id 1000 and the current user calling the container tool has id 1234. The kernel source tree was checked out by this same user so the files belong to user 1234. With Podman, the container will be running as user id 1000 with a mapping to id 1234 so that the files from the mounted volume appear to belong to id 1000 inside the container. With Docker and no namespace, the container will be running with user id 1234 which can access the files in the volume but not in the user 1000 home directory. This shouldn't be an issue when running commands only in the kernel tree but it is worth highlighting here as it might matter for special corner cases.

Note

Podman's Docker compatibility mode to run docker commands on top of a Podman backend is more complex and not fully supported yet. As such, Podman will take priority if both runtimes are available on the system.

Examples #

The TuxMake project provides a variety of prebuilt container images available on Docker Hub. Here's the shortest example to build a kernel using a TuxMake Clang image:

scripts/container -i docker.io/tuxmake/korg-clang -- make LLVM=1 defconfig
scripts/container -i docker.io/tuxmake/korg-clang -- make LLVM=1 -j$(nproc)

Note

When running a command with options within the container, it should be separated with a double dash -- to not confuse them with the container tool options. Plain commands with no options don't strictly require the double dashes e.g.:

scripts/container -i docker.io/tuxmake/korg-clang make mrproper

To run checkpatch.pl in a patches directory with a generic Perl image:

scripts/container -i perl:slim-trixie scripts/checkpatch.pl patches/*

As an alternative to the TuxMake images, the examples below refer to kernel.org images which are based on the kernel.org compiler toolchains. These aren't (yet) officially available in any public registry but users can build their own locally instead using this experimental repository by running make PREFIX=kernel.org/.

To build just bzImage using Clang:

scripts/container -i kernel.org/clang -- make bzImage -j$(nproc)

Same with GCC 15 as a particular version tag:

scripts/container -i kernel.org/gcc:15 -- make bzImage -j$(nproc)

For an out-of-tree build, a trick is to bind-mount the destination directory to a relative path inside the source tree:

mkdir -p $HOME/tmp/my-kernel-build
mkdir -p build
sudo mount --bind $HOME/tmp/my-kernel-build build
scripts/container -i kernel.org/gcc -- make mrproper
scripts/container -i kernel.org/gcc -- make O=build defconfig
scripts/container -i kernel.org/gcc -- make O=build -j$(nproc)

To run KUnit in an interactive shell and get the full output:

scripts/container -s -i kernel.org/gcc:kunit -- \
    tools/testing/kunit/kunit.py \
        run \
        --arch=x86_64 \
        --cross_compile=x86_64-linux-

To just start an interactive shell:

scripts/container -si kernel.org/gcc bash

To build the HTML documentation, which requires the kdocs image built with make PREFIX=kernel.org/ extra as it's not a compiler toolchain:

scripts/container -i kernel.org/kdocs make htmldocs

Compiler-Based Context Analysis

Peios Kernel / Kernel development / Development tools

Context Analysis is a language extension, which enables statically checking that required contexts are active (or inactive) by acquiring and releasing user-definable "context locks". An obvious application is lock-safety checking for the kernel's various synchronization primitives (each of which represents a "context lock"), and checking that locking rules are not violated.

The Clang compiler currently supports the full set of context analysis features. To enable for Clang, configure the kernel with:

CONFIG_WARN_CONTEXT_ANALYSIS=y

The feature requires Clang 22 or later.

The analysis is opt-in by default, and requires declaring which modules and subsystems should be analyzed in the respective Makefile:

CONTEXT_ANALYSIS_mymodule.o := y

Or for all translation units in the directory:

CONTEXT_ANALYSIS := y

It is possible to enable the analysis tree-wide, however, which will result in numerous false positive warnings currently and is not generally recommended:

CONFIG_WARN_CONTEXT_ANALYSIS_ALL=y

Programming Model #

The below describes the programming model around using context lock types.

Note

Enabling context analysis can be seen as enabling a dialect of Linux C with a Context System. Some valid patterns involving complex control-flow are constrained (such as conditional acquisition and later conditional release in the same function).

Context analysis is a way to specify permissibility of operations to depend on context locks being held (or not held). Typically we are interested in protecting data and code in a critical section by requiring a specific context to be active, for example by holding a specific lock. The analysis ensures that callers cannot perform an operation without the required context being active.

Context locks are associated with named structs, along with functions that operate on struct instances to acquire and release the associated context lock.

Context locks can be held either exclusively or shared. This mechanism allows assigning more precise privileges when a context is active, typically to distinguish where a thread may only read (shared) or also write (exclusive) to data guarded within a context.

The set of contexts that are actually active in a given thread at a given point in program execution is a run-time concept. The static analysis works by calculating an approximation of that set, called the context environment. The context environment is calculated for every program point, and describes the set of contexts that are statically known to be active, or inactive, at that particular point. This environment is a conservative approximation of the full set of contexts that will actually be active in a thread at run-time.

More details are also documented here.

Note

Clang's analysis explicitly does not infer context locks acquired or released by inline functions. It requires explicit annotations to (a) assert that it's not a bug if a context lock is released or acquired, and (b) to retain consistency between inline and non-inline function declarations.

Supported Kernel Primitives #

Currently the following synchronization primitives are supported: raw_spinlock_t, spinlock_t, rwlock_t, mutex, seqlock_t, bit_spinlock, RCU, SRCU (srcu_struct), rw_semaphore, local_lock_t, ww_mutex.

To initialize variables guarded by a context lock with an initialization function (type_init(&lock)), prefer using guard(type_init)(&lock) or scoped_guard(type_init, &lock) { ... } to initialize such guarded members or globals in the enclosing scope. This initializes the context lock and treats the context as active within the initialization scope (initialization implies exclusive access to the underlying object).

For example:

struct my_data {
        spinlock_t lock;
        int counter __guarded_by(&lock);
};

void init_my_data(struct my_data *d)
{
        ...
        guard(spinlock_init)(&d->lock);
        d->counter = 0;
        ...
}

Alternatively, initializing guarded variables can be done with context analysis disabled, preferably in the smallest possible scope (due to lack of any other checking): either with a context_unsafe(var = init) expression, or by marking small initialization functions with the __context_unsafe(init) attribute.

Lockdep assertions, such as lockdep_assert_held(), inform the compiler's context analysis that the associated synchronization primitive is held after the assertion. This avoids false positives in complex control-flow scenarios and encourages the use of Lockdep where static analysis is limited. For example, this is useful when a function doesn't always require a lock, making __must_hold() inappropriate.

Keywords #

__guarded_by() #

__guarded_by(...)

struct member and globals attribute, declares variable only accessible within active context

Parameters

  • ...: variable arguments

Description

Declares that the struct member or global variable is only accessible within the context entered by the given context lock. Read operations on the data require shared access, while write operations require exclusive access.

struct some_state {
        spinlock_t lock;
        long counter __guarded_by(&lock);
};

__pt_guarded_by() #

__pt_guarded_by(...)

struct member and globals attribute, declares pointed-to data only accessible within active context

Parameters

  • ...: variable arguments

Description

Declares that the data pointed to by the struct member pointer or global pointer is only accessible within the context entered by the given context lock. Read operations on the data require shared access, while write operations require exclusive access.

struct some_state {
        spinlock_t lock;
        long *counter __pt_guarded_by(&lock);
};

context_lock_struct() #

context_lock_struct(name, ...)

declare or define a context lock struct

Parameters

  • name: struct name
  • ...: variable arguments

Description

Helper to declare or define a struct type that is also a context lock.

context_lock_struct(my_handle) {
        int foo;
        long bar;
};

struct some_state {
        ...
};
// ... declared elsewhere ...
context_lock_struct(some_state);

Note

The implementation defines several helper functions that can acquire and release the context lock.

disable_context_analysis() #

disable_context_analysis()

disables context analysis

Description

Disables context analysis. Must be paired with a later enable_context_analysis().

enable_context_analysis() #

enable_context_analysis()

re-enables context analysis

Description

Re-enables context analysis. Must be paired with a prior disable_context_analysis().

context_unsafe() #

context_unsafe(...)

disable context checking for contained code

Parameters

  • ...: variable arguments

Description

Disables context checking for contained statements or expression.

struct some_data {
        spinlock_t lock;
        int counter __guarded_by(&lock);
};

int foo(struct some_data *d)
{
        // ...
        // other code that is still checked ...
        // ...
        return context_unsafe(d->counter);
}

__context_unsafe() #

__context_unsafe(comment)

function attribute, disable context checking

Parameters

  • comment: comment explaining why opt-out is safe

Description

Function attribute denoting that context analysis is disabled for the whole function. Forces adding an inline comment as argument.

token_context_lock() #

token_context_lock(name, ...)

declare an abstract global context lock instance

Parameters

  • name: token context lock name
  • ...: variable arguments

Description

Helper that declares an abstract global context lock instance name, but not backed by a real data structure (linker error if accidentally referenced). The type name is __ctx_lock_@name.

token_context_lock_instance() #

token_context_lock_instance(ctx, name)

declare another instance of a global context lock

Parameters

  • ctx: token context lock previously declared with token_context_lock()
  • name: name of additional global context lock instance

Description

Helper that declares an additional instance name of the same token context lock class ctx. This is helpful where multiple related token contexts are declared, to allow using the same underlying type (__ctx_lock_@ctx) as function arguments.

__must_hold() #

__must_hold(...)

function attribute, caller must hold exclusive context lock

Parameters

  • ...: variable arguments

Description

Function attribute declaring that the caller must hold the given context lock instance(s) exclusively.

__must_not_hold() #

__must_not_hold(...)

function attribute, caller must not hold context lock

Parameters

  • ...: variable arguments

Description

Function attribute declaring that the caller must not hold the given context lock instance(s).

__acquires() #

__acquires(...)

function attribute, function acquires context lock exclusively

Parameters

  • ...: variable arguments

Description

Function attribute declaring that the function acquires the given context lock instance(s) exclusively, but does not release them.

__cond_acquires() #

__cond_acquires(ret, x)

function attribute, function conditionally acquires a context lock exclusively

Parameters

  • ret: abstract value returned by function if context lock acquired
  • x: context lock instance pointer

Description

Function attribute declaring that the function conditionally acquires the given context lock instance x exclusively, but does not release it. The function return value ret denotes when the context lock is acquired.

ret may be one of: true, false, nonzero, 0, nonnull, NULL.

__releases() #

__releases(...)

function attribute, function releases a context lock exclusively

Parameters

  • ...: variable arguments

Description

Function attribute declaring that the function releases the given context lock instance(s) exclusively. The associated context(s) must be active on entry.

__acquire() #

__acquire(x)

function to acquire context lock exclusively

Parameters

  • x: context lock instance pointer

Description

No-op function that acquires the given context lock instance x exclusively.

__release() #

__release(x)

function to release context lock exclusively

Parameters

  • x: context lock instance pointer

Description

No-op function that releases the given context lock instance x.

__must_hold_shared() #

__must_hold_shared(...)

function attribute, caller must hold shared context lock

Parameters

  • ...: variable arguments

Description

Function attribute declaring that the caller must hold the given context lock instance(s) with shared access.

__acquires_shared() #

__acquires_shared(...)

function attribute, function acquires context lock shared

Parameters

  • ...: variable arguments

Description

Function attribute declaring that the function acquires the given context lock instance(s) with shared access, but does not release them.

__cond_acquires_shared() #

__cond_acquires_shared(ret, x)

function attribute, function conditionally acquires a context lock shared

Parameters

  • ret: abstract value returned by function if context lock acquired
  • x: context lock instance pointer

Description

Function attribute declaring that the function conditionally acquires the given context lock instance x with shared access, but does not release it. The function return value ret denotes when the context lock is acquired.

ret may be one of: true, false, nonzero, 0, nonnull, NULL.

__releases_shared() #

__releases_shared(...)

function attribute, function releases a context lock shared

Parameters

  • ...: variable arguments

Description

Function attribute declaring that the function releases the given context lock instance(s) with shared access. The associated context(s) must be active on entry.

__acquire_shared() #

__acquire_shared(x)

function to acquire context lock shared

Parameters

  • x: context lock instance pointer

Description

No-op function that acquires the given context lock instance x with shared access.

__release_shared() #

__release_shared(x)

function to release context lock shared

Parameters

  • x: context lock instance pointer

Description

No-op function that releases the given context lock instance x with shared access.

__acquire_ret() #

__acquire_ret(call, ret_expr)

helper to acquire context lock of return value

Parameters

  • call: call expression
  • ret_expr: acquire expression that uses __ret

__acquire_shared_ret() #

__acquire_shared_ret(call, ret_expr)

helper to acquire context lock shared of return value

Parameters

  • call: call expression
  • ret_expr: acquire shared expression that uses __ret

Note

The function attribute __no_context_analysis is reserved for internal implementation of context lock types, and should be avoided in normal code.

Background #

Clang originally called the feature Thread Safety Analysis, with some keywords and documentation still using the thread-safety-analysis-only terminology. This was later changed and the feature became more flexible, gaining the ability to define custom "capabilities". Its foundations can be found in Capability Systems, used to specify the permissibility of operations to depend on some "capability" being held (or not held).

Because the feature is not just able to express capabilities related to synchronization primitives, and "capability" is already overloaded in the kernel, the naming chosen for the kernel departs from Clang's initial "Thread Safety" and "capability" nomenclature; we refer to the feature as "Context Analysis" to avoid confusion. The internal implementation still makes references to Clang's terminology in a few places, such as -Wthread-safety being the warning option that also still appears in diagnostic messages.

Using gcov with the Linux kernel

Peios Kernel / Kernel development / Development tools

Peios: Integrity lockdown restricts debugfs access. Read-only files passing its safety checks can remain accessible, but writable or ioctl/mmap-capable debugfs interfaces can fail with EPERM. Native authority does not bypass lockdown. These upstream diagnostic recipes therefore depend on interface availability in the configured kernel. See Peios kernel behaviour.

Peios: Linux capability names in this interface retain their API meaning, but KACS evaluates them through native token privileges or compatibility rules. UID 0, setcap and Unix mode bits do not independently grant native authority. Object access and PIP checks remain additional constraints where applicable. See Peios kernel behaviour for the mapping and exceptions.

gcov profiling kernel support enables the use of GCC's coverage testing tool gcov with the Linux kernel. Coverage data of a running kernel is exported in gcov-compatible format via the "gcov" debugfs directory. To get coverage data for a specific file, change to the kernel build directory and use gcov with the -o option as follows (requires root):

# cd /tmp/linux-out
# gcov -o /sys/kernel/debug/gcov/tmp/linux-out/kernel spinlock.c

This will create source code files annotated with execution counts in the current directory. In addition, graphical gcov front-ends such as lcov can be used to automate the process of collecting data for the entire kernel and provide coverage overviews in HTML format.

Possible uses:

  • debugging (has this line been reached at all?)

  • test improvement (how do I change my test to cover these lines?)

  • minimizing kernel configurations (do I need this option if the associated code is never run?)

Preparation #

Configure the kernel with:

CONFIG_DEBUG_FS=y
CONFIG_GCOV_KERNEL=y

and to get coverage data for the entire kernel:

CONFIG_GCOV_PROFILE_ALL=y

Note that kernels compiled with profiling flags will be significantly larger and run slower. Also CONFIG_GCOV_PROFILE_ALL may not be supported on all architectures.

Profiling data will only become accessible once debugfs has been mounted:

mount -t debugfs none /sys/kernel/debug

Customization #

To enable profiling for specific files or directories, add a line similar to the following to the respective kernel Makefile:

  • For a single file (e.g. main.o):

    GCOV_PROFILE_main.o := y
    
  • For all files in one directory:

    GCOV_PROFILE := y
    

To exclude files from being profiled even when CONFIG_GCOV_PROFILE_ALL is specified, use:

GCOV_PROFILE_main.o := n

and:

GCOV_PROFILE := n

Only files which are linked to the main kernel image or are compiled as kernel modules are supported by this mechanism.

Module specific configs #

Gcov kernel configs for specific modules are described below:

  • CONFIG_GCOV_PROFILE_RDS:

    Enables GCOV profiling on RDS for checking which functions or lines are executed. This config is used by the rds selftest to generate coverage reports. If left unset the report is omitted.

Files #

The gcov kernel support creates the following files in debugfs:

  • /sys/kernel/debug/gcov

    Parent directory for all gcov-related files.

  • /sys/kernel/debug/gcov/reset

    Global reset file: resets all coverage data to zero when written to.

  • /sys/kernel/debug/gcov/path/to/compile/dir/file.gcda

    The actual gcov data file as understood by the gcov tool. Resets file coverage data to zero when written to.

  • /sys/kernel/debug/gcov/path/to/compile/dir/file.gcno

    Symbolic link to a static data file required by the gcov tool. This file is generated by gcc when compiling with option -ftest-coverage.

Modules #

Kernel modules may contain cleanup code which is only run during module unload time. The gcov mechanism provides a means to collect coverage data for such code by keeping a copy of the data associated with the unloaded module. This data remains available through debugfs. Once the module is loaded again, the associated coverage counters are initialized with the data from its previous instantiation.

This behavior can be deactivated by specifying the gcov_persist kernel parameter:

gcov_persist=0

At run-time, a user can also choose to discard data for an unloaded module by writing to its data file or the global reset file.

Separated build and test machines #

The gcov kernel profiling infrastructure is designed to work out-of-the box for setups where kernels are built and run on the same machine. In cases where the kernel runs on a separate machine, special preparations must be made, depending on where the gcov tool is used:

  • a) gcov is run on the TEST machine

    The gcov tool version on the test machine must be compatible with the gcc version used for kernel build. Also the following files need to be copied from build to test machine:

    • from the source tree:

      • all C source files + headers
    • from the build tree:

      • all C source files + headers

      • all .gcda and .gcno files

      • all links to directories

    It is important to note that these files need to be placed into the exact same file system location on the test machine as on the build machine. If any of the path components is symbolic link, the actual directory needs to be used instead (due to make's CURDIR handling).

  • b) gcov is run on the BUILD machine

    The following files need to be copied after each test case from test to build machine:

    • from the gcov directory in sysfs:

      • all .gcda files

      • all links to .gcno files

    These files can be copied to any location on the build machine. gcov must then be called with the -o option pointing to that directory.

    Example directory setup on the build machine:

    /tmp/linux:    kernel source tree
    /tmp/out:      kernel build directory as specified by make O=
    /tmp/coverage: location of the files copied from the test machine
    
    [user@build] cd /tmp/out
    [user@build] gcov -o /tmp/coverage/tmp/out/init main.c
    

Note on compilers #

GCC and LLVM gcov tools are not necessarily compatible. Use gcov to work with GCC-generated .gcno and .gcda files, and use llvm-cov for Clang.

Build differences between GCC and Clang gcov are handled by Kconfig. It automatically selects the appropriate gcov format depending on the detected toolchain.

Troubleshooting #

  • Problem

    Compilation aborts during linker step.

  • Cause

    Profiling flags are specified for source files which are not linked to the main kernel or which are linked by a custom linker procedure.

  • Solution

    Exclude affected source files from profiling by specifying GCOV_PROFILE := n or GCOV_PROFILE_basename.o := n in the corresponding Makefile.

  • Problem

    Files copied from sysfs appear empty or incomplete.

  • Cause

    Due to the way seq_file works, some tools such as cp or tar may not correctly copy files from sysfs.

  • Solution

    Use cat to read .gcda files and cp -d to copy links. Alternatively use the mechanism shown in Appendix B.

Appendix A: gather_on_build.sh #

Sample script to gather coverage meta files on the build machine (see Separated build and test machines a.):

#!/bin/bash

KSRC=$1
KOBJ=$2
DEST=$3

if [ -z "$KSRC" ] || [ -z "$KOBJ" ] || [ -z "$DEST" ]; then
  echo "Usage: $0 <ksrc directory> <kobj directory> <output.tar.gz>" >&2
  exit 1
fi

KSRC=$(cd $KSRC; printf "all:\n\t@echo \${CURDIR}\n" | make -f -)
KOBJ=$(cd $KOBJ; printf "all:\n\t@echo \${CURDIR}\n" | make -f -)

find $KSRC $KOBJ \( -name '*.gcno' -o -name '*.[ch]' -o -type l \) -a \
                 -perm /u+r,g+r | tar cfz $DEST -P -T -

if [ $? -eq 0 ] ; then
  echo "$DEST successfully created, copy to test system and unpack with:"
  echo "  tar xfz $DEST -P"
else
  echo "Could not create file $DEST"
fi

Appendix B: gather_on_test.sh #

Sample script to gather coverage data files on the test machine (see Separated build and test machines b.):

#!/bin/bash -e

DEST=$1
GCDA=/sys/kernel/debug/gcov

if [ -z "$DEST" ] ; then
  echo "Usage: $0 <output.tar.gz>" >&2
  exit 1
fi

TEMPDIR=$(mktemp -d)
echo Collecting data..
find $GCDA -type d -exec mkdir -p $TEMPDIR/\{\} \;
find $GCDA -name '*.gcda' -exec sh -c 'cat < $0 > '$TEMPDIR'/$0' {} \;
find $GCDA -name '*.gcno' -exec sh -c 'cp -d $0 '$TEMPDIR'/$0' {} \;
tar czf $DEST -C $TEMPDIR sys
rm -rf $TEMPDIR

echo "$DEST successfully created, copy to build system and unpack with:"
echo "  tar xfz $DEST"

Linux Kernel GPIO based sloppy logic analyzer

Peios Kernel / Kernel development / Development tools

Author: Wolfram Sang

Introduction #

This document briefly describes how to run the GPIO based in-kernel sloppy logic analyzer running on an isolated CPU.

The sloppy logic analyzer will utilize a few GPIO lines in input mode on a system to rapidly sample these digital lines, which will, if the Nyquist criteria is met, result in a time series log with approximate waveforms as they appeared on these lines. One way to use it is to analyze external traffic connected to these GPIO lines with wires (i.e. digital probes), acting as a common logic analyzer.

Another feature is to snoop on on-chip peripherals if the I/O cells of these peripherals can be used in GPIO input mode at the same time as they are being used as inputs or outputs for the peripheral. That means you could e.g. snoop I2C traffic without any wiring (if your hardware supports it). In the pin control subsystem such pin controllers are called "non-strict": a certain pin can be used with a certain peripheral and as a GPIO input line at the same time.

Note that this is a last resort analyzer which can be affected by latencies, non-deterministic code paths and non-maskable interrupts. It is called 'sloppy' for a reason. However, for e.g. remote development, it may be useful to get a first view and aid further debugging.

Setup #

Your kernel must have CONFIG_DEBUG_FS and CONFIG_CPUSETS enabled. Ideally, your runtime environment does not utilize cpusets otherwise, then isolation of a CPU core is easiest. If you do need cpusets, check that helper script for the sloppy logic analyzer does not interfere with your other settings.

Tell the kernel which GPIOs are used as probes. For a Device Tree based system, you need to use the following bindings. Because these bindings are only for debugging, there is no official schema:

i2c-analyzer {
        compatible = "gpio-sloppy-logic-analyzer";
        probe-gpios = <&gpio6 21 GPIO_OPEN_DRAIN>, <&gpio6 4 GPIO_OPEN_DRAIN>;
        probe-names = "SCL", "SDA";
};

Note that you must provide a name for every GPIO specified. Currently a maximum of 8 probes are supported. 32 are likely possible but are not implemented yet.

Usage #

The logic analyzer is configurable via files in debugfs. However, it is strongly recommended to not use them directly, but to use the script tools/gpio/gpio-sloppy-logic-analyzer. Besides checking parameters more extensively, it will isolate the CPU core so you will have the least disturbance while measuring.

The script has a help option explaining the parameters. For the above DT snippet which analyzes an I2C bus at 400kHz on a Renesas Salvator-XS board, the following settings are used: The isolated CPU shall be CPU1 because it is a big core in a big.LITTLE setup. Because CPU1 is the default, we don't need a parameter. The bus speed is 400kHz. So, the sampling theorem says we need to sample at least at 800kHz. However, falling edges of both signals in an I2C start condition happen faster, so we need a higher sampling frequency, e.g. -s 1500000 for 1.5MHz. Also, we don't want to sample right away but wait for a start condition on an idle bus. So, we need to set a trigger to a falling edge on SDA while SCL stays high, i.e. -t 1H+2F. Last is the duration, let us assume 15ms here which results in the parameter -d 15000. So, altogether:

gpio-sloppy-logic-analyzer -s 1500000 -t 1H+2F -d 15000

Note that the process will return you back to the prompt but a sub-process is still sampling in the background. Unless this has finished, you will not find a result file in the current or specified directory. For the above example, we will then need to trigger I2C communication:

i2cdetect -y -r <your bus number>

Result is a .sr file to be consumed with PulseView or sigrok-cli from the free sigrok project. It is a zip file which also contains the binary sample data which may be consumed by other software. The filename is the logic analyzer instance name plus a since-epoch timestamp.

Kernel Address Sanitizer (KASAN)

Peios Kernel / Kernel development / Development tools

Overview #

Kernel Address Sanitizer (KASAN) is a dynamic memory safety error detector designed to find out-of-bounds and use-after-free bugs.

KASAN has three modes:

  1. Generic KASAN

  2. Software Tag-Based KASAN

  3. Hardware Tag-Based KASAN

Generic KASAN, enabled with CONFIG_KASAN_GENERIC, is the mode intended for debugging, similar to userspace ASan. This mode is supported on many CPU architectures, but it has significant performance and memory overheads.

Software Tag-Based KASAN or SW_TAGS KASAN, enabled with CONFIG_KASAN_SW_TAGS, can be used for both debugging and dogfood testing, similar to userspace HWASan. This mode is only supported for arm64, but its moderate memory overhead allows using it for testing on memory-restricted devices with real workloads.

Hardware Tag-Based KASAN or HW_TAGS KASAN, enabled with CONFIG_KASAN_HW_TAGS, is the mode intended to be used as an in-field memory bug detector or as a security mitigation. This mode only works on arm64 CPUs that support MTE (Memory Tagging Extension), but it has low memory and performance overheads and thus can be used in production.

For details about the memory and performance impact of each KASAN mode, see the descriptions of the corresponding Kconfig options.

The Generic and the Software Tag-Based modes are commonly referred to as the software modes. The Software Tag-Based and the Hardware Tag-Based modes are referred to as the tag-based modes.

Support #

Architectures #

Generic KASAN is supported on x86_64, arm, arm64, powerpc, riscv, s390, xtensa, and loongarch, and the tag-based KASAN modes are supported only on arm64.

Compilers #

Software KASAN modes use compile-time instrumentation to insert validity checks before every memory access and thus require a compiler version that provides support for that. The Hardware Tag-Based mode relies on hardware to perform these checks but still requires a compiler version that supports the memory tagging instructions.

Generic KASAN requires GCC version 8.3.0 or later or any Clang version supported by the kernel.

Software Tag-Based KASAN requires GCC 11+ or any Clang version supported by the kernel.

Hardware Tag-Based KASAN requires GCC 10+ or Clang 12+.

Memory types #

Generic KASAN supports finding bugs in all of slab, page_alloc, vmap, vmalloc, stack, and global memory.

Software Tag-Based KASAN supports slab, page_alloc, vmalloc, and stack memory.

Hardware Tag-Based KASAN supports slab, page_alloc, and non-executable vmalloc memory.

For slab, both software KASAN modes support SLUB and SLAB allocators, while Hardware Tag-Based KASAN only supports SLUB.

Usage #

To enable KASAN, configure the kernel with:

CONFIG_KASAN=y

and choose between CONFIG_KASAN_GENERIC (to enable Generic KASAN), CONFIG_KASAN_SW_TAGS (to enable Software Tag-Based KASAN), and CONFIG_KASAN_HW_TAGS (to enable Hardware Tag-Based KASAN).

For the software modes, also choose between CONFIG_KASAN_OUTLINE and CONFIG_KASAN_INLINE. Outline and inline are compiler instrumentation types. The former produces a smaller binary while the latter is up to 2 times faster.

To include alloc and free stack traces of affected slab objects into reports, enable CONFIG_STACKTRACE. To include alloc and free stack traces of affected physical pages, enable CONFIG_PAGE_OWNER and boot with page_owner=on.

Boot parameters #

KASAN is affected by the generic panic_on_warn command line parameter. When it is enabled, KASAN panics the kernel after printing a bug report.

By default, KASAN prints a bug report only for the first invalid memory access. With kasan_multi_shot, KASAN prints a report on every invalid access. This effectively disables panic_on_warn for KASAN reports.

Alternatively, independent of panic_on_warn, the kasan.fault= boot parameter can be used to control panic and reporting behaviour:

  • kasan.fault=report, =panic, or =panic_on_write controls whether to only print a KASAN report, panic the kernel, or panic the kernel on invalid writes only (default: report). The panic happens even if kasan_multi_shot is enabled. Note that when using asynchronous mode of Hardware Tag-Based KASAN, kasan.fault=panic_on_write always panics on asynchronously checked accesses (including reads).

Software and Hardware Tag-Based KASAN modes (see the section about various modes below) support altering stack trace collection behavior:

  • kasan.stacktrace=off or =on disables or enables alloc and free stack traces collection (default: on).

  • kasan.stack_ring_size=<number of entries> specifies the number of entries in the stack ring (default: 32768).

Hardware Tag-Based KASAN mode is intended for use in production as a security mitigation. Therefore, it supports additional boot parameters that allow disabling KASAN altogether or controlling its features:

  • kasan=off or =on controls whether KASAN is enabled (default: on).

  • kasan.mode=sync, =async or =asymm controls whether KASAN is configured in synchronous, asynchronous or asymmetric mode of execution (default: sync). Synchronous mode: a bad access is detected immediately when a tag check fault occurs. Asynchronous mode: a bad access detection is delayed. When a tag check fault occurs, the information is stored in hardware (in the TFSR_EL1 register for arm64). The kernel periodically checks the hardware and only reports tag faults during these checks. Asymmetric mode: a bad access is detected synchronously on reads and asynchronously on writes.

  • kasan.write_only=off or kasan.write_only=on controls whether KASAN checks the write (store) accesses only or all accesses (default: off).

  • kasan.vmalloc=off or =on disables or enables tagging of vmalloc allocations (default: on).

  • kasan.page_alloc.sample=<sampling interval> makes KASAN tag only every Nth page_alloc allocation with the order equal or greater than kasan.page_alloc.sample.order, where N is the value of the sample parameter (default: 1, or tag every such allocation). This parameter is intended to mitigate the performance overhead introduced by KASAN. Note that enabling this parameter makes Hardware Tag-Based KASAN skip checks of allocations chosen by sampling and thus miss bad accesses to these allocations. Use the default value for accurate bug detection.

  • kasan.page_alloc.sample.order=<minimum page order> specifies the minimum order of allocations that are affected by sampling (default: 3). Only applies when kasan.page_alloc.sample is set to a value greater than 1. This parameter is intended to allow sampling only large page_alloc allocations, which is the biggest source of the performance overhead.

Error reports #

A typical KASAN report looks like this:

==================================================================
BUG: KASAN: slab-out-of-bounds in kmalloc_oob_right+0xa8/0xbc [kasan_test]
Write of size 1 at addr ffff8801f44ec37b by task insmod/2760

CPU: 1 PID: 2760 Comm: insmod Not tainted 4.19.0-rc3+ #698
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1 04/01/2014
Call Trace:
 dump_stack+0x94/0xd8
 print_address_description+0x73/0x280
 kasan_report+0x144/0x187
 __asan_report_store1_noabort+0x17/0x20
 kmalloc_oob_right+0xa8/0xbc [kasan_test]
 kmalloc_tests_init+0x16/0x700 [kasan_test]
 do_one_initcall+0xa5/0x3ae
 do_init_module+0x1b6/0x547
 load_module+0x75df/0x8070
 __do_sys_init_module+0x1c6/0x200
 __x64_sys_init_module+0x6e/0xb0
 do_syscall_64+0x9f/0x2c0
 entry_SYSCALL_64_after_hwframe+0x44/0xa9
RIP: 0033:0x7f96443109da
RSP: 002b:00007ffcf0b51b08 EFLAGS: 00000202 ORIG_RAX: 00000000000000af
RAX: ffffffffffffffda RBX: 000055dc3ee521a0 RCX: 00007f96443109da
RDX: 00007f96445cff88 RSI: 0000000000057a50 RDI: 00007f9644992000
RBP: 000055dc3ee510b0 R08: 0000000000000003 R09: 0000000000000000
R10: 00007f964430cd0a R11: 0000000000000202 R12: 00007f96445cff88
R13: 000055dc3ee51090 R14: 0000000000000000 R15: 0000000000000000

Allocated by task 2760:
 save_stack+0x43/0xd0
 kasan_kmalloc+0xa7/0xd0
 kmem_cache_alloc_trace+0xe1/0x1b0
 kmalloc_oob_right+0x56/0xbc [kasan_test]
 kmalloc_tests_init+0x16/0x700 [kasan_test]
 do_one_initcall+0xa5/0x3ae
 do_init_module+0x1b6/0x547
 load_module+0x75df/0x8070
 __do_sys_init_module+0x1c6/0x200
 __x64_sys_init_module+0x6e/0xb0
 do_syscall_64+0x9f/0x2c0
 entry_SYSCALL_64_after_hwframe+0x44/0xa9

Freed by task 815:
 save_stack+0x43/0xd0
 __kasan_slab_free+0x135/0x190
 kasan_slab_free+0xe/0x10
 kfree+0x93/0x1a0
 umh_complete+0x6a/0xa0
 call_usermodehelper_exec_async+0x4c3/0x640
 ret_from_fork+0x35/0x40

The buggy address belongs to the object at ffff8801f44ec300
 which belongs to the cache kmalloc-128 of size 128
The buggy address is located 123 bytes inside of
 128-byte region [ffff8801f44ec300, ffff8801f44ec380)
The buggy address belongs to the page:
page:ffffea0007d13b00 count:1 mapcount:0 mapping:ffff8801f7001640 index:0x0
flags: 0x200000000000100(slab)
raw: 0200000000000100 ffffea0007d11dc0 0000001a0000001a ffff8801f7001640
raw: 0000000000000000 0000000080150015 00000001ffffffff 0000000000000000
page dumped because: kasan: bad access detected

Memory state around the buggy address:
 ffff8801f44ec200: fc fc fc fc fc fc fc fc fb fb fb fb fb fb fb fb
 ffff8801f44ec280: fb fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
>ffff8801f44ec300: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03
                                                                ^
 ffff8801f44ec380: fc fc fc fc fc fc fc fc fb fb fb fb fb fb fb fb
 ffff8801f44ec400: fb fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
==================================================================

The report header summarizes what kind of bug happened and what kind of access caused it. It is followed by a stack trace of the bad access, a stack trace of where the accessed memory was allocated (in case a slab object was accessed), and a stack trace of where the object was freed (in case of a use-after-free bug report). Next comes a description of the accessed slab object and the information about the accessed memory page.

In the end, the report shows the memory state around the accessed address. Internally, KASAN tracks memory state separately for each memory granule, which is either 8 or 16 aligned bytes depending on KASAN mode. Each number in the memory state section of the report shows the state of one of the memory granules that surround the accessed address.

For Generic KASAN, the size of each memory granule is 8. The state of each granule is encoded in one shadow byte. Those 8 bytes can be accessible, partially accessible, freed, or be a part of a redzone. KASAN uses the following encoding for each shadow byte: 00 means that all 8 bytes of the corresponding memory region are accessible; number N (1 <= N <= 7) means that the first N bytes are accessible, and other (8 - N) bytes are not; any negative value indicates that the entire 8-byte word is inaccessible. KASAN uses different negative values to distinguish between different kinds of inaccessible memory like redzones or freed memory (see mm/kasan/kasan.h).

In the report above, the arrow points to the shadow byte 03, which means that the accessed address is partially accessible.

For tag-based KASAN modes, this last report section shows the memory tags around the accessed address (see the Implementation details section).

Note that KASAN bug titles (like slab-out-of-bounds or use-after-free) are best-effort: KASAN prints the most probable bug type based on the limited information it has. The actual type of the bug might be different.

Generic KASAN also reports up to two auxiliary call stack traces. These stack traces point to places in code that interacted with the object but that are not directly present in the bad access stack trace. Currently, this includes call_rcu() and workqueue queuing.

CONFIG_KASAN_EXTRA_INFO #

Enabling CONFIG_KASAN_EXTRA_INFO allows KASAN to record and report more information. The extra information currently supported is the CPU number and timestamp at allocation and free. More information can help find the cause of the bug and correlate the error with other system events, at the cost of using extra memory to record more information (more cost details in the help text of CONFIG_KASAN_EXTRA_INFO).

Here is the report with CONFIG_KASAN_EXTRA_INFO enabled (only the different parts are shown):

==================================================================
...
Allocated by task 134 on cpu 5 at 229.133855s:
...
Freed by task 136 on cpu 3 at 230.199335s:
...
==================================================================

Implementation details #

Generic KASAN #

Software KASAN modes use shadow memory to record whether each byte of memory is safe to access and use compile-time instrumentation to insert shadow memory checks before each memory access.

Generic KASAN dedicates 1/8th of kernel memory to its shadow memory (16TB to cover 128TB on x86_64) and uses direct mapping with a scale and offset to translate a memory address to its corresponding shadow address.

Here is the function which translates an address to its corresponding shadow address:

static inline void *kasan_mem_to_shadow(const void *addr)
{
    return (void *)((unsigned long)addr >> KASAN_SHADOW_SCALE_SHIFT)
            + KASAN_SHADOW_OFFSET;
}

where KASAN_SHADOW_SCALE_SHIFT = 3.

Compile-time instrumentation is used to insert memory access checks. Compiler inserts function calls (__asan_load*(addr), __asan_store*(addr)) before each memory access of size 1, 2, 4, 8, or 16. These functions check whether memory accesses are valid or not by checking corresponding shadow memory.

With inline instrumentation, instead of making function calls, the compiler directly inserts the code to check shadow memory. This option significantly enlarges the kernel, but it gives an x1.1-x2 performance boost over the outline-instrumented kernel.

Generic KASAN is the only mode that delays the reuse of freed objects via quarantine (see mm/kasan/quarantine.c for implementation).

Software Tag-Based KASAN #

Software Tag-Based KASAN uses a software memory tagging approach to checking access validity. It is currently only implemented for the arm64 architecture.

Software Tag-Based KASAN uses the Top Byte Ignore (TBI) feature of arm64 CPUs to store a pointer tag in the top byte of kernel pointers. It uses shadow memory to store memory tags associated with each 16-byte memory cell (therefore, it dedicates 1/16th of the kernel memory for shadow memory).

On each memory allocation, Software Tag-Based KASAN generates a random tag, tags the allocated memory with this tag, and embeds the same tag into the returned pointer.

Software Tag-Based KASAN uses compile-time instrumentation to insert checks before each memory access. These checks make sure that the tag of the memory that is being accessed is equal to the tag of the pointer that is used to access this memory. In case of a tag mismatch, Software Tag-Based KASAN prints a bug report.

Software Tag-Based KASAN also has two instrumentation modes (outline, which emits callbacks to check memory accesses; and inline, which performs the shadow memory checks inline). With outline instrumentation mode, a bug report is printed from the function that performs the access check. With inline instrumentation, a brk instruction is emitted by the compiler, and a dedicated brk handler is used to print bug reports.

Software Tag-Based KASAN uses 0xFF as a match-all pointer tag (accesses through pointers with the 0xFF pointer tag are not checked). The value 0xFE is currently reserved to tag freed memory regions.

Hardware Tag-Based KASAN #

Hardware Tag-Based KASAN is similar to the software mode in concept but uses hardware memory tagging support instead of compiler instrumentation and shadow memory.

Hardware Tag-Based KASAN is currently only implemented for arm64 architecture and based on both arm64 Memory Tagging Extension (MTE) introduced in ARMv8.5 Instruction Set Architecture and Top Byte Ignore (TBI).

Special arm64 instructions are used to assign memory tags for each allocation. Same tags are assigned to pointers to those allocations. On every memory access, hardware makes sure that the tag of the memory that is being accessed is equal to the tag of the pointer that is used to access this memory. In case of a tag mismatch, a fault is generated, and a report is printed.

Hardware Tag-Based KASAN uses 0xFF as a match-all pointer tag (accesses through pointers with the 0xFF pointer tag are not checked). The value 0xFE is currently reserved to tag freed memory regions.

If the hardware does not support MTE (pre ARMv8.5), Hardware Tag-Based KASAN will not be enabled. In this case, all KASAN boot parameters are ignored.

Note that enabling CONFIG_KASAN_HW_TAGS always results in in-kernel TBI being enabled. Even when kasan.mode=off is provided or when the hardware does not support MTE (but supports TBI).

Hardware Tag-Based KASAN only reports the first found bug. After that, MTE tag checking gets disabled.

Shadow memory #

The contents of this section are only applicable to software KASAN modes.

The kernel maps memory in several different parts of the address space. The range of kernel virtual addresses is large: there is not enough real memory to support a real shadow region for every address that could be accessed by the kernel. Therefore, KASAN only maps real shadow for certain parts of the address space.

Default behaviour #

By default, architectures only map real memory over the shadow region for the linear mapping (and potentially other small areas). For all other areas - such as vmalloc and vmemmap space - a single read-only page is mapped over the shadow area. This read-only shadow page declares all memory accesses as permitted.

This presents a problem for modules: they do not live in the linear mapping but in a dedicated module space. By hooking into the module allocator, KASAN temporarily maps real shadow memory to cover them. This allows detection of invalid accesses to module globals, for example.

This also creates an incompatibility with VMAP_STACK: if the stack lives in vmalloc space, it will be shadowed by the read-only page, and the kernel will fault when trying to set up the shadow data for stack variables.

CONFIG_KASAN_VMALLOC #

With CONFIG_KASAN_VMALLOC, KASAN can cover vmalloc space at the cost of greater memory usage. Currently, this is supported on x86, arm64, riscv, s390, and powerpc.

This works by hooking into vmalloc and vmap and dynamically allocating real shadow memory to back the mappings.

Most mappings in vmalloc space are small, requiring less than a full page of shadow space. Allocating a full shadow page per mapping would therefore be wasteful. Furthermore, to ensure that different mappings use different shadow pages, mappings would have to be aligned to KASAN_GRANULE_SIZE * PAGE_SIZE.

Instead, KASAN shares backing space across multiple mappings. It allocates a backing page when a mapping in vmalloc space uses a particular page of the shadow region. This page can be shared by other vmalloc mappings later on.

KASAN hooks into the vmap infrastructure to lazily clean up unused shadow memory.

To avoid the difficulties around swapping mappings around, KASAN expects that the part of the shadow region that covers the vmalloc space will not be covered by the early shadow page but will be left unmapped. This will require changes in arch-specific code.

This allows VMAP_STACK support on x86 and can simplify support of architectures that do not have a fixed module region.

For developers #

Ignoring accesses #

Software KASAN modes use compiler instrumentation to insert validity checks. Such instrumentation might be incompatible with some parts of the kernel, and therefore needs to be disabled.

Other parts of the kernel might access metadata for allocated objects. Normally, KASAN detects and reports such accesses, but in some cases (e.g., in memory allocators), these accesses are valid.

For software KASAN modes, to disable instrumentation for a specific file or directory, add a KASAN_SANITIZE annotation to the respective kernel Makefile:

  • For a single file (e.g., main.o):

    KASAN_SANITIZE_main.o := n
    
  • For all files in one directory:

    KASAN_SANITIZE := n
    

For software KASAN modes, to disable instrumentation on a per-function basis, use the KASAN-specific __no_sanitize_address function attribute or the generic noinstr one.

Note that disabling compiler instrumentation (either on a per-file or a per-function basis) makes KASAN ignore the accesses that happen directly in that code for software KASAN modes. It does not help when the accesses happen indirectly (through calls to instrumented functions) or with Hardware Tag-Based KASAN, which does not use compiler instrumentation.

For software KASAN modes, to disable KASAN reports in a part of the kernel code for the current task, annotate this part of the code with a kasan_disable_current()/kasan_enable_current() section. This also disables the reports for indirect accesses that happen through function calls.

For tag-based KASAN modes, to disable access checking, use kasan_reset_tag() or page_kasan_tag_reset(). Note that temporarily disabling access checking via page_kasan_tag_reset() requires saving and restoring the per-page KASAN tag via page_kasan_tag/page_kasan_tag_set.

Tests #

There are KASAN tests that allow verifying that KASAN works and can detect certain types of memory corruptions.

All KASAN tests are integrated with the KUnit Test Framework and can be enabled via CONFIG_KASAN_KUNIT_TEST. The tests can be run and partially verified automatically in a few different ways; see the instructions below.

Each KASAN test prints one of multiple KASAN reports if an error is detected. Then the test prints its number and status.

When a test passes:

ok 28 - kmalloc_double_kzfree

When a test fails due to a failed kmalloc:

# kmalloc_large_oob_right: ASSERTION FAILED at mm/kasan/kasan_test.c:245
Expected ptr is not null, but is
not ok 5 - kmalloc_large_oob_right

When a test fails due to a missing KASAN report:

# kmalloc_double_kzfree: EXPECTATION FAILED at mm/kasan/kasan_test.c:709
KASAN failure expected in "kfree_sensitive(ptr)", but none occurred
not ok 28 - kmalloc_double_kzfree

At the end the cumulative status of all KASAN tests is printed. On success:

ok 1 - kasan

Or, if one of the tests failed:

not ok 1 - kasan

There are a few ways to run the KASAN tests.

  1. Loadable module

    With CONFIG_KUNIT enabled, the tests can be built as a loadable module and run by loading kasan_test.ko with insmod or modprobe.

  2. Built-In

    With CONFIG_KUNIT built-in, the tests can be built-in as well. In this case, the tests will run at boot as a late-init call.

  3. Using kunit_tool

    With CONFIG_KUNIT and CONFIG_KASAN_KUNIT_TEST built-in, it is also possible to use kunit_tool to see the results of KUnit tests in a more readable way. This will not print the KASAN reports of the tests that passed. See KUnit documentation for more up-to-date information on kunit_tool.

KCOV: code coverage for fuzzing

Peios Kernel / Kernel development / Development tools

KCOV collects and exposes kernel code coverage information in a form suitable for coverage-guided fuzzing. Coverage data of a running kernel is exported via the kcov debugfs file. Coverage collection is enabled on a task basis, and thus KCOV can capture precise coverage of a single system call.

Note that KCOV does not aim to collect as much coverage as possible. It aims to collect more or less stable coverage that is a function of syscall inputs. To achieve this goal, it does not collect coverage in soft/hard interrupts (unless remove coverage collection is enabled, see below) and from some inherently non-deterministic parts of the kernel (e.g. scheduler, locking).

Besides collecting code coverage, KCOV can also collect comparison operands. See the "Comparison operands collection" section for details.

Besides collecting coverage data from syscall handlers, KCOV can also collect coverage for annotated parts of the kernel executing in background kernel tasks or soft interrupts. See the "Remote coverage collection" section for details.

Prerequisites #

KCOV relies on compiler instrumentation and requires GCC 6.1.0 or later or any Clang version supported by the kernel.

Collecting comparison operands is supported with GCC 8+ or with Clang.

To enable KCOV, configure the kernel with:

CONFIG_KCOV=y

To enable comparison operands collection, set:

CONFIG_KCOV_ENABLE_COMPARISONS=y

Coverage data only becomes accessible once debugfs has been mounted:

mount -t debugfs none /sys/kernel/debug

Coverage collection #

The following program demonstrates how to use KCOV to collect coverage for a single syscall from within a test program:

#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
#include <linux/types.h>

#define KCOV_INIT_TRACE                     _IOR('c', 1, unsigned long)
#define KCOV_ENABLE                 _IO('c', 100)
#define KCOV_DISABLE                        _IO('c', 101)
#define COVER_SIZE                  (64<<10)

#define KCOV_TRACE_PC  0
#define KCOV_TRACE_CMP 1

int main(int argc, char **argv)
{
    int fd;
    unsigned long *cover, n, i;

    /* A single fd descriptor allows coverage collection on a single
     * thread.
     */
    fd = open("/sys/kernel/debug/kcov", O_RDWR);
    if (fd == -1)
            perror("open"), exit(1);
    /* Setup trace mode and trace size. */
    if (ioctl(fd, KCOV_INIT_TRACE, COVER_SIZE))
            perror("ioctl"), exit(1);
    /* Mmap buffer shared between kernel- and user-space. */
    cover = (unsigned long*)mmap(NULL, COVER_SIZE * sizeof(unsigned long),
                                 PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if ((void*)cover == MAP_FAILED)
            perror("mmap"), exit(1);
    /* Enable coverage collection on the current thread. */
    if (ioctl(fd, KCOV_ENABLE, KCOV_TRACE_PC))
            perror("ioctl"), exit(1);
    /* Reset coverage from the tail of the ioctl() call. */
    __atomic_store_n(&cover[0], 0, __ATOMIC_RELAXED);
    /* Call the target syscall call. */
    read(-1, NULL, 0);
    /* Read number of PCs collected. */
    n = __atomic_load_n(&cover[0], __ATOMIC_RELAXED);
    for (i = 0; i < n; i++)
            printf("0x%lx\n", cover[i + 1]);
    /* Disable coverage collection for the current thread. After this call
     * coverage can be enabled for a different thread.
     */
    if (ioctl(fd, KCOV_DISABLE, 0))
            perror("ioctl"), exit(1);
    /* Free resources. */
    if (munmap(cover, COVER_SIZE * sizeof(unsigned long)))
            perror("munmap"), exit(1);
    if (close(fd))
            perror("close"), exit(1);
    return 0;
}

After piping through addr2line the output of the program looks as follows:

SyS_read
fs/read_write.c:562
__fdget_pos
fs/file.c:774
__fget_light
fs/file.c:746
__fget_light
fs/file.c:750
__fget_light
fs/file.c:760
__fdget_pos
fs/file.c:784
SyS_read
fs/read_write.c:562

If a program needs to collect coverage from several threads (independently), it needs to open /sys/kernel/debug/kcov in each thread separately.

The interface is fine-grained to allow efficient forking of test processes. That is, a parent process opens /sys/kernel/debug/kcov, enables trace mode, mmaps coverage buffer, and then forks child processes in a loop. The child processes only need to enable coverage (it gets disabled automatically when a thread exits).

Comparison operands collection #

Comparison operands collection is similar to coverage collection:

/* Same includes and defines as above. */

/* Number of 64-bit words per record. */
#define KCOV_WORDS_PER_CMP 4

/*
 * The format for the types of collected comparisons.
 *
 * Bit 0 shows whether one of the arguments is a compile-time constant.
 * Bits 1 & 2 contain log2 of the argument size, up to 8 bytes.
 */

#define KCOV_CMP_CONST          (1 << 0)
#define KCOV_CMP_SIZE(n)        ((n) << 1)
#define KCOV_CMP_MASK           KCOV_CMP_SIZE(3)

int main(int argc, char **argv)
{
    int fd;
    uint64_t *cover, type, arg1, arg2, is_const, size;
    unsigned long n, i;

    fd = open("/sys/kernel/debug/kcov", O_RDWR);
    if (fd == -1)
            perror("open"), exit(1);
    if (ioctl(fd, KCOV_INIT_TRACE, COVER_SIZE))
            perror("ioctl"), exit(1);
    /*
    * Note that the buffer pointer is of type uint64_t*, because all
    * the comparison operands are promoted to uint64_t.
    */
    cover = (uint64_t *)mmap(NULL, COVER_SIZE * sizeof(unsigned long),
                                 PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if ((void*)cover == MAP_FAILED)
            perror("mmap"), exit(1);
    /* Note KCOV_TRACE_CMP instead of KCOV_TRACE_PC. */
    if (ioctl(fd, KCOV_ENABLE, KCOV_TRACE_CMP))
            perror("ioctl"), exit(1);
    __atomic_store_n(&cover[0], 0, __ATOMIC_RELAXED);
    read(-1, NULL, 0);
    /* Read number of comparisons collected. */
    n = __atomic_load_n(&cover[0], __ATOMIC_RELAXED);
    for (i = 0; i < n; i++) {
            uint64_t ip;

            type = cover[i * KCOV_WORDS_PER_CMP + 1];
            /* arg1 and arg2 - operands of the comparison. */
            arg1 = cover[i * KCOV_WORDS_PER_CMP + 2];
            arg2 = cover[i * KCOV_WORDS_PER_CMP + 3];
            /* ip - caller address. */
            ip = cover[i * KCOV_WORDS_PER_CMP + 4];
            /* size of the operands. */
            size = 1 << ((type & KCOV_CMP_MASK) >> 1);
            /* is_const - true if either operand is a compile-time constant.*/
            is_const = type & KCOV_CMP_CONST;
            printf("ip: 0x%lx type: 0x%lx, arg1: 0x%lx, arg2: 0x%lx, "
                    "size: %lu, %s\n",
                    ip, type, arg1, arg2, size,
            is_const ? "const" : "non-const");
    }
    if (ioctl(fd, KCOV_DISABLE, 0))
            perror("ioctl"), exit(1);
    /* Free resources. */
    if (munmap(cover, COVER_SIZE * sizeof(unsigned long)))
            perror("munmap"), exit(1);
    if (close(fd))
            perror("close"), exit(1);
    return 0;
}

Note that the KCOV modes (collection of code coverage or comparison operands) are mutually exclusive.

Remote coverage collection #

Besides collecting coverage data from handlers of syscalls issued from a userspace process, KCOV can also collect coverage for parts of the kernel executing in other contexts - so-called "remote" coverage.

Using KCOV to collect remote coverage requires:

  1. Modifying kernel code to annotate the code section from where coverage should be collected with kcov_remote_start and kcov_remote_stop.

  2. Using KCOV_REMOTE_ENABLE instead of KCOV_ENABLE in the userspace process that collects coverage.

Both kcov_remote_start and kcov_remote_stop annotations and the KCOV_REMOTE_ENABLE ioctl accept handles that identify particular coverage collection sections. The way a handle is used depends on the context where the matching code section executes.

KCOV supports collecting remote coverage from the following contexts:

  1. Global kernel background tasks. These are the tasks that are spawned during kernel boot in a limited number of instances (e.g. one USB hub_event worker is spawned per one USB HCD).

  2. Local kernel background tasks. These are spawned when a userspace process interacts with some kernel interface and are usually killed when the process exits (e.g. vhost workers).

  3. Soft interrupts.

For #1 and #3, a unique global handle must be chosen and passed to the corresponding kcov_remote_start call. Then a userspace process must pass this handle to KCOV_REMOTE_ENABLE in the handles array field of the kcov_remote_arg struct. This will attach the used KCOV device to the code section referenced by this handle. Multiple global handles identifying different code sections can be passed at once.

For #2, the userspace process instead must pass a non-zero handle through the common_handle field of the kcov_remote_arg struct. This common handle gets saved to the kcov_handle field in the current task_struct and needs to be passed to the newly spawned local tasks via custom kernel code modifications. Those tasks should in turn use the passed handle in their kcov_remote_start and kcov_remote_stop annotations.

KCOV follows a predefined format for both global and common handles. Each handle is a u64 integer. Currently, only the one top and the lower 4 bytes are used. Bytes 4-7 are reserved and must be zero.

For global handles, the top byte of the handle denotes the id of a subsystem this handle belongs to. For example, KCOV uses 1 as the USB subsystem id. The lower 4 bytes of a global handle denote the id of a task instance within that subsystem. For example, each hub_event worker uses the USB bus number as the task instance id.

For common handles, a reserved value 0 is used as a subsystem id, as such handles don't belong to a particular subsystem. The lower 4 bytes of a common handle identify a collective instance of all local tasks spawned by the userspace process that passed a common handle to KCOV_REMOTE_ENABLE.

In practice, any value can be used for common handle instance id if coverage is only collected from a single userspace process on the system. However, if common handles are used by multiple processes, unique instance ids must be used for each process. One option is to use the process id as the common handle instance id.

The following program demonstrates using KCOV to collect coverage from both local tasks spawned by the process and the global task that handles USB bus #1:

/* Same includes and defines as above. */

struct kcov_remote_arg {
    __u32           trace_mode;
    __u32           area_size;
    __u32           num_handles;
    __aligned_u64   common_handle;
    __aligned_u64   handles[0];
};

#define KCOV_INIT_TRACE                     _IOR('c', 1, unsigned long)
#define KCOV_DISABLE                        _IO('c', 101)
#define KCOV_REMOTE_ENABLE          _IOW('c', 102, struct kcov_remote_arg)

#define COVER_SIZE  (64 << 10)

#define KCOV_TRACE_PC       0

#define KCOV_SUBSYSTEM_COMMON       (0x00ull << 56)
#define KCOV_SUBSYSTEM_USB  (0x01ull << 56)

#define KCOV_SUBSYSTEM_MASK (0xffull << 56)
#define KCOV_INSTANCE_MASK  (0xffffffffull)

static inline __u64 kcov_remote_handle(__u64 subsys, __u64 inst)
{
    if (subsys & ~KCOV_SUBSYSTEM_MASK || inst & ~KCOV_INSTANCE_MASK)
            return 0;
    return subsys | inst;
}

#define KCOV_COMMON_ID      0x42
#define KCOV_USB_BUS_NUM    1

int main(int argc, char **argv)
{
    int fd;
    unsigned long *cover, n, i;
    struct kcov_remote_arg *arg;

    fd = open("/sys/kernel/debug/kcov", O_RDWR);
    if (fd == -1)
            perror("open"), exit(1);
    if (ioctl(fd, KCOV_INIT_TRACE, COVER_SIZE))
            perror("ioctl"), exit(1);
    cover = (unsigned long*)mmap(NULL, COVER_SIZE * sizeof(unsigned long),
                                 PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if ((void*)cover == MAP_FAILED)
            perror("mmap"), exit(1);

    /* Enable coverage collection via common handle and from USB bus #1. */
    arg = calloc(1, sizeof(*arg) + sizeof(uint64_t));
    if (!arg)
            perror("calloc"), exit(1);
    arg->trace_mode = KCOV_TRACE_PC;
    arg->area_size = COVER_SIZE;
    arg->num_handles = 1;
    arg->common_handle = kcov_remote_handle(KCOV_SUBSYSTEM_COMMON,
                                                    KCOV_COMMON_ID);
    arg->handles[0] = kcov_remote_handle(KCOV_SUBSYSTEM_USB,
                                            KCOV_USB_BUS_NUM);
    if (ioctl(fd, KCOV_REMOTE_ENABLE, arg))
            perror("ioctl"), free(arg), exit(1);
    free(arg);

    /*
     * Here the user needs to trigger execution of a kernel code section
     * that is either annotated with the common handle, or to trigger some
     * activity on USB bus #1.
     */
    sleep(2);

    /*
     * The load to the coverage count should be an acquire to pair with
     * pair with the corresponding write memory barrier (smp_wmb()) on
     * the kernel-side in kcov_move_area().
     */
    n = __atomic_load_n(&cover[0], __ATOMIC_ACQUIRE);
    for (i = 0; i < n; i++)
            printf("0x%lx\n", cover[i + 1]);
    if (ioctl(fd, KCOV_DISABLE, 0))
            perror("ioctl"), exit(1);
    if (munmap(cover, COVER_SIZE * sizeof(unsigned long)))
            perror("munmap"), exit(1);
    if (close(fd))
            perror("close"), exit(1);
    return 0;
}

Kernel Concurrency Sanitizer (KCSAN)

Peios Kernel / Kernel development / Development tools

The Kernel Concurrency Sanitizer (KCSAN) is a dynamic race detector, which relies on compile-time instrumentation, and uses a watchpoint-based sampling approach to detect races. KCSAN's primary purpose is to detect data races.

Usage #

KCSAN is supported by both GCC and Clang. With GCC we require version 11 or later, and with Clang also require version 11 or later.

To enable KCSAN configure the kernel with:

CONFIG_KCSAN = y

KCSAN provides several other configuration options to customize behaviour (see the respective help text in lib/Kconfig.kcsan for more info).

Error reports #

A typical data race report looks like this:

==================================================================
BUG: KCSAN: data-race in test_kernel_read / test_kernel_write

write to 0xffffffffc009a628 of 8 bytes by task 487 on cpu 0:
 test_kernel_write+0x1d/0x30
 access_thread+0x89/0xd0
 kthread+0x23e/0x260
 ret_from_fork+0x22/0x30

read to 0xffffffffc009a628 of 8 bytes by task 488 on cpu 6:
 test_kernel_read+0x10/0x20
 access_thread+0x89/0xd0
 kthread+0x23e/0x260
 ret_from_fork+0x22/0x30

value changed: 0x00000000000009a6 -> 0x00000000000009b2

Reported by Kernel Concurrency Sanitizer on:
CPU: 6 PID: 488 Comm: access_thread Not tainted 5.12.0-rc2+ #1
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.14.0-2 04/01/2014
==================================================================

The header of the report provides a short summary of the functions involved in the race. It is followed by the access types and stack traces of the 2 threads involved in the data race. If KCSAN also observed a value change, the observed old value and new value are shown on the "value changed" line respectively.

The other less common type of data race report looks like this:

==================================================================
BUG: KCSAN: data-race in test_kernel_rmw_array+0x71/0xd0

race at unknown origin, with read to 0xffffffffc009bdb0 of 8 bytes by task 515 on cpu 2:
 test_kernel_rmw_array+0x71/0xd0
 access_thread+0x89/0xd0
 kthread+0x23e/0x260
 ret_from_fork+0x22/0x30

value changed: 0x0000000000002328 -> 0x0000000000002329

Reported by Kernel Concurrency Sanitizer on:
CPU: 2 PID: 515 Comm: access_thread Not tainted 5.12.0-rc2+ #1
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.14.0-2 04/01/2014
==================================================================

This report is generated where it was not possible to determine the other racing thread, but a race was inferred due to the data value of the watched memory location having changed. These reports always show a "value changed" line. A common reason for reports of this type are missing instrumentation in the racing thread, but could also occur due to e.g. DMA accesses. Such reports are shown only if CONFIG_KCSAN_REPORT_RACE_UNKNOWN_ORIGIN=y, which is enabled by default.

Selective analysis #

It may be desirable to disable data race detection for specific accesses, functions, compilation units, or entire subsystems. For static blacklisting, the below options are available:

  • KCSAN understands the data_race(expr) annotation, which tells KCSAN that any data races due to accesses in expr should be ignored and resulting behaviour when encountering a data race is deemed safe. Please see "Marking Shared-Memory Accesses" in the LKMM for more information.

  • Similar to data_race(...), the type qualifier __data_racy can be used to document that all data races due to accesses to a variable are intended and should be ignored by KCSAN:

    struct foo {
        ...
        int __data_racy stats_counter;
        ...
    };
    
  • Disabling data race detection for entire functions can be accomplished by using the function attribute __no_kcsan:

    __no_kcsan
    void foo(void) {
        ...
    

    To dynamically limit for which functions to generate reports, see the DebugFS interface blacklist/whitelist feature.

  • To disable data race detection for a particular compilation unit, add to the Makefile:

    KCSAN_SANITIZE_file.o := n
    
  • To disable data race detection for all compilation units listed in a Makefile, add to the respective Makefile:

    KCSAN_SANITIZE := n
    

Furthermore, it is possible to tell KCSAN to show or hide entire classes of data races, depending on preferences. These can be changed via the following Kconfig options:

  • CONFIG_KCSAN_REPORT_VALUE_CHANGE_ONLY: If enabled and a conflicting write is observed via a watchpoint, but the data value of the memory location was observed to remain unchanged, do not report the data race.

  • CONFIG_KCSAN_ASSUME_PLAIN_WRITES_ATOMIC: Assume that plain aligned writes up to word size are atomic by default. Assumes that such writes are not subject to unsafe compiler optimizations resulting in data races. The option causes KCSAN to not report data races due to conflicts where the only plain accesses are aligned writes up to word size.

  • CONFIG_KCSAN_PERMISSIVE: Enable additional permissive rules to ignore certain classes of common data races. Unlike the above, the rules are more complex involving value-change patterns, access type, and address. This option depends on CONFIG_KCSAN_REPORT_VALUE_CHANGE_ONLY=y. For details please see the kernel/kcsan/permissive.h. Testers and maintainers that only focus on reports from specific subsystems and not the whole kernel are recommended to disable this option.

To use the strictest possible rules, select CONFIG_KCSAN_STRICT=y, which configures KCSAN to follow the Linux-kernel memory consistency model (LKMM) as closely as possible.

DebugFS interface #

The file /sys/kernel/debug/kcsan provides the following interface:

  • Reading /sys/kernel/debug/kcsan returns various runtime statistics.

  • Writing on or off to /sys/kernel/debug/kcsan allows turning KCSAN on or off, respectively.

  • Writing !some_func_name to /sys/kernel/debug/kcsan adds some_func_name to the report filter list, which (by default) blacklists reporting data races where either one of the top stackframes are a function in the list.

  • Writing either blacklist or whitelist to /sys/kernel/debug/kcsan changes the report filtering behaviour. For example, the blacklist feature can be used to silence frequently occurring data races; the whitelist feature can help with reproduction and testing of fixes.

Tuning performance #

Core parameters that affect KCSAN's overall performance and bug detection ability are exposed as kernel command-line arguments whose defaults can also be changed via the corresponding Kconfig options.

  • kcsan.skip_watch (CONFIG_KCSAN_SKIP_WATCH): Number of per-CPU memory operations to skip, before another watchpoint is set up. Setting up watchpoints more frequently will result in the likelihood of races to be observed to increase. This parameter has the most significant impact on overall system performance and race detection ability.

  • kcsan.udelay_task (CONFIG_KCSAN_UDELAY_TASK): For tasks, the microsecond delay to stall execution after a watchpoint has been set up. Larger values result in the window in which we may observe a race to increase.

  • kcsan.udelay_interrupt (CONFIG_KCSAN_UDELAY_INTERRUPT): For interrupts, the microsecond delay to stall execution after a watchpoint has been set up. Interrupts have tighter latency requirements, and their delay should generally be smaller than the one chosen for tasks.

They may be tweaked at runtime via /sys/module/kcsan/parameters/.

Data Races #

In an execution, two memory accesses form a data race if they conflict, they happen concurrently in different threads, and at least one of them is a plain access; they conflict if both access the same memory location, and at least one is a write. For a more thorough discussion and definition, see "Plain Accesses and Data Races" in the LKMM.

Relationship with the Linux-Kernel Memory Consistency Model (LKMM) #

The LKMM defines the propagation and ordering rules of various memory operations, which gives developers the ability to reason about concurrent code. Ultimately this allows to determine the possible executions of concurrent code, and if that code is free from data races.

KCSAN is aware of marked atomic operations (READ_ONCE, WRITE_ONCE, atomic_*, etc.), and a subset of ordering guarantees implied by memory barriers. With CONFIG_KCSAN_WEAK_MEMORY=y, KCSAN models load or store buffering, and can detect missing smp_mb(), smp_wmb(), smp_rmb(), smp_store_release(), and all atomic_* operations with equivalent implied barriers.

Note, KCSAN will not report all data races due to missing memory ordering, specifically where a memory barrier would be required to prohibit subsequent memory operation from reordering before the barrier. Developers should therefore carefully consider the required memory ordering requirements that remain unchecked.

Race Detection Beyond Data Races #

For code with complex concurrency design, race-condition bugs may not always manifest as data races. Race conditions occur if concurrently executing operations result in unexpected system behaviour. On the other hand, data races are defined at the C-language level. The following macros can be used to check properties of concurrent code where bugs would not manifest as data races.

ASSERT_EXCLUSIVE_WRITER() #

ASSERT_EXCLUSIVE_WRITER(var)

assert no concurrent writes to var

Parameters

  • var: variable to assert on

Description

Assert that there are no concurrent writes to var; other readers are allowed. This assertion can be used to specify properties of concurrent code, where violation cannot be detected as a normal data race.

For example, if we only have a single writer, but multiple concurrent readers, to avoid data races, all these accesses must be marked; even concurrent marked writes racing with the single writer are bugs. Unfortunately, due to being marked, they are no longer data races. For cases like these, we can use the macro as follows:

void writer(void) {
        spin_lock(&update_foo_lock);
        ASSERT_EXCLUSIVE_WRITER(shared_foo);
        WRITE_ONCE(shared_foo, ...);
        spin_unlock(&update_foo_lock);
}
void reader(void) {
        // update_foo_lock does not need to be held!
        ... = READ_ONCE(shared_foo);
}

Note

ASSERT_EXCLUSIVE_WRITER_SCOPED(), if applicable, performs more thorough checking if a clear scope where no concurrent writes are expected exists.

ASSERT_EXCLUSIVE_WRITER_SCOPED() #

ASSERT_EXCLUSIVE_WRITER_SCOPED(var)

assert no concurrent writes to var in scope

Parameters

  • var: variable to assert on

Description

Scoped variant of ASSERT_EXCLUSIVE_WRITER().

Assert that there are no concurrent writes to var for the duration of the scope in which it is introduced. This provides a better way to fully cover the enclosing scope, compared to multiple ASSERT_EXCLUSIVE_WRITER(), and increases the likelihood for KCSAN to detect racing accesses.

For example, it allows finding race-condition bugs that only occur due to state changes within the scope itself:

void writer(void) {
        spin_lock(&update_foo_lock);
        {
                ASSERT_EXCLUSIVE_WRITER_SCOPED(shared_foo);
                WRITE_ONCE(shared_foo, 42);
                ...
                // shared_foo should still be 42 here!
        }
        spin_unlock(&update_foo_lock);
}
void buggy(void) {
        if (READ_ONCE(shared_foo) == 42)
                WRITE_ONCE(shared_foo, 1); // bug!
}

ASSERT_EXCLUSIVE_ACCESS() #

ASSERT_EXCLUSIVE_ACCESS(var)

assert no concurrent accesses to var

Parameters

  • var: variable to assert on

Description

Assert that there are no concurrent accesses to var (no readers nor writers). This assertion can be used to specify properties of concurrent code, where violation cannot be detected as a normal data race.

For example, where exclusive access is expected after determining no other users of an object are left, but the object is not actually freed. We can check that this property actually holds as follows:

if (refcount_dec_and_test(&obj->refcnt)) {
        ASSERT_EXCLUSIVE_ACCESS(*obj);
        do_some_cleanup(obj);
        release_for_reuse(obj);
}

Note

  1. ASSERT_EXCLUSIVE_ACCESS_SCOPED(), if applicable, performs more thorough checking if a clear scope where no concurrent accesses are expected exists.

  2. For cases where the object is freed, KASAN is a better fit to detect use-after-free bugs.

ASSERT_EXCLUSIVE_ACCESS_SCOPED() #

ASSERT_EXCLUSIVE_ACCESS_SCOPED(var)

assert no concurrent accesses to var in scope

Parameters

  • var: variable to assert on

Description

Scoped variant of ASSERT_EXCLUSIVE_ACCESS().

Assert that there are no concurrent accesses to var (no readers nor writers) for the entire duration of the scope in which it is introduced. This provides a better way to fully cover the enclosing scope, compared to multiple ASSERT_EXCLUSIVE_ACCESS(), and increases the likelihood for KCSAN to detect racing accesses.

ASSERT_EXCLUSIVE_BITS() #

ASSERT_EXCLUSIVE_BITS(var, mask)

assert no concurrent writes to subset of bits in var

Parameters

  • var: variable to assert on
  • mask: only check for modifications to bits set in mask

Description

Bit-granular variant of ASSERT_EXCLUSIVE_WRITER().

Assert that there are no concurrent writes to a subset of bits in var; concurrent readers are permitted. This assertion captures more detailed bit-level properties, compared to the other (word granularity) assertions. Only the bits set in mask are checked for concurrent modifications, while ignoring the remaining bits, i.e. concurrent writes (or reads) to ~mask bits are ignored.

Use this for variables, where some bits must not be modified concurrently, yet other bits are expected to be modified concurrently.

For example, variables where, after initialization, some bits are read-only, but other bits may still be modified concurrently. A reader may wish to assert that this is true as follows:

ASSERT_EXCLUSIVE_BITS(flags, READ_ONLY_MASK);
foo = (READ_ONCE(flags) & READ_ONLY_MASK) >> READ_ONLY_SHIFT;

Note

The access that immediately follows ASSERT_EXCLUSIVE_BITS() is assumed to access the masked bits only, and KCSAN optimistically assumes it is therefore safe, even in the presence of data races, and marking it with READ_ONCE() is optional from KCSAN's point-of-view. We caution, however, that it may still be advisable to do so, since we cannot reason about all compiler optimizations when it comes to bit manipulations (on the reader and writer side). If you are sure nothing can go wrong, we can write the above simply as:

ASSERT_EXCLUSIVE_BITS(flags, READ_ONLY_MASK);
foo = (flags & READ_ONLY_MASK) >> READ_ONLY_SHIFT;

Another example, where this may be used, is when certain bits of var may only be modified when holding the appropriate lock, but other bits may still be modified concurrently. Writers, where other bits may change concurrently, could use the assertion as follows:

spin_lock(&foo_lock);
ASSERT_EXCLUSIVE_BITS(flags, FOO_MASK);
old_flags = flags;
new_flags = (old_flags & ~FOO_MASK) | (new_foo << FOO_SHIFT);
if (cmpxchg(&flags, old_flags, new_flags) != old_flags) { ... }
spin_unlock(&foo_lock);

Implementation Details #

KCSAN relies on observing that two accesses happen concurrently. Crucially, we want to (a) increase the chances of observing races (especially for races that manifest rarely), and (b) be able to actually observe them. We can accomplish (a) by injecting various delays, and (b) by using address watchpoints (or breakpoints).

If we deliberately stall a memory access, while we have a watchpoint for its address set up, and then observe the watchpoint to fire, two accesses to the same address just raced. Using hardware watchpoints, this is the approach taken in DataCollider. Unlike DataCollider, KCSAN does not use hardware watchpoints, but instead relies on compiler instrumentation and "soft watchpoints".

In KCSAN, watchpoints are implemented using an efficient encoding that stores access type, size, and address in a long; the benefits of using "soft watchpoints" are portability and greater flexibility. KCSAN then relies on the compiler instrumenting plain accesses. For each instrumented plain access:

  1. Check if a matching watchpoint exists; if yes, and at least one access is a write, then we encountered a racing access.

  2. Periodically, if no matching watchpoint exists, set up a watchpoint and stall for a small randomized delay.

  3. Also check the data value before the delay, and re-check the data value after delay; if the values mismatch, we infer a race of unknown origin.

To detect data races between plain and marked accesses, KCSAN also annotates marked accesses, but only to check if a watchpoint exists; i.e. KCSAN never sets up a watchpoint on marked accesses. By never setting up watchpoints for marked operations, if all accesses to a variable that is accessed concurrently are properly marked, KCSAN will never trigger a watchpoint and therefore never report the accesses.

Modeling Weak Memory #

KCSAN's approach to detecting data races due to missing memory barriers is based on modeling access reordering (with CONFIG_KCSAN_WEAK_MEMORY=y). Each plain memory access for which a watchpoint is set up, is also selected for simulated reordering within the scope of its function (at most 1 in-flight access).

Once an access has been selected for reordering, it is checked along every other access until the end of the function scope. If an appropriate memory barrier is encountered, the access will no longer be considered for simulated reordering.

When the result of a memory operation should be ordered by a barrier, KCSAN can then detect data races where the conflict only occurs as a result of a missing barrier. Consider the example:

int x, flag;
void T1(void)
{
    x = 1;                  // data race!
    WRITE_ONCE(flag, 1);    // correct: smp_store_release(&flag, 1)
}
void T2(void)
{
    while (!READ_ONCE(flag));   // correct: smp_load_acquire(&flag)
    ... = x;                    // data race!
}

When weak memory modeling is enabled, KCSAN can consider x in T1 for simulated reordering. After the write of flag, x is again checked for concurrent accesses: because T2 is able to proceed after the write of flag, a data race is detected. With the correct barriers in place, x would not be considered for reordering after the proper release of flag, and no data race would be detected.

Deliberate trade-offs in complexity but also practical limitations mean only a subset of data races due to missing memory barriers can be detected. With currently available compiler support, the implementation is limited to modeling the effects of "buffering" (delaying accesses), since the runtime cannot "prefetch" accesses. Also recall that watchpoints are only set up for plain accesses, and the only access type for which KCSAN simulates reordering. This means reordering of marked accesses is not modeled.

A consequence of the above is that acquire operations do not require barrier instrumentation (no prefetching). Furthermore, marked accesses introducing address or control dependencies do not require special handling (the marked access cannot be reordered, later dependent accesses cannot be prefetched).

Key Properties #

  1. Memory Overhead: The overall memory overhead is only a few MiB depending on configuration. The current implementation uses a small array of longs to encode watchpoint information, which is negligible.

  2. Performance Overhead: KCSAN's runtime aims to be minimal, using an efficient watchpoint encoding that does not require acquiring any shared locks in the fast-path. For kernel boot on a system with 8 CPUs:

    • 5.0x slow-down with the default KCSAN config;

    • 2.8x slow-down from runtime fast-path overhead only (set very large KCSAN_SKIP_WATCH and unset KCSAN_SKIP_WATCH_RANDOMIZE).

  3. Annotation Overheads: Minimal annotations are required outside the KCSAN runtime. As a result, maintenance overheads are minimal as the kernel evolves.

  4. Detects Racy Writes from Devices: Due to checking data values upon setting up watchpoints, racy writes from devices can also be detected.

  5. Memory Ordering: KCSAN is aware of only a subset of LKMM ordering rules; this may result in missed data races (false negatives).

  6. Analysis Accuracy: For observed executions, due to using a sampling strategy, the analysis is unsound (false negatives possible), but aims to be complete (no false positives).

Alternatives Considered #

An alternative data race detection approach for the kernel can be found in the Kernel Thread Sanitizer (KTSAN). KTSAN is a happens-before data race detector, which explicitly establishes the happens-before order between memory operations, which can then be used to determine data races as defined in Data Races.

To build a correct happens-before relation, KTSAN must be aware of all ordering rules of the LKMM and synchronization primitives. Unfortunately, any omission leads to large numbers of false positives, which is especially detrimental in the context of the kernel which includes numerous custom synchronization mechanisms. To track the happens-before relation, KTSAN's implementation requires metadata for each memory location (shadow memory), which for each page corresponds to 4 pages of shadow memory, and can translate into overhead of tens of GiB on a large system.

Kernel Electric-Fence (KFENCE)

Peios Kernel / Kernel development / Development tools

Kernel Electric-Fence (KFENCE) is a low-overhead sampling-based memory safety error detector. KFENCE detects heap out-of-bounds access, use-after-free, and invalid-free errors.

KFENCE is designed to be enabled in production kernels, and has near zero performance overhead. Compared to KASAN, KFENCE trades performance for precision. The main motivation behind KFENCE's design, is that with enough total uptime KFENCE will detect bugs in code paths not typically exercised by non-production test workloads. One way to quickly achieve a large enough total uptime is when the tool is deployed across a large fleet of machines.

Usage #

To enable KFENCE, configure the kernel with:

CONFIG_KFENCE=y

To build a kernel with KFENCE support, but disabled by default (to enable, set kfence.sample_interval to non-zero value), configure the kernel with:

CONFIG_KFENCE=y
CONFIG_KFENCE_SAMPLE_INTERVAL=0

KFENCE provides several other configuration options to customize behaviour (see the respective help text in lib/Kconfig.kfence for more info).

Tuning performance #

The most important parameter is KFENCE's sample interval, which can be set via the kernel boot parameter kfence.sample_interval in milliseconds. The sample interval determines the frequency with which heap allocations will be guarded by KFENCE. The default is configurable via the Kconfig option CONFIG_KFENCE_SAMPLE_INTERVAL. Setting kfence.sample_interval=0 disables KFENCE.

The sample interval controls a timer that sets up KFENCE allocations. By default, to keep the real sample interval predictable, the normal timer also causes CPU wake-ups when the system is completely idle. This may be undesirable on power-constrained systems. The boot parameter kfence.deferrable=1 instead switches to a "deferrable" timer which does not force CPU wake-ups on idle systems, at the risk of unpredictable sample intervals. The default is configurable via the Kconfig option CONFIG_KFENCE_DEFERRABLE.

Warning

The KUnit test suite is very likely to fail when using a deferrable timer since it currently causes very unpredictable sample intervals.

By default KFENCE will only sample 1 heap allocation within each sample interval. Burst mode allows to sample successive heap allocations, where the kernel boot parameter kfence.burst can be set to a non-zero value which denotes the additional successive allocations within a sample interval; setting kfence.burst=N means that 1 + N successive allocations are attempted through KFENCE for each sample interval.

The KFENCE memory pool is of fixed size, and if the pool is exhausted, no further KFENCE allocations occur. With CONFIG_KFENCE_NUM_OBJECTS (default 255), the number of available guarded objects can be controlled. Each object requires 2 pages, one for the object itself and the other one used as a guard page; object pages are interleaved with guard pages, and every object page is therefore surrounded by two guard pages.

The total memory dedicated to the KFENCE memory pool can be computed as:

( #objects + 1 ) * 2 * PAGE_SIZE

Using the default config, and assuming a page size of 4 KiB, results in dedicating 2 MiB to the KFENCE memory pool.

Note: On architectures that support huge pages, KFENCE will ensure that the pool is using pages of size PAGE_SIZE. This will result in additional page tables being allocated.

Error reports #

A typical out-of-bounds access looks like this:

==================================================================
BUG: KFENCE: out-of-bounds read in test_out_of_bounds_read+0xa6/0x234

Out-of-bounds read at 0xffff8c3f2e291fff (1B left of kfence-#72):
 test_out_of_bounds_read+0xa6/0x234
 kunit_try_run_case+0x61/0xa0
 kunit_generic_run_threadfn_adapter+0x16/0x30
 kthread+0x176/0x1b0
 ret_from_fork+0x22/0x30

kfence-#72: 0xffff8c3f2e292000-0xffff8c3f2e29201f, size=32, cache=kmalloc-32

allocated by task 484 on cpu 0 at 32.919330s:
 test_alloc+0xfe/0x738
 test_out_of_bounds_read+0x9b/0x234
 kunit_try_run_case+0x61/0xa0
 kunit_generic_run_threadfn_adapter+0x16/0x30
 kthread+0x176/0x1b0
 ret_from_fork+0x22/0x30

CPU: 0 PID: 484 Comm: kunit_try_catch Not tainted 5.13.0-rc3+ #7
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.14.0-2 04/01/2014
==================================================================

The header of the report provides a short summary of the function involved in the access. It is followed by more detailed information about the access and its origin. Note that, real kernel addresses are only shown when using the kernel command line option no_hash_pointers.

Use-after-free accesses are reported as:

==================================================================
BUG: KFENCE: use-after-free read in test_use_after_free_read+0xb3/0x143

Use-after-free read at 0xffff8c3f2e2a0000 (in kfence-#79):
 test_use_after_free_read+0xb3/0x143
 kunit_try_run_case+0x61/0xa0
 kunit_generic_run_threadfn_adapter+0x16/0x30
 kthread+0x176/0x1b0
 ret_from_fork+0x22/0x30

kfence-#79: 0xffff8c3f2e2a0000-0xffff8c3f2e2a001f, size=32, cache=kmalloc-32

allocated by task 488 on cpu 2 at 33.871326s:
 test_alloc+0xfe/0x738
 test_use_after_free_read+0x76/0x143
 kunit_try_run_case+0x61/0xa0
 kunit_generic_run_threadfn_adapter+0x16/0x30
 kthread+0x176/0x1b0
 ret_from_fork+0x22/0x30

freed by task 488 on cpu 2 at 33.871358s:
 test_use_after_free_read+0xa8/0x143
 kunit_try_run_case+0x61/0xa0
 kunit_generic_run_threadfn_adapter+0x16/0x30
 kthread+0x176/0x1b0
 ret_from_fork+0x22/0x30

CPU: 2 PID: 488 Comm: kunit_try_catch Tainted: G    B             5.13.0-rc3+ #7
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.14.0-2 04/01/2014
==================================================================

KFENCE also reports on invalid frees, such as double-frees:

==================================================================
BUG: KFENCE: invalid free in test_double_free+0xdc/0x171

Invalid free of 0xffff8c3f2e2a4000 (in kfence-#81):
 test_double_free+0xdc/0x171
 kunit_try_run_case+0x61/0xa0
 kunit_generic_run_threadfn_adapter+0x16/0x30
 kthread+0x176/0x1b0
 ret_from_fork+0x22/0x30

kfence-#81: 0xffff8c3f2e2a4000-0xffff8c3f2e2a401f, size=32, cache=kmalloc-32

allocated by task 490 on cpu 1 at 34.175321s:
 test_alloc+0xfe/0x738
 test_double_free+0x76/0x171
 kunit_try_run_case+0x61/0xa0
 kunit_generic_run_threadfn_adapter+0x16/0x30
 kthread+0x176/0x1b0
 ret_from_fork+0x22/0x30

freed by task 490 on cpu 1 at 34.175348s:
 test_double_free+0xa8/0x171
 kunit_try_run_case+0x61/0xa0
 kunit_generic_run_threadfn_adapter+0x16/0x30
 kthread+0x176/0x1b0
 ret_from_fork+0x22/0x30

CPU: 1 PID: 490 Comm: kunit_try_catch Tainted: G    B             5.13.0-rc3+ #7
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.14.0-2 04/01/2014
==================================================================

KFENCE also uses pattern-based redzones on the other side of an object's guard page, to detect out-of-bounds writes on the unprotected side of the object. These are reported on frees:

==================================================================
BUG: KFENCE: memory corruption in test_kmalloc_aligned_oob_write+0xef/0x184

Corrupted memory at 0xffff8c3f2e33aff9 [ 0xac . . . . . . ] (in kfence-#156):
 test_kmalloc_aligned_oob_write+0xef/0x184
 kunit_try_run_case+0x61/0xa0
 kunit_generic_run_threadfn_adapter+0x16/0x30
 kthread+0x176/0x1b0
 ret_from_fork+0x22/0x30

kfence-#156: 0xffff8c3f2e33afb0-0xffff8c3f2e33aff8, size=73, cache=kmalloc-96

allocated by task 502 on cpu 7 at 42.159302s:
 test_alloc+0xfe/0x738
 test_kmalloc_aligned_oob_write+0x57/0x184
 kunit_try_run_case+0x61/0xa0
 kunit_generic_run_threadfn_adapter+0x16/0x30
 kthread+0x176/0x1b0
 ret_from_fork+0x22/0x30

CPU: 7 PID: 502 Comm: kunit_try_catch Tainted: G    B             5.13.0-rc3+ #7
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.14.0-2 04/01/2014
==================================================================

For such errors, the address where the corruption occurred as well as the invalidly written bytes (offset from the address) are shown; in this representation, '.' denote untouched bytes. In the example above 0xac is the value written to the invalid address at offset 0, and the remaining '.' denote that no following bytes have been touched. Note that, real values are only shown if the kernel was booted with no_hash_pointers; to avoid information disclosure otherwise, '!' is used instead to denote invalidly written bytes.

And finally, KFENCE may also report on invalid accesses to any protected page where it was not possible to determine an associated object, e.g. if adjacent object pages had not yet been allocated:

==================================================================
BUG: KFENCE: invalid read in test_invalid_access+0x26/0xe0

Invalid read at 0xffffffffb670b00a:
 test_invalid_access+0x26/0xe0
 kunit_try_run_case+0x51/0x85
 kunit_generic_run_threadfn_adapter+0x16/0x30
 kthread+0x137/0x160
 ret_from_fork+0x22/0x30

CPU: 4 PID: 124 Comm: kunit_try_catch Tainted: G        W         5.8.0-rc6+ #7
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.13.0-1 04/01/2014
==================================================================

DebugFS interface #

Some debugging information is exposed via debugfs:

  • The file /sys/kernel/debug/kfence/stats provides runtime statistics.

  • The file /sys/kernel/debug/kfence/objects provides a list of objects allocated via KFENCE, including those already freed but protected.

Implementation Details #

Guarded allocations are set up based on the sample interval. After expiration of the sample interval, the next allocation through the main allocator (SLAB or SLUB) returns a guarded allocation from the KFENCE object pool (allocation sizes up to PAGE_SIZE are supported). At this point, the timer is reset, and the next allocation is set up after the expiration of the interval.

When using CONFIG_KFENCE_STATIC_KEYS=y, KFENCE allocations are "gated" through the main allocator's fast-path by relying on static branches via the static keys infrastructure. The static branch is toggled to redirect the allocation to KFENCE. Depending on sample interval, target workloads, and system architecture, this may perform better than the simple dynamic branch. Careful benchmarking is recommended.

KFENCE objects each reside on a dedicated page, at either the left or right page boundaries selected at random. The pages to the left and right of the object page are "guard pages", whose attributes are changed to a protected state, and cause page faults on any attempted access. Such page faults are then intercepted by KFENCE, which handles the fault gracefully by reporting an out-of-bounds access, and marking the page as accessible so that the faulting code can (wrongly) continue executing (set panic_on_warn to panic instead).

To detect out-of-bounds writes to memory within the object's page itself, KFENCE also uses pattern-based redzones. For each object page, a redzone is set up for all non-object memory. For typical alignments, the redzone is only required on the unguarded side of an object. Because KFENCE must honor the cache's requested alignment, special alignments may result in unprotected gaps on either side of an object, all of which are redzoned.

The following figure illustrates the page layout:

---+-----------+-----------+-----------+-----------+-----------+---
   | xxxxxxxxx | O :       | xxxxxxxxx |       : O | xxxxxxxxx |
   | xxxxxxxxx | B :       | xxxxxxxxx |       : B | xxxxxxxxx |
   | x GUARD x | J : RED-  | x GUARD x | RED-  : J | x GUARD x |
   | xxxxxxxxx | E :  ZONE | xxxxxxxxx |  ZONE : E | xxxxxxxxx |
   | xxxxxxxxx | C :       | xxxxxxxxx |       : C | xxxxxxxxx |
   | xxxxxxxxx | T :       | xxxxxxxxx |       : T | xxxxxxxxx |
---+-----------+-----------+-----------+-----------+-----------+---

Upon deallocation of a KFENCE object, the object's page is again protected and the object is marked as freed. Any further access to the object causes a fault and KFENCE reports a use-after-free access. Freed objects are inserted at the tail of KFENCE's freelist, so that the least recently freed objects are reused first, and the chances of detecting use-after-frees of recently freed objects is increased.

If pool utilization reaches 75% (default) or above, to reduce the risk of the pool eventually being fully occupied by allocated objects yet ensure diverse coverage of allocations, KFENCE limits currently covered allocations of the same source from further filling up the pool. The "source" of an allocation is based on its partial allocation stack trace. A side-effect is that this also limits frequent long-lived allocations (e.g. pagecache) of the same source filling up the pool permanently, which is the most common risk for the pool becoming full and the sampled allocation rate dropping to zero. The threshold at which to start limiting currently covered allocations can be configured via the boot parameter kfence.skip_covered_thresh (pool usage%).

Interface #

The following describes the functions which are used by allocators as well as page handling code to set up and deal with KFENCE allocations.

is_kfence_address() #

bool is_kfence_address(const void *addr)

check if an address belongs to KFENCE pool

Parameters

  • const void *addr: address to check

Return

true or false depending on whether the address is within the KFENCE object range.

Description

KFENCE objects live in a separate page range and are not to be intermixed with regular heap objects (e.g. KFENCE objects must never be added to the allocator freelists). Failing to do so may and will result in heap corruptions, therefore is_kfence_address() must be used to check whether an object requires specific handling.

Note

This function may be used in fast-paths, and is performance critical. Future changes should take this into account; for instance, we want to avoid introducing another load and therefore need to keep KFENCE_POOL_SIZE a constant (until immediate patching support is added to the kernel).

kfence_shutdown_cache() #

void kfence_shutdown_cache(struct kmem_cache *s)

handle shutdown_cache() for KFENCE objects

Parameters

  • struct kmem_cache *s: cache being shut down

Description

Before shutting down a cache, one must ensure there are no remaining objects allocated from it. Because KFENCE objects are not referenced from the cache directly, we need to check them here.

Note that shutdown_cache() is internal to SL*B, and kmem_cache_destroy() does not return if allocated objects still exist: it prints an error message and simply aborts destruction of a cache, leaking memory.

If the only such objects are KFENCE objects, we will not leak the entire cache, but instead try to provide more useful debug info by making allocated objects "zombie allocations". Objects may then still be used or freed (which is handled gracefully), but usage will result in showing KFENCE error reports which include stack traces to the user of the object, the original allocation site, and caller to shutdown_cache().

kfence_alloc() #

void * kfence_alloc(struct kmem_cache *s, size_t size, gfp_t flags)

allocate a KFENCE object with a low probability

Parameters

  • struct kmem_cache *s: struct kmem_cache with object requirements
  • size_t size: exact size of the object to allocate (can be less than s->size e.g. for kmalloc caches)
  • gfp_t flags: GFP flags

Return

  • NULL - must proceed with allocating as usual,
  • non-NULL - pointer to a KFENCE object.

Description

kfence_alloc() should be inserted into the heap allocation fast path, allowing it to transparently return KFENCE-allocated objects with a low probability using a static branch (the probability is controlled by the kfence.sample_interval boot parameter).

kfence_ksize() #

size_t kfence_ksize(const void *addr)

get actual amount of memory allocated for a KFENCE object

Parameters

  • const void *addr: pointer to a heap object

Return

  • 0 - not a KFENCE object, must call __ksize() instead,
  • non-0 - this many bytes can be accessed without causing a memory error.

Description

kfence_ksize() returns the number of bytes requested for a KFENCE object at allocation time. This number may be less than the object size of the corresponding struct kmem_cache.

kfence_object_start() #

void * kfence_object_start(const void *addr)

find the beginning of a KFENCE object

Parameters

  • const void *addr: address within a KFENCE-allocated object

Return

address of the beginning of the object.

Description

SL[AU]B-allocated objects are laid out within a page one by one, so it is easy to calculate the beginning of an object given a pointer inside it and the object size. The same is not true for KFENCE, which places a single object at either end of the page. This helper function is used to find the beginning of a KFENCE-allocated object.

__kfence_free() #

void __kfence_free(void *addr)

release a KFENCE heap object to KFENCE pool

Parameters

  • void *addr: object to be freed

Description

Requires: is_kfence_address(addr)

Release a KFENCE object and mark it as freed.

kfence_free() #

bool kfence_free(void *addr)

try to release an arbitrary heap object to KFENCE pool

Parameters

  • void *addr: object to be freed

Return

  • false - object doesn't belong to KFENCE pool and was ignored,
  • true - object was released to KFENCE pool.

Description

Release a KFENCE object and mark it as freed. May be called on any object, even non-KFENCE objects, to simplify integration of the hooks into the allocator's free codepath. The allocator must check the return value to determine if it was a KFENCE object or not.

kfence_handle_page_fault() #

bool kfence_handle_page_fault(unsigned long addr, bool is_write, struct pt_regs *regs)

perform page fault handling for KFENCE pages

Parameters

  • unsigned long addr: faulting address
  • bool is_write: is access a write
  • struct pt_regs *regs: current struct pt_regs (can be NULL, but shows full stack trace)

Return

  • false - address outside KFENCE pool,
  • true - page fault handled by KFENCE, no additional handling required.

Description

A page fault inside KFENCE pool indicates a memory error, such as an out-of-bounds access, a use-after-free or an invalid memory access. In these cases KFENCE prints an error message and marks the offending page as present, so that the kernel can proceed.

Related Tools #

In userspace, a similar approach is taken by GWP-ASan. GWP-ASan also relies on guard pages and a sampling strategy to detect memory unsafety bugs at scale. KFENCE's design is directly influenced by GWP-ASan, and can be seen as its kernel sibling. Another similar but non-sampling approach, that also inspired the name "KFENCE", can be found in the userspace Electric Fence Malloc Debugger.

In the kernel, several tools exist to debug memory access errors, and in particular KASAN can detect all bug classes that KFENCE can detect. While KASAN is more precise, relying on compiler instrumentation, this comes at a performance cost.

It is worth highlighting that KASAN and KFENCE are complementary, with different target environments. For instance, KASAN is the better debugging-aid, where test cases or reproducers exists: due to the lower chance to detect the error, it would require more effort using KFENCE to debug. Deployments at scale that cannot afford to enable KASAN, however, would benefit from using KFENCE to discover bugs due to code paths not exercised by test cases or fuzzers.

Kernel Memory Leak Detector

Peios Kernel / Kernel development / Development tools

Kmemleak provides a way of detecting possible kernel memory leaks in a way similar to a tracing garbage collector, with the difference that the orphan objects are not freed but only reported via /sys/kernel/debug/kmemleak. A similar method is used by the Valgrind tool (memcheck --leak-check) to detect the memory leaks in user-space applications.

Usage #

CONFIG_DEBUG_KMEMLEAK in "Kernel hacking" has to be enabled. A kernel thread scans the memory every 10 minutes (by default) and prints the number of new unreferenced objects found. If the debugfs isn't already mounted, mount with:

# mount -t debugfs nodev /sys/kernel/debug/

To display the details of all the possible scanned memory leaks:

# cat /sys/kernel/debug/kmemleak

To trigger an intermediate memory scan:

# echo scan > /sys/kernel/debug/kmemleak

To clear the list of all current possible memory leaks:

# echo clear > /sys/kernel/debug/kmemleak

New leaks will then come up upon reading /sys/kernel/debug/kmemleak again.

Note that the orphan objects are listed in the order they were allocated and one object at the beginning of the list may cause other subsequent objects to be reported as orphan.

Memory scanning parameters can be modified at run-time by writing to the /sys/kernel/debug/kmemleak file. The following parameters are supported:

    • off

      disable kmemleak (irreversible)

    • stack=on

      enable the task stacks scanning (default)

    • stack=off

      disable the tasks stacks scanning

    • scan=on

      start the automatic memory scanning thread (default)

    • scan=off

      stop the automatic memory scanning thread

    • scan=<secs>

      set the automatic memory scanning period in seconds (default 600, 0 to stop the automatic scanning)

    • scan

      trigger a memory scan

    • clear

      clear list of current memory leak suspects, done by marking all current reported unreferenced objects grey, or free all kmemleak objects if kmemleak has been disabled.

    • dump=<addr>

      dump information about the object found at <addr>

Kmemleak can also be disabled at boot-time by passing kmemleak=off on the kernel command line.

Memory may be allocated or freed before kmemleak is initialised and these actions are stored in an early log buffer. The size of this buffer is configured via the CONFIG_DEBUG_KMEMLEAK_MEM_POOL_SIZE option.

If CONFIG_DEBUG_KMEMLEAK_DEFAULT_OFF are enabled, the kmemleak is disabled by default. Passing kmemleak=on on the kernel command line enables the function.

If you are getting errors like "Error while writing to stdout" or "write_loop: Invalid argument", make sure kmemleak is properly enabled.

Basic Algorithm #

The memory allocations via kmalloc(), vmalloc(), kmem_cache_alloc() and friends are traced and the pointers, together with additional information like size and stack trace, are stored in a rbtree. The corresponding freeing function calls are tracked and the pointers removed from the kmemleak data structures.

An allocated block of memory is considered orphan if no pointer to its start address or to any location inside the block can be found by scanning the memory (including saved registers). This means that there might be no way for the kernel to pass the address of the allocated block to a freeing function and therefore the block is considered a memory leak.

The scanning algorithm steps:

  1. mark all objects as white (remaining white objects will later be considered orphan)

  2. scan the memory starting with the data section and stacks, checking the values against the addresses stored in the rbtree. If a pointer to a white object is found, the object is added to the gray list

  3. scan the gray objects for matching addresses (some white objects can become gray and added at the end of the gray list) until the gray set is finished

  4. the remaining white objects are considered orphan and reported via /sys/kernel/debug/kmemleak

Some allocated memory blocks have pointers stored in the kernel's internal data structures and they cannot be detected as orphans. To avoid this, kmemleak can also store the number of values pointing to an address inside the block address range that need to be found so that the block is not considered a leak. One example is __vmalloc().

Testing specific sections with kmemleak #

Upon initial bootup your /sys/kernel/debug/kmemleak output page may be quite extensive. This can also be the case if you have very buggy code when doing development. To work around these situations you can use the 'clear' command to clear all reported unreferenced objects from the /sys/kernel/debug/kmemleak output. By issuing a 'scan' after a 'clear' you can find new unreferenced objects; this should help with testing specific sections of code.

To test a critical section on demand with a clean kmemleak do:

# echo clear > /sys/kernel/debug/kmemleak
... test your kernel or modules ...
# echo scan > /sys/kernel/debug/kmemleak

Then as usual to get your report with:

# cat /sys/kernel/debug/kmemleak

Freeing kmemleak internal objects #

To allow access to previously found memory leaks after kmemleak has been disabled by the user or due to an fatal error, internal kmemleak objects won't be freed when kmemleak is disabled, and those objects may occupy a large part of physical memory.

In this situation, you may reclaim memory with:

# echo clear > /sys/kernel/debug/kmemleak

Kmemleak API #

See the include/linux/kmemleak.h header for the functions prototype.

  • kmemleak_init - initialize kmemleak

  • kmemleak_alloc - notify of a memory block allocation

  • kmemleak_alloc_percpu - notify of a percpu memory block allocation

  • kmemleak_vmalloc - notify of a vmalloc() memory allocation

  • kmemleak_free - notify of a memory block freeing

  • kmemleak_free_part - notify of a partial memory block freeing

  • kmemleak_free_percpu - notify of a percpu memory block freeing

  • kmemleak_update_trace - update object allocation stack trace

  • kmemleak_not_leak - mark an object as not a leak

  • kmemleak_transient_leak - mark an object as a transient leak

  • kmemleak_ignore - do not scan or report an object as leak

  • kmemleak_scan_area - add scan areas inside a memory block

  • kmemleak_no_scan - do not scan a memory block

  • kmemleak_erase - erase an old value in a pointer variable

  • kmemleak_alloc_recursive - as kmemleak_alloc but checks the recursiveness

  • kmemleak_free_recursive - as kmemleak_free but checks the recursiveness

The following functions take a physical address as the object pointer and only perform the corresponding action if the address has a lowmem mapping:

  • kmemleak_alloc_phys

  • kmemleak_free_part_phys

  • kmemleak_ignore_phys

Dealing with false positives/negatives #

The false negatives are real memory leaks (orphan objects) but not reported by kmemleak because values found during the memory scanning point to such objects. To reduce the number of false negatives, kmemleak provides the kmemleak_ignore, kmemleak_scan_area, kmemleak_no_scan and kmemleak_erase functions (see above). The task stacks also increase the amount of false negatives and their scanning is not enabled by default.

The false positives are objects wrongly reported as being memory leaks (orphan). For objects known not to be leaks, kmemleak provides the kmemleak_not_leak function. The kmemleak_ignore could also be used if the memory block is known not to contain other pointers and it will no longer be scanned.

Some of the reported leaks are only transient, especially on SMP systems, because of pointers temporarily stored in CPU registers or stacks. Kmemleak defines MSECS_MIN_AGE (defaulting to 1000) representing the minimum age of an object to be reported as a memory leak.

Limitations and Drawbacks #

The main drawback is the reduced performance of memory allocation and freeing. To avoid other penalties, the memory scanning is only performed when the /sys/kernel/debug/kmemleak file is read. Anyway, this tool is intended for debugging purposes where the performance might not be the most important requirement.

To keep the algorithm simple, kmemleak scans for values pointing to any address inside a block's address range. This may lead to an increased number of false negatives. However, it is likely that a real memory leak will eventually become visible.

Another source of false negatives is the data stored in non-pointer values. In a future version, kmemleak could only scan the pointer members in the allocated structures. This feature would solve many of the false negative cases described above.

The tool can report false positives. These are cases where an allocated block doesn't need to be freed (some cases in the init_call functions), the pointer is calculated by other methods than the usual container_of macro or the pointer is stored in a location not scanned by kmemleak.

Page allocations and ioremap are not tracked.

Testing with kmemleak-test #

To check if you have all set up to use kmemleak, you can use the kmemleak-test module, a module that deliberately leaks memory. Set CONFIG_SAMPLE_KMEMLEAK as module (it can't be used as built-in) and boot the kernel with kmemleak enabled. Load the module and perform a scan with:

# modprobe kmemleak-test
# echo scan > /sys/kernel/debug/kmemleak

Note that the you may not get results instantly or on the first scanning. When kmemleak gets results, it'll log kmemleak: <count of leaks> new suspected memory leaks. Then read the file to see then:

# cat /sys/kernel/debug/kmemleak
unreferenced object 0xffff89862ca702e8 (size 32):
  comm "modprobe", pid 2088, jiffies 4294680594 (age 375.486s)
  hex dump (first 32 bytes):
    6b 6b 6b 6b 6b 6b 6b 6b 6b 6b 6b 6b 6b 6b 6b 6b  kkkkkkkkkkkkkkkk
    6b 6b 6b 6b 6b 6b 6b 6b 6b 6b 6b 6b 6b 6b 6b a5  kkkkkkkkkkkkkkk.
  backtrace:
    [<00000000e0a73ec7>] 0xffffffffc01d2036
    [<000000000c5d2a46>] do_one_initcall+0x41/0x1df
    [<0000000046db7e0a>] do_init_module+0x55/0x200
    [<00000000542b9814>] load_module+0x203c/0x2480
    [<00000000c2850256>] __do_sys_finit_module+0xba/0xe0
    [<000000006564e7ef>] do_syscall_64+0x43/0x110
    [<000000007c873fa6>] entry_SYSCALL_64_after_hwframe+0x44/0xa9
...

Removing the module with rmmod kmemleak_test should also trigger some kmemleak results.

Kernel Memory Sanitizer (KMSAN)

Peios Kernel / Kernel development / Development tools

KMSAN is a dynamic error detector aimed at finding uses of uninitialized values. It is based on compiler instrumentation, and is quite similar to the userspace MemorySanitizer tool.

An important note is that KMSAN is not intended for production use, because it drastically increases kernel memory footprint and slows the whole system down.

Usage #

Building the kernel #

In order to build a kernel with KMSAN you will need a fresh Clang (14.0.6+). Please refer to LLVM documentation for the instructions on how to build Clang.

Now configure and build the kernel with CONFIG_KMSAN enabled.

Example report #

Here is an example of a KMSAN report:

=====================================================
BUG: KMSAN: uninit-value in test_uninit_kmsan_check_memory+0x1be/0x380 [kmsan_test]
 test_uninit_kmsan_check_memory+0x1be/0x380 mm/kmsan/kmsan_test.c:273
 kunit_run_case_internal lib/kunit/test.c:333
 kunit_try_run_case+0x206/0x420 lib/kunit/test.c:374
 kunit_generic_run_threadfn_adapter+0x6d/0xc0 lib/kunit/try-catch.c:28
 kthread+0x721/0x850 kernel/kthread.c:327
 ret_from_fork+0x1f/0x30 ??:?

Uninit was stored to memory at:
 do_uninit_local_array+0xfa/0x110 mm/kmsan/kmsan_test.c:260
 test_uninit_kmsan_check_memory+0x1a2/0x380 mm/kmsan/kmsan_test.c:271
 kunit_run_case_internal lib/kunit/test.c:333
 kunit_try_run_case+0x206/0x420 lib/kunit/test.c:374
 kunit_generic_run_threadfn_adapter+0x6d/0xc0 lib/kunit/try-catch.c:28
 kthread+0x721/0x850 kernel/kthread.c:327
 ret_from_fork+0x1f/0x30 ??:?

Local variable uninit created at:
 do_uninit_local_array+0x4a/0x110 mm/kmsan/kmsan_test.c:256
 test_uninit_kmsan_check_memory+0x1a2/0x380 mm/kmsan/kmsan_test.c:271

Bytes 4-7 of 8 are uninitialized
Memory access of size 8 starts at ffff888083fe3da0

CPU: 0 PID: 6731 Comm: kunit_try_catch Tainted: G    B       E     5.16.0-rc3+ #104
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.14.0-2 04/01/2014
=====================================================

The report says that the local variable uninit was created uninitialized in do_uninit_local_array(). The third stack trace corresponds to the place where this variable was created.

The first stack trace shows where the uninit value was used (in test_uninit_kmsan_check_memory()). The tool shows the bytes which were left uninitialized in the local variable, as well as the stack where the value was copied to another memory location before use.

A use of uninitialized value v is reported by KMSAN in the following cases:

  • in a condition, e.g. if (v) { ... };

  • in an indexing or pointer dereferencing, e.g. array[v] or *v;

  • when it is copied to userspace or hardware, e.g. copy_to_user(..., &v, ...);

  • when it is passed as an argument to a function, and CONFIG_KMSAN_CHECK_PARAM_RETVAL is enabled (see below).

The mentioned cases (apart from copying data to userspace or hardware, which is a security issue) are considered undefined behavior from the C11 Standard point of view.

Disabling the instrumentation #

A function can be marked with __no_kmsan_checks. Doing so makes KMSAN ignore uninitialized values in that function and mark its output as initialized. As a result, the user will not get KMSAN reports related to that function.

Another function attribute supported by KMSAN is __no_sanitize_memory. Applying this attribute to a function will result in KMSAN not instrumenting it, which can be helpful if we do not want the compiler to interfere with some low-level code (e.g. that marked with noinstr which implicitly adds __no_sanitize_memory).

This however comes at a cost: stack allocations from such functions will have incorrect shadow/origin values, likely leading to false positives. Functions called from non-instrumented code may also receive incorrect metadata for their parameters.

As a rule of thumb, avoid using __no_sanitize_memory explicitly.

It is also possible to disable KMSAN for a single file (e.g. main.o):

KMSAN_SANITIZE_main.o := n

or for the whole directory:

KMSAN_SANITIZE := n

in the Makefile. Think of this as applying __no_sanitize_memory to every function in the file or directory. Most users won't need KMSAN_SANITIZE, unless their code gets broken by KMSAN (e.g. runs at early boot time).

KMSAN checks can also be temporarily disabled for the current task using kmsan_disable_current() and kmsan_enable_current() calls. Each kmsan_enable_current() call must be preceded by a kmsan_disable_current() call; these call pairs may be nested. One needs to be careful with these calls, keeping the regions short and preferring other ways to disable instrumentation, where possible.

Support #

In order for KMSAN to work the kernel must be built with Clang, which so far is the only compiler that has KMSAN support. The kernel instrumentation pass is based on the userspace MemorySanitizer tool.

The runtime library only supports x86_64 at the moment.

How KMSAN works #

KMSAN shadow memory #

KMSAN associates a metadata byte (also called shadow byte) with every byte of kernel memory. A bit in the shadow byte is set if the corresponding bit of the kernel memory byte is uninitialized. Marking the memory uninitialized (i.e. setting its shadow bytes to 0xff) is called poisoning, marking it initialized (setting the shadow bytes to 0x00) is called unpoisoning.

When a new variable is allocated on the stack, it is poisoned by default by instrumentation code inserted by the compiler (unless it is a stack variable that is immediately initialized). Any new heap allocation done without __GFP_ZERO is also poisoned.

Compiler instrumentation also tracks the shadow values as they are used along the code. When needed, instrumentation code invokes the runtime library in mm/kmsan/ to persist shadow values.

The shadow value of a basic or compound type is an array of bytes of the same length. When a constant value is written into memory, that memory is unpoisoned. When a value is read from memory, its shadow memory is also obtained and propagated into all the operations which use that value. For every instruction that takes one or more values the compiler generates code that calculates the shadow of the result depending on those values and their shadows.

Example:

int a = 0xff;  // i.e. 0x000000ff
int b;
int c = a | b;

In this case the shadow of a is 0, shadow of b is 0xffffffff, shadow of c is 0xffffff00. This means that the upper three bytes of c are uninitialized, while the lower byte is initialized.

Origin tracking #

Every four bytes of kernel memory also have a so-called origin mapped to them. This origin describes the point in program execution at which the uninitialized value was created. Every origin is associated with either the full allocation stack (for heap-allocated memory), or the function containing the uninitialized variable (for locals).

When an uninitialized variable is allocated on stack or heap, a new origin value is created, and that variable's origin is filled with that value. When a value is read from memory, its origin is also read and kept together with the shadow. For every instruction that takes one or more values, the origin of the result is one of the origins corresponding to any of the uninitialized inputs. If a poisoned value is written into memory, its origin is written to the corresponding storage as well.

Example 1:

int a = 42;
int b;
int c = a + b;

In this case the origin of b is generated upon function entry, and is stored to the origin of c right before the addition result is written into memory.

Several variables may share the same origin address, if they are stored in the same four-byte chunk. In this case every write to either variable updates the origin for all of them. We have to sacrifice precision in this case, because storing origins for individual bits (and even bytes) would be too costly.

Example 2:

int combine(short a, short b) {
  union ret_t {
    int i;
    short s[2];
  } ret;
  ret.s[0] = a;
  ret.s[1] = b;
  return ret.i;
}

If a is initialized and b is not, the shadow of the result would be 0xffff0000, and the origin of the result would be the origin of b. ret.s[0] would have the same origin, but it will never be used, because that variable is initialized.

If both function arguments are uninitialized, only the origin of the second argument is preserved.

Origin chaining #

To ease debugging, KMSAN creates a new origin for every store of an uninitialized value to memory. The new origin references both its creation stack and the previous origin the value had. This may cause increased memory consumption, so we limit the length of origin chains in the runtime.

Clang instrumentation API #

Clang instrumentation pass inserts calls to functions defined in mm/kmsan/nstrumentation.c into the kernel code.

Shadow manipulation #

For every memory access the compiler emits a call to a function that returns a pair of pointers to the shadow and origin addresses of the given memory:

typedef struct {
  void *shadow, *origin;
} shadow_origin_ptr_t

shadow_origin_ptr_t __msan_metadata_ptr_for_load_{1,2,4,8}(void *addr)
shadow_origin_ptr_t __msan_metadata_ptr_for_store_{1,2,4,8}(void *addr)
shadow_origin_ptr_t __msan_metadata_ptr_for_load_n(void *addr, uintptr_t size)
shadow_origin_ptr_t __msan_metadata_ptr_for_store_n(void *addr, uintptr_t size)

The function name depends on the memory access size.

The compiler makes sure that for every loaded value its shadow and origin values are read from memory. When a value is stored to memory, its shadow and origin are also stored using the metadata pointers.

Handling locals #

A special function is used to create a new origin value for a local variable and set the origin of that variable to that value:

void __msan_poison_alloca(void *addr, uintptr_t size, char *descr)

Access to per-task data #

At the beginning of every instrumented function KMSAN inserts a call to __msan_get_context_state():

kmsan_context_state *__msan_get_context_state(void)

kmsan_context_state is declared in include/linux/kmsan.h:

struct kmsan_context_state {
  char param_tls[KMSAN_PARAM_SIZE];
  char retval_tls[KMSAN_RETVAL_SIZE];
  char va_arg_tls[KMSAN_PARAM_SIZE];
  char va_arg_origin_tls[KMSAN_PARAM_SIZE];
  u64 va_arg_overflow_size_tls;
  char param_origin_tls[KMSAN_PARAM_SIZE];
  depot_stack_handle_t retval_origin_tls;
};

This structure is used by KMSAN to pass parameter shadows and origins between instrumented functions (unless the parameters are checked immediately by CONFIG_KMSAN_CHECK_PARAM_RETVAL).

Passing uninitialized values to functions #

Clang's MemorySanitizer instrumentation has an option, -fsanitize-memory-param-retval, which makes the compiler check function parameters passed by value, as well as function return values.

The option is controlled by CONFIG_KMSAN_CHECK_PARAM_RETVAL, which is enabled by default to let KMSAN report uninitialized values earlier. Please refer to the LKML discussion for more details.

Because of the way the checks are implemented in LLVM (they are only applied to parameters marked as noundef), not all parameters are guaranteed to be checked, so we cannot give up the metadata storage in kmsan_context_state.

String functions #

The compiler replaces calls to memcpy()/memmove()/memset() with the following functions. These functions are also called when data structures are initialized or copied, making sure shadow and origin values are copied alongside with the data:

void *__msan_memcpy(void *dst, void *src, uintptr_t n)
void *__msan_memmove(void *dst, void *src, uintptr_t n)
void *__msan_memset(void *dst, int c, uintptr_t n)

Error reporting #

For each use of a value the compiler emits a shadow check that calls __msan_warning() in the case that value is poisoned:

void __msan_warning(u32 origin)

__msan_warning() causes KMSAN runtime to print an error report.

Inline assembly instrumentation #

KMSAN instruments every inline assembly output with a call to:

void __msan_instrument_asm_store(void *addr, uintptr_t size)

, which unpoisons the memory region.

This approach may mask certain errors, but it also helps to avoid a lot of false positives in bitwise operations, atomics etc.

Sometimes the pointers passed into inline assembly do not point to valid memory. In such cases they are ignored at runtime.

Runtime library #

The code is located in mm/kmsan/.

Per-task KMSAN state #

Every task_struct has an associated KMSAN task state that holds the KMSAN context (see above) and a per-task counter disallowing KMSAN reports:

struct kmsan_context {
  ...
  unsigned int depth;
  struct kmsan_context_state cstate;
  ...
}

struct task_struct {
  ...
  struct kmsan_context kmsan;
  ...
}

KMSAN contexts #

When running in a kernel task context, KMSAN uses current->kmsan.cstate to hold the metadata for function parameters and return values.

But in the case the kernel is running in the interrupt, softirq or NMI context, where current is unavailable, KMSAN switches to per-cpu interrupt state:

DEFINE_PER_CPU(struct kmsan_ctx, kmsan_percpu_ctx);

Metadata allocation #

There are several places in the kernel for which the metadata is stored.

1. Each struct page instance contains two pointers to its shadow and origin pages:

struct page {
  ...
  struct page *shadow, *origin;
  ...
};

At boot-time, the kernel allocates shadow and origin pages for every available kernel page. This is done quite late, when the kernel address space is already fragmented, so normal data pages may arbitrarily interleave with the metadata pages.

This means that in general for two contiguous memory pages their shadow/origin pages may not be contiguous. Consequently, if a memory access crosses the boundary of a memory block, accesses to shadow/origin memory may potentially corrupt other pages or read incorrect values from them.

In practice, contiguous memory pages returned by the same alloc_pages() call will have contiguous metadata, whereas if these pages belong to two different allocations their metadata pages can be fragmented.

For the kernel data (.data, .bss etc.) and percpu memory regions there also are no guarantees on metadata contiguity.

In the case __msan_metadata_ptr_for_XXX_YYY() hits the border between two pages with non-contiguous metadata, it returns pointers to fake shadow/origin regions:

char dummy_load_page[PAGE_SIZE] __attribute__((aligned(PAGE_SIZE)));
char dummy_store_page[PAGE_SIZE] __attribute__((aligned(PAGE_SIZE)));

dummy_load_page is zero-initialized, so reads from it always yield zeroes. All stores to dummy_store_page are ignored.

2. For vmalloc memory and modules, there is a direct mapping between the memory range, its shadow and origin. KMSAN reduces the vmalloc area by 3/4, making only the first quarter available to vmalloc(). The second quarter of the vmalloc area contains shadow memory for the first quarter, the third one holds the origins. A small part of the fourth quarter contains shadow and origins for the kernel modules. Please refer to arch/x86/include/asm/pgtable_64_types.h for more details.

When an array of pages is mapped into a contiguous virtual memory space, their shadow and origin pages are similarly mapped into contiguous regions.

References #

E. Stepanov, K. Serebryany. MemorySanitizer: fast detector of uninitialized memory use in C++. In Proceedings of CGO 2015.

Linux Kernel Selftests

Peios Kernel / Kernel development / Development tools

Peios: Linux capability names in this interface retain their API meaning, but KACS evaluates them through native token privileges or compatibility rules. UID 0, setcap and Unix mode bits do not independently grant native authority. Object access and PIP checks remain additional constraints where applicable. See Peios kernel behaviour for the mapping and exceptions.

The kernel contains a set of "self tests" under the tools/testing/selftests/ directory. These are intended to be small tests to exercise individual code paths in the kernel. Tests are intended to be run after building, installing and booting a kernel.

Kselftest from mainline can be run on older stable kernels. Running tests from mainline offers the best coverage. Several test rings run mainline kselftest suite on stable releases. The reason is that when a new test gets added to test existing code to regression test a bug, we should be able to run that test on an older kernel. Hence, it is important to keep code that can still test an older kernel and make sure it skips the test gracefully on newer releases.

You can find additional information on Kselftest framework, how to write new tests using the framework on Kselftest wiki:

https://kselftest.wiki.kernel.org/

On some systems, hot-plug tests could hang forever waiting for cpu and memory to be ready to be offlined. A special hot-plug target is created to run the full range of hot-plug tests. In default mode, hot-plug tests run in safe mode with a limited scope. In limited mode, cpu-hotplug test is run on a single cpu as opposed to all hotplug capable cpus, and memory hotplug test is run on 2% of hotplug capable memory instead of 10%.

kselftest runs as a userspace process. Tests that can be written/run in userspace may wish to use the Test Harness. Tests that need to be run in kernel space may wish to use a Test Module.

Documentation on the tests #

For documentation on the kselftests themselves, see:

  • Device testing with kselftest

Running the selftests (hotplug tests are run in limited mode) #

To build the tests:

$ make headers
$ make -C tools/testing/selftests

To run the tests:

$ make -C tools/testing/selftests run_tests

To build and run the tests with a single command, use:

$ make kselftest

Note that some tests will require root privileges.

Kselftest supports saving output files in a separate directory and then running tests. To locate output files in a separate directory two syntaxes are supported. In both cases the working directory must be the root of the kernel src. This is applicable to "Running a subset of selftests" section below.

To build, save output files in a separate directory with O=

$ make O=/tmp/kselftest kselftest

To build, save output files in a separate directory with KBUILD_OUTPUT

$ export KBUILD_OUTPUT=/tmp/kselftest; make kselftest

The O= assignment takes precedence over the KBUILD_OUTPUT environment variable.

The above commands by default run the tests and print full pass/fail report. Kselftest supports "summary" option to make it easier to understand the test results. Please find the detailed individual test results for each test in /tmp/testname file(s) when summary option is specified. This is applicable to "Running a subset of selftests" section below.

To run kselftest with summary option enabled

$ make summary=1 kselftest

Running a subset of selftests #

You can use the "TARGETS" variable on the make command line to specify single test to run, or a list of tests to run.

To run only tests targeted for a single subsystem:

$ make -C tools/testing/selftests TARGETS=ptrace run_tests

You can specify multiple tests to build and run:

$  make TARGETS="size timers" kselftest

To build, save output files in a separate directory with O=

$ make O=/tmp/kselftest TARGETS="size timers" kselftest

To build, save output files in a separate directory with KBUILD_OUTPUT

$ export KBUILD_OUTPUT=/tmp/kselftest; make TARGETS="size timers" kselftest

Additionally you can use the "SKIP_TARGETS" variable on the make command line to specify one or more targets to exclude from the TARGETS list.

To run all tests but a single subsystem:

$ make -C tools/testing/selftests SKIP_TARGETS=ptrace run_tests

You can specify multiple tests to skip:

$  make SKIP_TARGETS="size timers" kselftest

You can also specify a restricted list of tests to run together with a dedicated skiplist:

$  make TARGETS="breakpoints size timers" SKIP_TARGETS=size kselftest

See the top-level tools/testing/selftests/Makefile for the list of all possible targets.

Running the full range hotplug selftests #

To build the hotplug tests:

$ make -C tools/testing/selftests hotplug

To run the hotplug tests:

$ make -C tools/testing/selftests run_hotplug

Note that some tests will require root privileges.

Install selftests #

You can use the "install" target of "make" (which calls the kselftest_install.sh tool) to install selftests in the default location (tools/testing/selftests/kselftest_install), or in a user specified location via the INSTALL_PATH "make" variable.

To install selftests in default location:

$ make -C tools/testing/selftests install

To install selftests in a user specified location:

$ make -C tools/testing/selftests install INSTALL_PATH=/some/other/path

Running installed selftests #

Found in the install directory, as well as in the Kselftest tarball, is a script named run_kselftest.sh to run the tests.

You can simply do the following to run the installed Kselftests. Please note some tests will require root privileges:

$ cd kselftest_install
$ ./run_kselftest.sh

To see the list of available tests, the -l option can be used:

$ ./run_kselftest.sh -l

The -c option can be used to run all the tests from a test collection, or the -t option for specific single tests. Either can be used multiple times:

$ ./run_kselftest.sh -c size -c seccomp -t timers:posix_timers -t timer:nanosleep

For other features see the script usage output, seen with the -h option.

Timeout for selftests #

Selftests are designed to be quick and so a default timeout is used of 45 seconds for each test. Tests can override the default timeout by adding a settings file in their directory and set a timeout variable there to the configured a desired upper timeout for the test. Only a few tests override the timeout with a value higher than 45 seconds, selftests strives to keep it that way. Timeouts in selftests are not considered fatal because the system under which a test runs may change and this can also modify the expected time it takes to run a test. If you have control over the systems which will run the tests you can configure a test runner on those systems to use a greater or lower timeout on the command line as with the -o or the --override-timeout argument. For example to use 165 seconds instead one would use:

$ ./run_kselftest.sh --override-timeout 165

You can look at the TAP output to see if you ran into the timeout. Test runners which know a test must run under a specific time can then optionally treat these timeouts then as fatal.

Packaging selftests #

In some cases packaging is desired, such as when tests need to run on a different system. To package selftests, run:

$ make -C tools/testing/selftests gen_tar

This generates a tarball in the INSTALL_PATH/kselftest-packages directory. By default, .gz format is used. The tar compression format can be overridden by specifying a FORMAT make variable. Any value recognized by tar's auto-compress option is supported, such as:

$ make -C tools/testing/selftests gen_tar FORMAT=.xz

make gen_tar invokes make install so you can use it to package a subset of tests by using variables specified in Running a subset of selftests section:

$ make -C tools/testing/selftests gen_tar TARGETS="size" FORMAT=.xz

Contributing new tests #

In general, the rules for selftests are

  • Do as much as you can if you're not root;

  • Don't take too long;

  • Don't break the build on any architecture, and

  • Don't cause the top-level "make run_tests" to fail if your feature is unconfigured.

  • The output of tests must conform to the TAP standard to ensure high testing quality and to capture failures/errors with specific details. The kselftest.h and kselftest_harness.h headers provide wrappers for outputting test results. These wrappers should be used for pass, fail, exit, and skip messages. CI systems can easily parse TAP output messages to detect test results.

Contributing new tests (details) #

  • In your Makefile, use facilities from lib.mk by including it instead of reinventing the wheel. Specify flags and binaries generation flags on need basis before including lib.mk.

    CFLAGS = $(KHDR_INCLUDES)
    TEST_GEN_PROGS := close_range_test
    include ../lib.mk
    
  • Use TEST_GEN_XXX if such binaries or files are generated during compiling.

    TEST_PROGS, TEST_GEN_PROGS mean it is the executable tested by default.

    TEST_GEN_MODS_DIR should be used by tests that require modules to be built before the test starts. The variable will contain the name of the directory containing the modules.

    TEST_CUSTOM_PROGS should be used by tests that require custom build rules and prevent common build rule use.

    TEST_PROGS are for test shell scripts. Please ensure shell script has its exec bit set. Otherwise, lib.mk run_tests will generate a warning.

    TEST_CUSTOM_PROGS and TEST_PROGS will be run by common run_tests.

    TEST_PROGS_EXTENDED, TEST_GEN_PROGS_EXTENDED mean it is the executable which is not tested by default.

    TEST_FILES, TEST_GEN_FILES mean it is the file which is used by test.

    TEST_INCLUDES is similar to TEST_FILES, it lists files which should be included when exporting or installing the tests, with the following differences:

    • symlinks to files in other directories are preserved

    • the part of paths below tools/testing/selftests/ is preserved when copying the files to the output directory

    TEST_INCLUDES is meant to list dependencies located in other directories of the selftests hierarchy.

  • First use the headers inside the kernel source and/or git repo, and then the system headers. Headers for the kernel release as opposed to headers installed by the distro on the system should be the primary focus to be able to find regressions. Use KHDR_INCLUDES in Makefile to include headers from the kernel source.

  • If a test needs specific kernel config options enabled, add a config file in the test directory to enable them.

    e.g: tools/testing/selftests/android/config

  • Create a .gitignore file inside test directory and add all generated objects in it.

  • Add new test name in TARGETS in selftests/Makefile:

    TARGETS += android
    
  • All changes should pass:

    kselftest-{all,install,clean,gen_tar}
    kselftest-{all,install,clean,gen_tar} O=abo_path
    kselftest-{all,install,clean,gen_tar} O=rel_path
    make -C tools/testing/selftests {all,install,clean,gen_tar}
    make -C tools/testing/selftests {all,install,clean,gen_tar} O=abs_path
    make -C tools/testing/selftests {all,install,clean,gen_tar} O=rel_path
    

Test Module #

Kselftest tests the kernel from userspace. Sometimes things need testing from within the kernel, one method of doing this is to create a test module. We can tie the module into the kselftest framework by using a shell script test runner. kselftest/module.sh is designed to facilitate this process. There is also a header file provided to assist writing kernel modules that are for use with kselftest:

  • tools/testing/selftests/kselftest_module.h

  • tools/testing/selftests/kselftest/module.sh

Note that test modules should taint the kernel with TAINT_TEST. This will happen automatically for modules which are in the tools/testing/ directory, or for modules which use the kselftest_module.h header above. Otherwise, you'll need to add MODULE_INFO(test, "Y") to your module source. selftests which do not load modules typically should not taint the kernel, but in cases where a non-test module is loaded, TEST_TAINT can be applied from userspace by writing to /proc/sys/kernel/tainted.

How to use #

Here we show the typical steps to create a test module and tie it into kselftest. We use kselftests for lib/ as an example.

  1. Create the test module

  2. Create the test script that will run (load/unload) the module e.g. tools/testing/selftests/lib/bitmap.sh

  3. Add line to config file e.g. tools/testing/selftests/lib/config

  4. Add test script to makefile e.g. tools/testing/selftests/lib/Makefile

  5. Verify it works:

# Assumes you have booted a fresh build of this kernel tree
cd /path/to/linux/tree
make kselftest-merge
make modules
sudo make modules_install
make TARGETS=lib kselftest

Example Module #

A bare bones test module might look like this:

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

#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt

#include "../tools/testing/selftests/kselftest_module.h"

KSTM_MODULE_GLOBALS();

/*
 * Kernel module for testing the foobinator
 */

static int __init test_function()
{
        ...
}

static void __init selftest(void)
{
        KSTM_CHECK_ZERO(do_test_case("", 0));
}

KSTM_MODULE_LOADERS(test_foo);
MODULE_AUTHOR("John Developer <jd@fooman.org>");
MODULE_LICENSE("GPL");
MODULE_INFO(test, "Y");

Example test script #

#!/bin/bash
# SPDX-License-Identifier: GPL-2.0+
$(dirname $0)/../kselftest/module.sh "foo" test_foo

Test Harness #

The kselftest_harness.h file contains useful helpers to build tests. The test harness is for userspace testing, for kernel space testing see Test Module above.

The tests from tools/testing/selftests/seccomp/seccomp_bpf.c can be used as example.

Example #

#include "kselftest_harness.h"

TEST(standalone_test) {
  do_some_stuff;
  EXPECT_GT(10, stuff) {
     stuff_state_t state;
     enumerate_stuff_state(&state);
     TH_LOG("expectation failed with state: %s", state.msg);
  }
  more_stuff;
  ASSERT_NE(some_stuff, NULL) TH_LOG("how did it happen?!");
  last_stuff;
  EXPECT_EQ(0, last_stuff);
}

FIXTURE(my_fixture) {
  mytype_t *data;
  int awesomeness_level;
};
FIXTURE_SETUP(my_fixture) {
  self->data = mytype_new();
  ASSERT_NE(NULL, self->data);
}
FIXTURE_TEARDOWN(my_fixture) {
  mytype_free(self->data);
}
TEST_F(my_fixture, data_is_good) {
  EXPECT_EQ(1, is_my_data_good(self->data));
}

TEST_HARNESS_MAIN

Helpers #

TH_LOG() #

TH_LOG(fmt, ...)

Parameters

  • fmt: format string
  • ...: optional arguments

Description

TH_LOG(format, ...)

Optional debug logging function available for use in tests. Logging may be enabled or disabled by defining TH_LOG_ENABLED. E.g., #define TH_LOG_ENABLED 1

If no definition is provided, logging is enabled by default.

TEST() #

TEST(test_name)

Defines the test function and creates the registration stub

Parameters

  • test_name: test name

Description

TEST(name) { implementation }

Defines a test by name. Names must be unique and tests must not be run in parallel. The implementation containing block is a function and scoping should be treated as such. Returning early may be performed with a bare "return;" statement.

EXPECT_* and ASSERT_* are valid in a TEST() { } context.

TEST_SIGNAL() #

TEST_SIGNAL(test_name, signal)

Parameters

  • test_name: test name
  • signal: signal number

Description

TEST_SIGNAL(name, signal) { implementation }

Defines a test by name and the expected term signal. Names must be unique and tests must not be run in parallel. The implementation containing block is a function and scoping should be treated as such. Returning early may be performed with a bare "return;" statement.

EXPECT_* and ASSERT_* are valid in a TEST() { } context.

FIXTURE_DATA() #

FIXTURE_DATA(datatype_name)

Wraps the struct name so we have one less argument to pass around

Parameters

  • datatype_name: datatype name

Description

FIXTURE_DATA(datatype_name)

Almost always, you want just FIXTURE() instead (see below). This call may be used when the type of the fixture data is needed. In general, this should not be needed unless the self is being passed to a helper directly.

FIXTURE() #

FIXTURE(fixture_name)

Called once per fixture to setup the data and register

Parameters

  • fixture_name: fixture name

Description

FIXTURE(fixture_name) {
  type property1;
  ...
};

Defines the data provided to TEST_F()-defined tests as self. It should be populated and cleaned up using FIXTURE_SETUP() and FIXTURE_TEARDOWN().

FIXTURE_SETUP() #

FIXTURE_SETUP(fixture_name)

Prepares the setup function for the fixture. _metadata is included so that EXPECT_, ASSERT_ etc. work correctly.

Parameters

  • fixture_name: fixture name

Description

FIXTURE_SETUP(fixture_name) { implementation }

Populates the required "setup" function for a fixture. An instance of the datatype defined with FIXTURE_DATA() will be exposed as self for the implementation.

ASSERT_* are valid for use in this context and will prempt the execution of any dependent fixture tests.

A bare "return;" statement may be used to return early.

FIXTURE_TEARDOWN() #

FIXTURE_TEARDOWN(fixture_name)

Parameters

  • fixture_name: fixture name

Description

_metadata is included so that EXPECT_, ASSERT_ etc. work correctly.

FIXTURE_TEARDOWN(fixture_name) { implementation }

Populates the required "teardown" function for a fixture. An instance of the datatype defined with FIXTURE_DATA() will be exposed as self for the implementation to clean up.

A bare "return;" statement may be used to return early.

FIXTURE_VARIANT() #

FIXTURE_VARIANT(fixture_name)

Optionally called once per fixture to declare fixture variant

Parameters

  • fixture_name: fixture name

Description

FIXTURE_VARIANT(fixture_name) {
  type property1;
  ...
};

Defines type of constant parameters provided to FIXTURE_SETUP(), TEST_F() and FIXTURE_TEARDOWN as variant. Variants allow the same tests to be run with different arguments.

FIXTURE_VARIANT_ADD() #

FIXTURE_VARIANT_ADD(fixture_name, variant_name)

Called once per fixture variant to setup and register the data

Parameters

  • fixture_name: fixture name
  • variant_name: name of the parameter set

Description

FIXTURE_VARIANT_ADD(fixture_name, variant_name) {
  .property1 = val1,
  ...
};

Defines a variant of the test fixture, provided to FIXTURE_SETUP() and TEST_F() as variant. Tests of each fixture will be run once for each variant.

TEST_F() #

TEST_F(fixture_name, test_name)

Emits test registration and helpers for fixture-based test cases

Parameters

  • fixture_name: fixture name
  • test_name: test name

Description

TEST_F(fixture, name) { implementation }

Defines a test that depends on a fixture (e.g., is part of a test case). Very similar to TEST() except that self is the setup instance of fixture's datatype exposed for use by the implementation.

The metadata object is shared (MAP_SHARED) with all the potential forked processes, which enables them to use EXCEPT() and ASSERT_().

The self object is only shared with the potential forked processes if FIXTURE_TEARDOWN_PARENT() is used instead of FIXTURE_TEARDOWN().

TEST_HARNESS_MAIN #

TEST_HARNESS_MAIN

Simple wrapper to run the test harness

Description

TEST_HARNESS_MAIN

Use once to append a main() to the test file.

Operators #

Operators for use in TEST() and TEST_F(). ASSERT_* calls will stop test execution immediately. EXPECT_* calls will emit a failure warning, note it, and continue.

ASSERT_EQ() #

ASSERT_EQ(expected, seen)

Parameters

  • expected: expected value
  • seen: measured value

Description

ASSERT_EQ(expected, measured): expected == measured

ASSERT_NE() #

ASSERT_NE(expected, seen)

Parameters

  • expected: expected value
  • seen: measured value

Description

ASSERT_NE(expected, measured): expected != measured

ASSERT_LT() #

ASSERT_LT(expected, seen)

Parameters

  • expected: expected value
  • seen: measured value

Description

ASSERT_LT(expected, measured): expected < measured

ASSERT_LE() #

ASSERT_LE(expected, seen)

Parameters

  • expected: expected value
  • seen: measured value

Description

ASSERT_LE(expected, measured): expected <= measured

ASSERT_GT() #

ASSERT_GT(expected, seen)

Parameters

  • expected: expected value
  • seen: measured value

Description

ASSERT_GT(expected, measured): expected > measured

ASSERT_GE() #

ASSERT_GE(expected, seen)

Parameters

  • expected: expected value
  • seen: measured value

Description

ASSERT_GE(expected, measured): expected >= measured

ASSERT_NULL() #

ASSERT_NULL(seen)

Parameters

  • seen: measured value

Description

ASSERT_NULL(measured): NULL == measured

ASSERT_TRUE() #

ASSERT_TRUE(seen)

Parameters

  • seen: measured value

Description

ASSERT_TRUE(measured): measured != 0

ASSERT_FALSE() #

ASSERT_FALSE(seen)

Parameters

  • seen: measured value

Description

ASSERT_FALSE(measured): measured == 0

ASSERT_STREQ() #

ASSERT_STREQ(expected, seen)

Parameters

  • expected: expected value
  • seen: measured value

Description

ASSERT_STREQ(expected, measured): !strcmp(expected, measured)

ASSERT_STRNE() #

ASSERT_STRNE(expected, seen)

Parameters

  • expected: expected value
  • seen: measured value

Description

ASSERT_STRNE(expected, measured): strcmp(expected, measured)

EXPECT_EQ() #

EXPECT_EQ(expected, seen)

Parameters

  • expected: expected value
  • seen: measured value

Description

EXPECT_EQ(expected, measured): expected == measured

EXPECT_NE() #

EXPECT_NE(expected, seen)

Parameters

  • expected: expected value
  • seen: measured value

Description

EXPECT_NE(expected, measured): expected != measured

EXPECT_LT() #

EXPECT_LT(expected, seen)

Parameters

  • expected: expected value
  • seen: measured value

Description

EXPECT_LT(expected, measured): expected < measured

EXPECT_LE() #

EXPECT_LE(expected, seen)

Parameters

  • expected: expected value
  • seen: measured value

Description

EXPECT_LE(expected, measured): expected <= measured

EXPECT_GT() #

EXPECT_GT(expected, seen)

Parameters

  • expected: expected value
  • seen: measured value

Description

EXPECT_GT(expected, measured): expected > measured

EXPECT_GE() #

EXPECT_GE(expected, seen)

Parameters

  • expected: expected value
  • seen: measured value

Description

EXPECT_GE(expected, measured): expected >= measured

EXPECT_NULL() #

EXPECT_NULL(seen)

Parameters

  • seen: measured value

Description

EXPECT_NULL(measured): NULL == measured

EXPECT_TRUE() #

EXPECT_TRUE(seen)

Parameters

  • seen: measured value

Description

EXPECT_TRUE(measured): 0 != measured

EXPECT_FALSE() #

EXPECT_FALSE(seen)

Parameters

  • seen: measured value

Description

EXPECT_FALSE(measured): 0 == measured

EXPECT_STREQ() #

EXPECT_STREQ(expected, seen)

Parameters

  • expected: expected value
  • seen: measured value

Description

EXPECT_STREQ(expected, measured): !strcmp(expected, measured)

EXPECT_STRNE() #

EXPECT_STRNE(expected, seen)

Parameters

  • expected: expected value
  • seen: measured value

Description

EXPECT_STRNE(expected, measured): strcmp(expected, measured)

The Kernel Test Anything Protocol (KTAP), version 1

Peios Kernel / Kernel development / Development tools

TAP, or the Test Anything Protocol is a format for specifying test results used by a number of projects. Its website and specification are found at this link. The Linux Kernel largely uses TAP output for test results. However, Kernel testing frameworks have special needs for test results which don't align with the original TAP specification. Thus, a "Kernel TAP" (KTAP) format is specified to extend and alter TAP to support these use-cases. This specification describes the generally accepted format of KTAP as it is currently used in the kernel.

KTAP test results describe a series of tests (which may be nested: i.e., test can have subtests), each of which can contain both diagnostic data -- e.g., log lines -- and a final result. The test structure and results are machine-readable, whereas the diagnostic data is unstructured and is there to aid human debugging.

KTAP output is built from four different types of lines:

  • Version lines

  • Plan lines

  • Test case result lines

  • Diagnostic lines

In general, valid KTAP output should also form valid TAP output, but some information, in particular nested test results, may be lost. Also note that there is a stagnant draft specification for TAP14, KTAP diverges from this in a couple of places (notably the "Subtest" header), which are described where relevant later in this document.

Version lines #

All KTAP-formatted results begin with a "version line" which specifies which version of the (K)TAP standard the result is compliant with.

For example:

  • "KTAP version 1"

  • "TAP version 13"

  • "TAP version 14"

Note that, in KTAP, subtests also begin with a version line, which denotes the start of the nested test results. This differs from TAP14, which uses a separate "Subtest" line.

While, going forward, "KTAP version 1" should be used by compliant tests, it is expected that most parsers and other tooling will accept the other versions listed here for compatibility with existing tests and frameworks.

Plan lines #

A test plan provides the number of tests (or subtests) in the KTAP output.

Plan lines must follow the format of "1..N" where N is the number of tests or subtests. Plan lines follow version lines to indicate the number of nested tests.

While there are cases where the number of tests is not known in advance -- in which case the test plan may be omitted -- it is strongly recommended one is present where possible.

Test case result lines #

Test case result lines indicate the final status of a test. They are required and must have the format:

<result> <number> [<description>][ # [<directive>] [<diagnostic data>]]

The result can be either "ok", which indicates the test case passed, or "not ok", which indicates that the test case failed.

<number> represents the number of the test being performed. The first test must have the number 1 and the number then must increase by 1 for each additional subtest within the same test at the same nesting level.

The description is a description of the test, generally the name of the test, and can be any string of characters other than # or a newline. The description is optional, but recommended.

The directive and any diagnostic data is optional. If either are present, they must follow a hash sign, "#".

A directive is a keyword that indicates a different outcome for a test other than passed and failed. The directive is optional, and consists of a single keyword preceding the diagnostic data. In the event that a parser encounters a directive it doesn't support, it should fall back to the "ok" / "not ok" result.

Currently accepted directives are:

  • "SKIP", which indicates a test was skipped (note the result of the test case result line can be either "ok" or "not ok" if the SKIP directive is used)

  • "TODO", which indicates that a test is not expected to pass at the moment, e.g. because the feature it is testing is known to be broken. While this directive is inherited from TAP, its use in the kernel is discouraged.

  • "XFAIL", which indicates that a test is expected to fail. This is similar to "TODO", above, and is used by some kselftest tests.

  • “TIMEOUT”, which indicates a test has timed out (note the result of the test case result line should be “not ok” if the TIMEOUT directive is used)

  • “ERROR”, which indicates that the execution of a test has failed due to a specific error that is included in the diagnostic data. (note the result of the test case result line should be “not ok” if the ERROR directive is used)

The diagnostic data is a plain-text field which contains any additional details about why this result was produced. This is typically an error message for ERROR or failed tests, or a description of missing dependencies for a SKIP result.

The diagnostic data field is optional, and results which have neither a directive nor any diagnostic data do not need to include the "#" field separator.

Example result lines include:

ok 1 test_case_name

The test "test_case_name" passed.

not ok 1 test_case_name

The test "test_case_name" failed.

ok 1 test # SKIP necessary dependency unavailable

The test "test" was SKIPPED with the diagnostic message "necessary dependency unavailable".

not ok 1 test # TIMEOUT 30 seconds

The test "test" timed out, with diagnostic data "30 seconds".

ok 5 check return code # rcode=0

The test "check return code" passed, with additional diagnostic data “rcode=0”

Diagnostic lines #

If tests wish to output any further information, they should do so using "diagnostic lines". Diagnostic lines are optional, freeform text, and are often used to describe what is being tested and any intermediate results in more detail than the final result and diagnostic data line provides.

Diagnostic lines are formatted as "# <diagnostic_description>", where the description can be any string. Diagnostic lines can be anywhere in the test output. As a rule, diagnostic lines regarding a test are directly before the test result line for that test.

Note that most tools will treat unknown lines (see below) as diagnostic lines, even if they do not start with a "#": this is to capture any other useful kernel output which may help debug the test. It is nevertheless recommended that tests always prefix any diagnostic output they have with a "#" character.

Unknown lines #

There may be lines within KTAP output that do not follow the format of one of the four formats for lines described above. This is allowed, however, they will not influence the status of the tests.

This is an important difference from TAP. Kernel tests may print messages to the system console or a log file. Both of these destinations may contain messages either from unrelated kernel or userspace activity, or kernel messages from non-test code that is invoked by the test. The kernel code invoked by the test likely is not aware that a test is in progress and thus can not print the message as a diagnostic message.

Nested tests #

In KTAP, tests can be nested. This is done by having a test include within its output an entire set of KTAP-formatted results. This can be used to categorize and group related tests, or to split out different results from the same test.

The "parent" test's result should consist of all of its subtests' results, starting with another KTAP version line and test plan, and end with the overall result. If one of the subtests fail, for example, the parent test should also fail.

Additionally, all lines in a subtest should be indented. One level of indentation is two spaces: " ". The indentation should begin at the version line and should end before the parent test's result line.

"Unknown lines" are not considered to be lines in a subtest and thus are allowed to be either indented or not indented.

An example of a test with two nested subtests:

KTAP version 1
1..1
  KTAP version 1
  1..2
  ok 1 test_1
  not ok 2 test_2
# example failed
not ok 1 example

An example format with multiple levels of nested testing:

KTAP version 1
1..2
  KTAP version 1
  1..2
    KTAP version 1
    1..2
    not ok 1 test_1
    ok 2 test_2
  not ok 1 test_3
  ok 2 test_4 # SKIP
not ok 1 example_test_1
ok 2 example_test_2

Major differences between TAP and KTAP #

Feature

TAP

KTAP

yaml and json in diagnosic message

ok

not recommended

TODO directive

ok

not recognized

allows an arbitrary number of tests to be nested

no

yes

"Unknown lines" are in category of "Anything else"

yes

no

"Unknown lines" are

incorrect

allowed

The TAP14 specification does permit nested tests, but instead of using another nested version line, uses a line of the form "Subtest: <name>" where <name> is the name of the parent test.

Example KTAP output #

KTAP version 1
1..1
  KTAP version 1
  1..3
    KTAP version 1
    1..1
    # test_1: initializing test_1
    ok 1 test_1
  ok 1 example_test_1
    KTAP version 1
    1..2
    ok 1 test_1 # SKIP test_1 skipped
    ok 2 test_2
  ok 2 example_test_2
    KTAP version 1
    1..3
    ok 1 test_1
    # test_2: FAIL
    not ok 2 test_2
    ok 3 test_3 # SKIP test_3 skipped
  not ok 3 example_test_3
not ok 1 main_test

This output defines the following hierarchy:

A single test called "main_test", which fails, and has three subtests:

  • "example_test_1", which passes, and has one subtest:

    • "test_1", which passes, and outputs the diagnostic message "test_1: initializing test_1"
  • "example_test_2", which passes, and has two subtests:

    • "test_1", which is skipped, with the explanation "test_1 skipped"

    • "test_2", which passes

  • "example_test_3", which fails, and has three subtests

    • "test_1", which passes

    • "test_2", which outputs the diagnostic line "test_2: FAIL", and fails.

    • "test_3", which is skipped with the explanation "test_3 skipped"

Note that the individual subtests with the same names do not conflict, as they are found in different parent tests. This output also exhibits some sensible rules for "bubbling up" test results: a test fails if any of its subtests fail. Skipped tests do not affect the result of the parent test (though it often makes sense for a test to be marked skipped if _all_ of its subtests have been skipped).

See also: #

  • The TAP specification: https://testanything.org/tap-version-13-specification.html

  • The (stagnant) TAP version 14 specification: https://github.com/TestAnything/Specification/blob/tap-14-specification/specification.md

  • The kselftest documentation: Documentation/dev-tools/kselftest.rst

  • The KUnit documentation: Documentation/dev-tools/kunit/index.rst

Using Propeller with the Linux kernel

Peios Kernel / Kernel development / Development tools

This enables Propeller build support for the kernel when using Clang compiler. Propeller is a profile-guided optimization (PGO) method used to optimize binary executables. Like AutoFDO, it utilizes hardware sampling to gather information about the frequency of execution of different code paths within a binary. Unlike AutoFDO, this information is then used right before linking phase to optimize (among others) block layout within and across functions.

A few important notes about adopting Propeller optimization:

  1. Although it can be used as a standalone optimization step, it is strongly recommended to apply Propeller on top of AutoFDO, AutoFDO+ThinLTO or Instrument FDO. The rest of this document assumes this paradigm.

  2. Propeller uses another round of profiling on top of AutoFDO/AutoFDO+ThinLTO/iFDO. The whole build process involves "build-afdo - train-afdo - build-propeller - train-propeller - build-optimized".

  3. Propeller requires LLVM 19 release or later for Clang/Clang++ and the linker(ld.lld).

  4. In addition to LLVM toolchain, Propeller requires a profiling conversion tool: https://github.com/google/autofdo with a release after v0.30.1: https://github.com/google/autofdo/releases/tag/v0.30.1.

The Propeller optimization process involves the following steps:

  1. Initial building: Build the AutoFDO or AutoFDO+ThinLTO binary as you would normally do, but with a set of compile-time / link-time flags, so that a special metadata section is created within the kernel binary. The special section is only intend to be used by the profiling tool, it is not part of the runtime image, nor does it change kernel run time text sections.

  2. Profiling: The above kernel is then run with a representative workload to gather execution frequency data. This data is collected using hardware sampling, via perf. Propeller is most effective on platforms supporting advanced PMU features like LBR on Intel machines. This step is the same as profiling the kernel for AutoFDO (the exact perf parameters can be different).

  3. Propeller profile generation: Perf output file is converted to a pair of Propeller profiles via an offline tool.

  4. Optimized build: Build the AutoFDO or AutoFDO+ThinLTO optimized binary as you would normally do, but with a compile-time / link-time flag to pick up the Propeller compile time and link time profiles. This build step uses 3 profiles - the AutoFDO profile, the Propeller compile-time profile and the Propeller link-time profile.

  5. Deployment: The optimized kernel binary is deployed and used in production environments, providing improved performance and reduced latency.

Preparation #

Configure the kernel with:

CONFIG_AUTOFDO_CLANG=y
CONFIG_PROPELLER_CLANG=y

Customization #

The default CONFIG_PROPELLER_CLANG setting covers kernel space objects for Propeller builds. One can, however, enable or disable Propeller build for individual files and directories by adding a line similar to the following to the respective kernel Makefile:

  • For enabling a single file (e.g. foo.o):

    PROPELLER_PROFILE_foo.o := y
    
  • For enabling all files in one directory:

    PROPELLER_PROFILE := y
    
  • For disabling one file:

    PROPELLER_PROFILE_foo.o := n
    
  • For disabling all files in one directory:

    PROPELLER__PROFILE := n
    

Workflow #

Here is an example workflow for building an AutoFDO+Propeller kernel:

  1. Assuming an AutoFDO profile is already collected following instructions in the AutoFDO document, build the kernel on the host machine, with AutoFDO and Propeller build configs

    CONFIG_AUTOFDO_CLANG=y
    CONFIG_PROPELLER_CLANG=y
    

    and

    $ make LLVM=1 CLANG_AUTOFDO_PROFILE=<autofdo-profile-name>
    
  2. Install the kernel on the test machine.

  3. Run the load tests. The '-c' option in perf specifies the sample event period. We suggest using a suitable prime number, like 500009, for this purpose.

    • For Intel platforms:

      $ perf record -e BR_INST_RETIRED.NEAR_TAKEN:k -a -N -b -c <count> -o <perf_file> -- <loadtest>
      
    • For AMD platforms:

      $ perf record --pfm-event RETIRED_TAKEN_BRANCH_INSTRUCTIONS:k -a -N -b -c <count> -o <perf_file> -- <loadtest>
      

    Note you can repeat the above steps to collect multiple <perf_file>s.

  4. (Optional) Download the raw perf file(s) to the host machine.

  5. Use the create_llvm_prof tool (https://github.com/google/autofdo) to generate Propeller profile.

    $ create_llvm_prof --binary=<vmlinux> --profile=<perf_file>
                       --format=propeller --propeller_output_module_name
                       --out=<propeller_profile_prefix>_cc_profile.txt
                       --propeller_symorder=<propeller_profile_prefix>_ld_profile.txt
    

    "<propeller_profile_prefix>" can be something like "/home/user/dir/any_string".

    This command generates a pair of Propeller profiles: "<propeller_profile_prefix>_cc_profile.txt" and "<propeller_profile_prefix>_ld_profile.txt".

    If there are more than 1 perf_file collected in the previous step, you can create a temp list file "<perf_file_list>" with each line containing one perf file name and run:

    $ create_llvm_prof --binary=<vmlinux> --profile=@<perf_file_list>
                       --format=propeller --propeller_output_module_name
                       --out=<propeller_profile_prefix>_cc_profile.txt
                       --propeller_symorder=<propeller_profile_prefix>_ld_profile.txt
    
  6. Rebuild the kernel using the AutoFDO and Propeller profiles.

    CONFIG_AUTOFDO_CLANG=y
    CONFIG_PROPELLER_CLANG=y
    

    and

    $ make LLVM=1 CLANG_AUTOFDO_PROFILE=<profile_file> CLANG_PROPELLER_PROFILE_PREFIX=<propeller_profile_prefix>
    

Sparse

Peios Kernel / Kernel development / Development tools

Sparse is a semantic checker for C programs; it can be used to find a number of potential problems with kernel code. See https://lwn.net/Articles/689907/ for an overview of sparse; this document contains some kernel-specific sparse information. More information on sparse, mainly about its internals, can be found in its official pages at https://sparse.docs.kernel.org.

Using sparse for typechecking #

"__bitwise" is a type attribute, so you have to do something like this:

typedef int __bitwise pm_request_t;

enum pm_request {
        PM_SUSPEND = (__force pm_request_t) 1,
        PM_RESUME = (__force pm_request_t) 2
};

which makes PM_SUSPEND and PM_RESUME "bitwise" integers (the "__force" is there because sparse will complain about casting to/from a bitwise type, but in this case we really _do_ want to force the conversion). And because the enum values are all the same type, now "enum pm_request" will be that type too.

And with gcc, all the "__bitwise"/"__force stuff" goes away, and it all ends up looking just like integers to gcc.

Quite frankly, you don't need the enum there. The above all really just boils down to one special "int __bitwise" type.

So the simpler way is to just do:

typedef int __bitwise pm_request_t;

#define PM_SUSPEND ((__force pm_request_t) 1)
#define PM_RESUME ((__force pm_request_t) 2)

and you now have all the infrastructure needed for strict typechecking.

One small note: the constant integer "0" is special. You can use a constant zero as a bitwise integer type without sparse ever complaining. This is because "bitwise" (as the name implies) was designed for making sure that bitwise types don't get mixed up (little-endian vs big-endian vs cpu-endian vs whatever), and there the constant "0" really _is_ special.

Getting sparse #

You can get tarballs of the latest released versions from: https://www.kernel.org/pub/software/devel/sparse/dist/

Alternatively, you can get snapshots of the latest development version of sparse using git to clone:

git://git.kernel.org/pub/scm/devel/sparse/sparse.git

Once you have it, just do:

make
make install

as a regular user, and it will install sparse in your ~/bin directory.

Using sparse #

Do a kernel make with "make C=1" to run sparse on all the C files that get recompiled, or use "make C=2" to run sparse on the files whether they need to be recompiled or not. The latter is a fast way to check the whole tree if you have already built it.

The optional make variable CF can be used to pass arguments to sparse. The build system passes -Wbitwise to sparse automatically.

Note that sparse defines the __CHECKER__ preprocessor symbol.

Device testing with kselftest

Peios Kernel / Kernel development / Development tools

There are a few different kselftests available for testing devices generically, with some overlap in coverage and different requirements. This document aims to give an overview of each one.

Note: Paths in this document are relative to the kselftest folder (tools/testing/selftests).

Device oriented kselftests:

  • Devicetree (dt)

    • Coverage: Probe status for devices described in Devicetree

    • Requirements: None

  • Error logs (devices/error_logs)

    • Coverage: Error (or more critical) log messages presence coming from any device

    • Requirements: None

  • Discoverable bus (devices/probe)

    • Coverage: Presence and probe status of USB or PCI devices that have been described in the reference file

    • Requirements: Manually describe the devices that should be tested in a YAML reference file (see devices/probe/boards/google,spherion.yaml for an example)

  • Exist (devices/exist)

    • Coverage: Presence of all devices

    • Requirements: Generate the reference (see devices/exist/README.rst for details) on a known-good kernel

Therefore, the suggestion is to enable the error log and devicetree tests on all (DT-based) platforms, since they don't have any requirements. Then to greatly improve coverage, generate the reference for each platform and enable the exist test. The discoverable bus test can be used to verify the probe status of specific USB or PCI devices, but is probably not worth it for most cases.

Kernel Testing Guide

Peios Kernel / Kernel development / Development tools

There are a number of different tools for testing the Linux kernel, so knowing when to use each of them can be a challenge. This document provides a rough overview of their differences, and how they fit together.

Writing and Running Tests #

The bulk of kernel tests are written using either the kselftest or KUnit frameworks. These both provide infrastructure to help make running tests and groups of tests easier, as well as providing helpers to aid in writing new tests.

If you're looking to verify the behaviour of the Kernel — particularly specific parts of the kernel — then you'll want to use KUnit or kselftest.

The Difference Between KUnit and kselftest #

KUnit (Documentation/dev-tools/kunit/index.rst) is an entirely in-kernel system for "white box" testing: because test code is part of the kernel, it can access internal structures and functions which aren't exposed to userspace.

KUnit tests therefore are best written against small, self-contained parts of the kernel, which can be tested in isolation. This aligns well with the concept of 'unit' testing.

For example, a KUnit test might test an individual kernel function (or even a single codepath through a function, such as an error handling case), rather than a feature as a whole.

This also makes KUnit tests very fast to build and run, allowing them to be run frequently as part of the development process.

There is a KUnit test style guide which may give further pointers in Documentation/dev-tools/kunit/style.rst

kselftest (Documentation/dev-tools/kselftest.rst), on the other hand, is largely implemented in userspace, and tests are normal userspace scripts or programs.

This makes it easier to write more complicated tests, or tests which need to manipulate the overall system state more (e.g., spawning processes, etc.). However, it's not possible to call kernel functions directly from kselftest. This means that only kernel functionality which is exposed to userspace somehow (e.g. by a syscall, device, filesystem, etc.) can be tested with kselftest. To work around this, some tests include a companion kernel module which exposes more information or functionality. If a test runs mostly or entirely within the kernel, however, KUnit may be the more appropriate tool.

kselftest is therefore suited well to tests of whole features, as these will expose an interface to userspace, which can be tested, but not implementation details. This aligns well with 'system' or 'end-to-end' testing.

For example, all new system calls should be accompanied by kselftest tests.

Code Coverage Tools #

The Linux Kernel supports two different code coverage measurement tools. These can be used to verify that a test is executing particular functions or lines of code. This is useful for determining how much of the kernel is being tested, and for finding corner-cases which are not covered by the appropriate test.

Documentation/dev-tools/gcov.rst is GCC's coverage testing tool, which can be used with the kernel to get global or per-module coverage. Unlike KCOV, it does not record per-task coverage. Coverage data can be read from debugfs, and interpreted using the usual gcov tooling.

Documentation/dev-tools/kcov.rst is a feature which can be built in to the kernel to allow capturing coverage on a per-task level. It's therefore useful for fuzzing and other situations where information about code executed during, for example, a single syscall is useful.

Dynamic Analysis Tools #

The kernel also supports a number of dynamic analysis tools, which attempt to detect classes of issues when they occur in a running kernel. These typically each look for a different class of bugs, such as invalid memory accesses, concurrency issues such as data races, or other undefined behaviour like integer overflows.

Some of these tools are listed below:

  • kmemleak detects possible memory leaks. See Documentation/dev-tools/kmemleak.rst

  • KASAN detects invalid memory accesses such as out-of-bounds and use-after-free errors. See Documentation/dev-tools/kasan.rst

  • UBSAN detects behaviour that is undefined by the C standard, like integer overflows. See Documentation/dev-tools/ubsan.rst

  • KCSAN detects data races. See Documentation/dev-tools/kcsan.rst

  • KFENCE is a low-overhead detector of memory issues, which is much faster than KASAN and can be used in production. See Documentation/dev-tools/kfence.rst

  • lockdep is a locking correctness validator. See Documentation/locking/lockdep-design.rst

  • Runtime Verification (RV) supports checking specific behaviours for a given subsystem. See Documentation/trace/rv/runtime-verification.rst

  • There are several other pieces of debug instrumentation in the kernel, many of which can be found in lib/Kconfig.debug

These tools tend to test the kernel as a whole, and do not "pass" like kselftest or KUnit tests. They can be combined with KUnit or kselftest by running tests on a kernel with these tools enabled: you can then be sure that none of these errors are occurring during the test.

Some of these tools integrate with KUnit or kselftest and will automatically fail tests if an issue is detected.

Static Analysis Tools #

In addition to testing a running kernel, one can also analyze kernel source code directly (at compile time) using static analysis tools. The tools commonly used in the kernel allow one to inspect the whole source tree or just specific files within it. They make it easier to detect and fix problems during the development process.

Sparse can help test the kernel by performing type-checking, lock checking, value range checking, in addition to reporting various errors and warnings while examining the code. See the Documentation/dev-tools/sparse.rst documentation page for details on how to use it.

Smatch extends Sparse and provides additional checks for programming logic mistakes such as missing breaks in switch statements, unused return values on error checking, forgetting to set an error code in the return of an error path, etc. Smatch also has tests against more serious issues such as integer overflows, null pointer dereferences, and memory leaks. See the project page at http://smatch.sourceforge.net/.

Coccinelle is another static analyzer at our disposal. Coccinelle is often used to aid refactoring and collateral evolution of source code, but it can also help to avoid certain bugs that occur in common code patterns. The types of tests available include API tests, tests for correct usage of kernel iterators, checks for the soundness of free operations, analysis of locking behavior, and further tests known to help keep consistent kernel usage. See the Documentation/dev-tools/coccinelle.rst documentation page for details.

Beware, though, that static analysis tools suffer from false positives. Errors and warns need to be evaluated carefully before attempting to fix them.

When to use Sparse and Smatch #

Sparse does type checking, such as verifying that annotated variables do not cause endianness bugs, detecting places that use __user pointers improperly, and analyzing the compatibility of symbol initializers.

Smatch does flow analysis and, if allowed to build the function database, it also does cross function analysis. Smatch tries to answer questions like where is this buffer allocated? How big is it? Can this index be controlled by the user? Is this variable larger than that variable?

It's generally easier to write checks in Smatch than it is to write checks in Sparse. Nevertheless, there are some overlaps between Sparse and Smatch checks.

Strong points of Smatch and Coccinelle #

Coccinelle is probably the easiest for writing checks. It works before the pre-processor so it's easier to check for bugs in macros using Coccinelle. Coccinelle also creates patches for you, which no other tool does.

For example, with Coccinelle you can do a mass conversion from kmalloc(x * size, GFP_KERNEL) to kmalloc_array(x, size, GFP_KERNEL), and that's really useful. If you just created a Smatch warning and try to push the work of converting on to the maintainers they would be annoyed. You'd have to argue about each warning if can really overflow or not.

Coccinelle does no analysis of variable values, which is the strong point of Smatch. On the other hand, Coccinelle allows you to do simple things in a simple way.

Undefined Behavior Sanitizer - UBSAN

Peios Kernel / Kernel development / Development tools

UBSAN is a runtime undefined behaviour checker.

UBSAN uses compile-time instrumentation to catch undefined behavior (UB). Compiler inserts code that perform certain kinds of checks before operations that may cause UB. If check fails (i.e. UB detected) __ubsan_handle_* function called to print error message.

GCC has that feature since 4.9.x [1] (see -fsanitize=undefined option and its suboptions). GCC 5.x has more checkers implemented [2].

Report example #

================================================================================
UBSAN: Undefined behaviour in ../include/linux/bitops.h:110:33
shift exponent 32 is to large for 32-bit type 'unsigned int'
CPU: 0 PID: 0 Comm: swapper Not tainted 4.4.0-rc1+ #26
 0000000000000000 ffffffff82403cc8 ffffffff815e6cd6 0000000000000001
 ffffffff82403cf8 ffffffff82403ce0 ffffffff8163a5ed 0000000000000020
 ffffffff82403d78 ffffffff8163ac2b ffffffff815f0001 0000000000000002
Call Trace:
 [<ffffffff815e6cd6>] dump_stack+0x45/0x5f
 [<ffffffff8163a5ed>] ubsan_epilogue+0xd/0x40
 [<ffffffff8163ac2b>] __ubsan_handle_shift_out_of_bounds+0xeb/0x130
 [<ffffffff815f0001>] ? radix_tree_gang_lookup_slot+0x51/0x150
 [<ffffffff8173c586>] _mix_pool_bytes+0x1e6/0x480
 [<ffffffff83105653>] ? dmi_walk_early+0x48/0x5c
 [<ffffffff8173c881>] add_device_randomness+0x61/0x130
 [<ffffffff83105b35>] ? dmi_save_one_device+0xaa/0xaa
 [<ffffffff83105653>] dmi_walk_early+0x48/0x5c
 [<ffffffff831066ae>] dmi_scan_machine+0x278/0x4b4
 [<ffffffff8111d58a>] ? vprintk_default+0x1a/0x20
 [<ffffffff830ad120>] ? early_idt_handler_array+0x120/0x120
 [<ffffffff830b2240>] setup_arch+0x405/0xc2c
 [<ffffffff830ad120>] ? early_idt_handler_array+0x120/0x120
 [<ffffffff830ae053>] start_kernel+0x83/0x49a
 [<ffffffff830ad120>] ? early_idt_handler_array+0x120/0x120
 [<ffffffff830ad386>] x86_64_start_reservations+0x2a/0x2c
 [<ffffffff830ad4f3>] x86_64_start_kernel+0x16b/0x17a
================================================================================

Usage #

To enable UBSAN, configure the kernel with:

CONFIG_UBSAN=y

To exclude files from being instrumented use:

UBSAN_SANITIZE_main.o := n

and to exclude all targets in one directory use:

UBSAN_SANITIZE := n

When disabled for all targets, specific files can be enabled using:

UBSAN_SANITIZE_main.o := y

Detection of unaligned accesses controlled through the separate option - CONFIG_UBSAN_ALIGNMENT. It's off by default on architectures that support unaligned accesses (CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS=y). One could still enable it in config, just note that it will produce a lot of UBSAN reports.

References #

KUnit - Linux Kernel Unit Testing

Peios Kernel / Kernel development / Development tools / kunit

Contents:

  • Getting Started
  • KUnit Architecture
  • Running tests with kunit_tool
  • Run Tests without kunit_tool
  • Writing Tests
  • API Reference
  • Test Style and Nomenclature
  • Frequently Asked Questions
  • Tips For Running KUnit Tests

This section details the kernel unit testing framework.

Introduction #

KUnit (Kernel unit testing framework) provides a common framework for unit tests within the Linux kernel. Using KUnit, you can define groups of test cases called test suites. The tests either run on kernel boot if built-in, or load as a module. KUnit automatically flags and reports failed test cases in the kernel log. The test results appear in KTAP (Kernel - Test Anything Protocol) format. It is inspired by JUnit, Python’s unittest.mock, and GoogleTest/GoogleMock (C++ unit testing framework).

KUnit tests are part of the kernel, written in the C (programming) language, and test parts of the Kernel implementation (example: a C language function). Excluding build time, from invocation to completion, KUnit can run around 100 tests in less than 10 seconds. KUnit can test any kernel component, for example: file system, system calls, memory management, device drivers and so on.

KUnit follows the white-box testing approach. The test has access to internal system functionality. KUnit runs in kernel space and is not restricted to things exposed to user-space.

In addition, KUnit has kunit_tool, a script (tools/testing/kunit/kunit.py) that configures the Linux kernel, runs KUnit tests under QEMU or UML (User Mode Linux), parses the test results and displays them in a user friendly manner.

Features #

  • Provides a framework for writing unit tests.

  • Runs tests on any kernel architecture.

  • Runs a test in milliseconds.

Prerequisites #

  • Any Linux kernel compatible hardware.

  • For Kernel under test, Linux kernel version 5.5 or greater.

Unit Testing #

A unit test tests a single unit of code in isolation. A unit test is the finest granularity of testing and allows all possible code paths to be tested in the code under test. This is possible if the code under test is small and does not have any external dependencies outside of the test's control like hardware.

Write Unit Tests #

To write good unit tests, there is a simple but powerful pattern: Arrange-Act-Assert. This is a great way to structure test cases and defines an order of operations.

  • Arrange inputs and targets: At the start of the test, arrange the data that allows a function to work. Example: initialize a statement or object.

  • Act on the target behavior: Call your function/code under test.

  • Assert expected outcome: Verify that the result (or resulting state) is as expected.

Unit Testing Advantages #

  • Increases testing speed and development in the long run.

  • Detects bugs at initial stage and therefore decreases bug fix cost compared to acceptance testing.

  • Improves code quality.

  • Encourages writing testable code.

Read also What is the difference between a unit test and other kinds of tests?.

How do I use it? #

You can find a step-by-step guide to writing and running KUnit tests in Documentation/dev-tools/kunit/start.rst

Alternatively, feel free to look through the rest of the KUnit documentation, or to experiment with tools/testing/kunit/kunit.py and the example test under lib/kunit/kunit-example-test.c

Happy testing!

KUnit Architecture

Peios Kernel / Kernel development / Development tools / kunit

The KUnit architecture is divided into two parts:

  • In-Kernel Testing Framework

  • kunit_tool (Command-line Test Harness)

In-Kernel Testing Framework #

The kernel testing library supports KUnit tests written in C using KUnit. These KUnit tests are kernel code. KUnit performs the following tasks:

  • Organizes tests

  • Reports test results

  • Provides test utilities

Test Cases #

The test case is the fundamental unit in KUnit. KUnit test cases are organised into suites. A KUnit test case is a function with type signature void (*)(struct kunit *test). These test case functions are wrapped in a struct called struct kunit_case.

Each KUnit test case receives a struct kunit context object that tracks a running test. The KUnit assertion macros and other KUnit utilities use the struct kunit context object. As an exception, there are two fields:

  • ->priv: The setup functions can use it to store arbitrary test user data.

  • ->param_value: It contains the parameter value which can be retrieved in the parameterized tests.

Test Suites #

A KUnit suite includes a collection of test cases. The KUnit suites are represented by the struct kunit_suite. For example:

static struct kunit_case example_test_cases[] = {
        KUNIT_CASE(example_test_foo),
        KUNIT_CASE(example_test_bar),
        KUNIT_CASE(example_test_baz),
        {}
};

static struct kunit_suite example_test_suite = {
        .name = "example",
        .init = example_test_init,
        .exit = example_test_exit,
        .test_cases = example_test_cases,
};
kunit_test_suite(example_test_suite);

In the above example, the test suite example_test_suite, runs the test cases example_test_foo, example_test_bar, and example_test_baz. Before running the test, the example_test_init is called and after running the test, example_test_exit is called. The kunit_test_suite(example_test_suite) registers the test suite with the KUnit test framework.

Executor #

The KUnit executor can list and run built-in KUnit tests on boot. The Test suites are stored in a linker section called .kunit_test_suites. For the code, see KUNIT_TABLE() macro definition in include/asm-generic/vmlinux.lds.h. The linker section consists of an array of pointers to struct kunit_suite, and is populated by the kunit_test_suites() macro. The KUnit executor iterates over the linker section array in order to run all the tests that are compiled into the kernel.

KUnit Suite Memory

KUnit Suite Memory Diagram

On the kernel boot, the KUnit executor uses the start and end addresses of this section to iterate over and run all tests. For the implementation of the executor, see lib/kunit/executor.c. When built as a module, the kunit_test_suites() macro defines a module_init() function, which runs all the tests in the compilation unit instead of utilizing the executor.

In KUnit tests, some error classes do not affect other tests or parts of the kernel, each KUnit case executes in a separate thread context. See the kunit_try_catch_run() function in lib/kunit/try-catch.c.

Assertion Macros #

KUnit tests verify state using expectations/assertions. All expectations/assertions are formatted as: KUNIT_{EXPECT|ASSERT}_<op>[_MSG](kunit, property[, message])

  • {EXPECT|ASSERT} determines whether the check is an assertion or an expectation. In the event of a failure, the testing flow differs as follows:

    • For expectations, the test is marked as failed and the failure is logged.

    • Failing assertions, on the other hand, result in the test case being terminated immediately.

      • Assertions call the function: void __noreturn __kunit_abort(struct kunit *).

      • __kunit_abort calls the function: void __noreturn kunit_try_catch_throw(struct kunit_try_catch *try_catch).

      • kunit_try_catch_throw calls the function: void kthread_complete_and_exit(struct completion *, long) __noreturn; and terminates the special thread context.

  • <op> denotes a check with options: TRUE (supplied property has the boolean value "true"), EQ (two supplied properties are equal), NOT_ERR_OR_NULL (supplied pointer is not null and does not contain an "err" value).

  • [_MSG] prints a custom message on failure.

Test Result Reporting #

KUnit prints the test results in KTAP format. KTAP is based on TAP14, see Documentation/dev-tools/ktap.rst. KTAP works with KUnit and Kselftest. The KUnit executor prints KTAP results to dmesg, and debugfs (if configured).

Parameterized Tests #

Each KUnit parameterized test is associated with a collection of parameters. The test is invoked multiple times, once for each parameter value and the parameter is stored in the param_value field. The test case includes a KUNIT_CASE_PARAM() macro that accepts a generator function. The generator function is passed the previous parameter and returns the next parameter. It also includes a macro for generating array-based common-case generators.

kunit_tool (Command-line Test Harness) #

kunit_tool is a Python script, found in tools/testing/kunit/kunit.py. It is used to configure, build, execute, parse test results and run all of the previous commands in correct order (i.e., configure, build, execute and parse). You have two options for running KUnit tests: either build the kernel with KUnit enabled and manually parse the results (see Documentation/dev-tools/kunit/run_manual.rst) or use kunit_tool (see Documentation/dev-tools/kunit/run_wrapper.rst).

  • configure command generates the kernel .config from a .kunitconfig file (and any architecture-specific options). The Python scripts available in qemu_configs folder (for example, tools/testing/kunit/qemu configs/powerpc.py) contains additional configuration options for specific architectures. It parses both the existing .config and the .kunitconfig files to ensure that .config is a superset of .kunitconfig. If not, it will combine the two and run make olddefconfig to regenerate the .config file. It then checks to see if .config has become a superset. This verifies that all the Kconfig dependencies are correctly specified in the file .kunitconfig. The kunit_config.py script contains the code for parsing Kconfigs. The code which runs make olddefconfig is part of the kunit_kernel.py script. You can invoke this command through: ./tools/testing/kunit/kunit.py config and generate a .config file.

  • build runs make on the kernel tree with required options (depends on the architecture and some options, for example: build_dir) and reports any errors. To build a KUnit kernel from the current .config, you can use the build argument: ./tools/testing/kunit/kunit.py build.

  • exec command executes kernel results either directly (using User-mode Linux configuration), or through an emulator such as QEMU. It reads results from the log using standard output (stdout), and passes them to parse to be parsed. If you already have built a kernel with built-in KUnit tests, you can run the kernel and display the test results with the exec argument: ./tools/testing/kunit/kunit.py exec.

  • parse extracts the KTAP output from a kernel log, parses the test results, and prints a summary. For failed tests, any diagnostic output will be included.

Frequently Asked Questions

Peios Kernel / Kernel development / Development tools / kunit

How is this different from Autotest, kselftest, and so on? #

KUnit is a unit testing framework. Autotest, kselftest (and some others) are not.

A unit test is supposed to test a single unit of code in isolation and hence the name unit test. A unit test should be the finest granularity of testing and should allow all possible code paths to be tested in the code under test. This is only possible if the code under test is small and does not have any external dependencies outside of the test's control like hardware.

There are no testing frameworks currently available for the kernel that do not require installing the kernel on a test machine or in a virtual machine. All testing frameworks require tests to be written in userspace and run on the kernel under test. This is true for Autotest, kselftest, and some others, disqualifying any of them from being considered unit testing frameworks.

Does KUnit support running on architectures other than UML? #

Yes, mostly.

For the most part, the KUnit core framework (what we use to write the tests) can compile to any architecture. It compiles like just another part of the kernel and runs when the kernel boots, or when built as a module, when the module is loaded. However, there is infrastructure, like the KUnit Wrapper (tools/testing/kunit/kunit.py) that might not support some architectures (see Running tests on QEMU).

In short, yes, you can run KUnit on other architectures, but it might require more work than using KUnit on UML.

For more information, see Writing Tests For Other Architectures.

What is the difference between a unit test and other kinds of tests? #

Most existing tests for the Linux kernel would be categorized as an integration test, or an end-to-end test.

  • A unit test is supposed to test a single unit of code in isolation. A unit test should be the finest granularity of testing and, as such, allows all possible code paths to be tested in the code under test. This is only possible if the code under test is small and does not have any external dependencies outside of the test's control like hardware.

  • An integration test tests the interaction between a minimal set of components, usually just two or three. For example, someone might write an integration test to test the interaction between a driver and a piece of hardware, or to test the interaction between the userspace libraries the kernel provides and the kernel itself. However, one of these tests would probably not test the entire kernel along with hardware interactions and interactions with the userspace.

  • An end-to-end test usually tests the entire system from the perspective of the code under test. For example, someone might write an end-to-end test for the kernel by installing a production configuration of the kernel on production hardware with a production userspace and then trying to exercise some behavior that depends on interactions between the hardware, the kernel, and userspace.

KUnit is not working, what should I do? #

Unfortunately, there are a number of things which can break, but here are some things to try.

  1. Run ./tools/testing/kunit/kunit.py run with the --raw_output parameter. This might show details or error messages hidden by the kunit_tool parser.

  2. Instead of running kunit.py run, try running kunit.py config, kunit.py build, and kunit.py exec independently. This can help track down where an issue is occurring. (If you think the parser is at fault, you can run it manually against stdin or a file with kunit.py parse.)

  3. Running the UML kernel directly can often reveal issues or error messages, kunit_tool ignores. This should be as simple as running ./vmlinux after building the UML kernel (for example, by using kunit.py build). Note that UML has some unusual requirements (such as the host having a tmpfs filesystem mounted), and has had issues in the past when built statically and the host has KASLR enabled. (On older host kernels, you may need to run setarch `uname -m` -R ./vmlinux to disable KASLR.)

  4. Make sure the kernel .config has CONFIG_KUNIT=y and at least one test (e.g. CONFIG_KUNIT_EXAMPLE_TEST=y). kunit_tool will keep its .config around, so you can see what config was used after running kunit.py run. It also preserves any config changes you might make, so you can enable/disable things with make ARCH=um menuconfig or similar, and then re-run kunit_tool.

  5. Try to run make ARCH=um defconfig before running kunit.py run. This may help clean up any residual config items which could be causing problems.

  6. Finally, try running KUnit outside UML. KUnit and KUnit tests can be built into any kernel, or can be built as a module and loaded at runtime. Doing so should allow you to determine if UML is causing the issue you're seeing. When tests are built-in, they will execute when the kernel boots, and modules will automatically execute associated tests when loaded. Test results can be collected from /sys/kernel/debug/kunit/<test suite>/results, and can be parsed with kunit.py parse. For more details, see Running tests on QEMU.

If none of the above tricks help, you are always welcome to email any issues to kunit-dev@googlegroups.com.

Run Tests without kunit_tool

Peios Kernel / Kernel development / Development tools / kunit

If we do not want to use kunit_tool (For example: we want to integrate with other systems, or run tests on real hardware), we can include KUnit in any kernel, read out results, and parse manually.

Note

KUnit is not designed for use in a production system. It is possible that tests may reduce the stability or security of the system.

Configure the Kernel #

KUnit tests can run without kunit_tool. This can be useful, if:

  • We have an existing kernel configuration to test.

  • Need to run on real hardware (or using an emulator/VM kunit_tool does not support).

  • Wish to integrate with some existing testing systems.

KUnit is configured with the CONFIG_KUNIT option, and individual tests can also be built by enabling their config options in our .config. KUnit tests usually (but don't always) have config options ending in _KUNIT_TEST. Most tests can either be built as a module, or be built into the kernel.

Note

We can enable the KUNIT_ALL_TESTS config option to automatically enable all tests with satisfied dependencies. This is a good way of quickly testing everything applicable to the current config.

KUnit can be enabled or disabled at boot time, and this behavior is controlled by the kunit.enable kernel parameter. By default, kunit.enable is set to 1 because KUNIT_DEFAULT_ENABLED is enabled by default. To ensure that tests are executed as expected, verify that kunit.enable=1 at boot time.

Once we have built our kernel (and/or modules), it is simple to run the tests. If the tests are built-in, they will run automatically on the kernel boot. The results will be written to the kernel log (dmesg) in TAP format.

If the tests are built as modules, they will run when the module is loaded.

# modprobe example-test

The results will appear in TAP format in dmesg.

debugfs #

KUnit can be accessed from userspace via the debugfs filesystem (See more information about debugfs at Documentation/filesystems/debugfs.rst).

If CONFIG_KUNIT_DEBUGFS is enabled, the KUnit debugfs filesystem is mounted at /sys/kernel/debug/kunit. You can use this filesystem to perform the following actions.

Retrieve Test Results #

You can use debugfs to retrieve KUnit test results. The test results are accessible from the debugfs filesystem in the following read-only file:

/sys/kernel/debug/kunit/<test_suite>/results

The test results are printed in a KTAP document. Note this document is separate to the kernel log and thus, may have different test suite numbering.

Run Tests After Kernel Has Booted #

You can use the debugfs filesystem to trigger built-in tests to run after boot. To run the test suite, you can use the following command to write to the /sys/kernel/debug/kunit/<test_suite>/run file:

echo "any string" > /sys/kernel/debugfs/kunit/<test_suite>/run

As a result, the test suite runs and the results are printed to the kernel log.

However, this feature is not available with KUnit suites that use init data, because init data may have been discarded after the kernel boots. KUnit suites that use init data should be defined using the kunit_test_init_section_suites() macro.

Also, you cannot use this feature to run tests concurrently. Instead a test will wait to run until other tests have completed or failed.

Note

For test authors, to use this feature, tests will need to correctly initialise and/or clean up any data, so the test runs correctly a second time.

Running tests with kunit_tool

Peios Kernel / Kernel development / Development tools / kunit

We can either run KUnit tests using kunit_tool or can run tests manually, and then use kunit_tool to parse the results. To run tests manually, see: Documentation/dev-tools/kunit/run_manual.rst. As long as we can build the kernel, we can run KUnit.

kunit_tool is a Python script which configures and builds a kernel, runs tests, and formats the test results.

Run command:

./tools/testing/kunit/kunit.py run

We should see the following:

Configuring KUnit Kernel ...
Building KUnit kernel...
Starting KUnit kernel...

We may want to use the following options:

./tools/testing/kunit/kunit.py run --timeout=30 --jobs=`nproc --all`
  • --timeout sets a maximum amount of time for tests to run.

  • --jobs sets the number of threads to build the kernel.

kunit_tool will generate a .kunitconfig with a default configuration, if no other .kunitconfig file exists (in the build directory). In addition, it verifies that the generated .config file contains the CONFIG options in the .kunitconfig. It is also possible to pass a separate .kunitconfig fragment to kunit_tool. This is useful if we have several different groups of tests we want to run independently, or if we want to use pre-defined test configs for certain subsystems.

To use a different .kunitconfig file (such as one provided to test a particular subsystem), pass it as an option:

./tools/testing/kunit/kunit.py run --kunitconfig=fs/ext4/.kunitconfig

To view kunit_tool flags (optional command-line arguments), run:

./tools/testing/kunit/kunit.py run --help

Creating a .kunitconfig file #

If we want to run a specific set of tests (rather than those listed in the KUnit defconfig), we can provide Kconfig options in the .kunitconfig file. For default .kunitconfig, see: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/kunit/configs/default.config. A .kunitconfig is a minconfig (a .config generated by running make savedefconfig), used for running a specific set of tests. This file contains the regular Kernel configs with specific test targets. The .kunitconfig also contains any other config options required by the tests (For example: dependencies for features under tests, configs that enable/disable certain code blocks, arch configs and so on).

To create a .kunitconfig, using the KUnit defconfig:

cd $PATH_TO_LINUX_REPO
cp tools/testing/kunit/configs/default.config .kunit/.kunitconfig

We can then add any other Kconfig options. For example:

CONFIG_LIST_KUNIT_TEST=y

kunit_tool ensures that all config options in .kunitconfig are set in the kernel .config before running the tests. It warns if we have not included the options dependencies.

Note

Removing something from the .kunitconfig will not rebuild the .config file. The configuration is only updated if the .kunitconfig is not a subset of .config. This means that we can use other tools (For example: make menuconfig) to adjust other config options. The build dir needs to be set for make menuconfig to work, therefore by default use make O=.kunit menuconfig.

Configuring, building, and running tests #

If we want to make manual changes to the KUnit build process, we can run part of the KUnit build process independently. When running kunit_tool, from a .kunitconfig, we can generate a .config by using the config argument:

./tools/testing/kunit/kunit.py config

To build a KUnit kernel from the current .config, we can use the build argument:

./tools/testing/kunit/kunit.py build

If we already have built UML kernel with built-in KUnit tests, we can run the kernel, and display the test results with the exec argument:

./tools/testing/kunit/kunit.py exec

The run command discussed in section: Running tests with kunit_tool, is equivalent to running the above three commands in sequence.

Parsing test results #

KUnit tests output displays results in TAP (Test Anything Protocol) format. When running tests, kunit_tool parses this output and prints a summary. To see the raw test results in TAP format, we can pass the --raw_output argument:

./tools/testing/kunit/kunit.py run --raw_output

If we have KUnit results in the raw TAP format, we can parse them and print the human-readable summary with the parse command for kunit_tool. This accepts a filename for an argument, or will read from standard input.

# Reading from a file
./tools/testing/kunit/kunit.py parse /var/log/dmesg
# Reading from stdin
dmesg | ./tools/testing/kunit/kunit.py parse

Filtering tests #

By passing a bash style glob filter to the exec or run commands, we can run a subset of the tests built into a kernel . For example: if we only want to run KUnit resource tests, use:

./tools/testing/kunit/kunit.py run 'kunit-resource*'

This uses the standard glob format with wildcard characters.

Running tests on QEMU #

kunit_tool supports running tests on qemu as well as via UML. To run tests on qemu, by default it requires two flags:

  • --arch: Selects a configs collection (Kconfig, qemu config options and so on), that allow KUnit tests to be run on the specified architecture in a minimal way. The architecture argument is same as the option name passed to the ARCH variable used by Kbuild. Not all architectures currently support this flag, but we can use --qemu_config to handle it. If um is passed (or this flag is ignored), the tests will run via UML. Non-UML architectures, for example: i386, x86_64, arm and so on; run on qemu.

    --arch help lists all valid --arch values.

  • --cross_compile: Specifies the Kbuild toolchain. It passes the same argument as passed to the CROSS_COMPILE variable used by Kbuild. As a reminder, this will be the prefix for the toolchain binaries such as GCC. For example:

    • sparc64-linux-gnu if we have the sparc toolchain installed on our system.

    • $HOME/toolchains/microblaze/gcc-9.2.0-nolibc/microblaze-linux/bin/microblaze-linux if we have downloaded the microblaze toolchain from the 0-day website to a directory in our home directory called toolchains.

This means that for most architectures, running under qemu is as simple as:

./tools/testing/kunit/kunit.py run --arch=x86_64

When cross-compiling, we'll likely need to specify a different toolchain, for example:

./tools/testing/kunit/kunit.py run \
        --arch=s390 \
        --cross_compile=s390x-linux-gnu-

If we want to run KUnit tests on an architecture not supported by the --arch flag, or want to run KUnit tests on qemu using a non-default configuration; then we can write our own``QemuConfig``. These QemuConfigs are written in Python. They have an import line from..qemu_config import QemuArchParams at the top of the file. The file must contain a variable called QEMU_ARCH that has an instance of QemuArchParams assigned to it. See example in: tools/testing/kunit/qemu_configs/x86_64.py.

Once we have a QemuConfig, we can pass it into kunit_tool, using the --qemu_config flag. When used, this flag replaces the --arch flag. For example: using tools/testing/kunit/qemu_configs/x86_64.py, the invocation appear as

./tools/testing/kunit/kunit.py run \
        --timeout=60 \
        --jobs=12 \
        --qemu_config=./tools/testing/kunit/qemu_configs/x86_64.py

Running command-line arguments #

kunit_tool has a number of other command-line arguments which can be useful for our test environment. Below are the most commonly used command line arguments:

  • --help: Lists all available options. To list common options, place --help before the command. To list options specific to that command, place --help after the command.

    Note

    Different commands (config, build, run, etc) have different supported options.

  • --build_dir: Specifies kunit_tool build directory. It includes the .kunitconfig, .config files and compiled kernel.

  • --make_options: Specifies additional options to pass to make, when compiling a kernel (using build or run commands). For example: to enable compiler warnings, we can pass --make_options W=1.

  • --alltests: Enable a predefined set of options in order to build as many tests as possible.

    Note

    The list of enabled options can be found in tools/testing/kunit/configs/all_tests.config.

    If you only want to enable all tests with otherwise satisfied dependencies, instead add CONFIG_KUNIT_ALL_TESTS=y to your .kunitconfig.

  • --kunitconfig: Specifies the path or the directory of the .kunitconfig file. For example:

    • lib/kunit/.kunitconfig can be the path of the file.

    • lib/kunit can be the directory in which the file is located.

    This file is used to build and run with a predefined set of tests and their dependencies. For example, to run tests for a given subsystem.

  • --kconfig_add: Specifies additional configuration options to be appended to the .kunitconfig file. For example:

    ./tools/testing/kunit/kunit.py run --kconfig_add CONFIG_KASAN=y
    
  • --arch: Runs tests on the specified architecture. The architecture argument is same as the Kbuild ARCH environment variable. For example, i386, x86_64, arm, um, etc. Non-UML architectures run on qemu. Default is um.

  • --cross_compile: Specifies the Kbuild toolchain. It passes the same argument as passed to the CROSS_COMPILE variable used by Kbuild. This will be the prefix for the toolchain binaries such as GCC. For example:

    • sparc64-linux-gnu- if we have the sparc toolchain installed on our system.

    • $HOME/toolchains/microblaze/gcc-9.2.0-nolibc/microblaze-linux/bin/microblaze-linux if we have downloaded the microblaze toolchain from the 0-day website to a specified path in our home directory called toolchains.

  • --qemu_config: Specifies the path to a file containing a custom qemu architecture definition. This should be a python file containing a QemuArchParams object.

  • --qemu_args: Specifies additional qemu arguments, for example, -smp 8.

  • --jobs: Specifies the number of jobs (commands) to run simultaneously. By default, this is set to the number of cores on your system.

  • --timeout: Specifies the maximum number of seconds allowed for all tests to run. This does not include the time taken to build the tests.

  • --kernel_args: Specifies additional kernel command-line arguments. May be repeated.

  • --run_isolated: If set, boots the kernel for each individual suite/test. This is useful for debugging a non-hermetic test, one that might pass/fail based on what ran before it.

  • --raw_output: If set, generates unformatted output from kernel. Possible options are:

    • all: To view the full kernel output, use --raw_output=all.

    • kunit: This is the default option and filters to KUnit output. Use --raw_output or --raw_output=kunit.

  • --json: If set, stores the test results in a JSON format and prints to stdout or saves to a file if a filename is specified.

  • --filter: Specifies filters on test attributes, for example, speed!=slow. Multiple filters can be used by wrapping input in quotes and separating filters by commas. Example: --filter "speed>slow, module=example".

  • --filter_action: If set to skip, filtered tests will be shown as skipped in the output rather than showing no output.

  • --list_tests: If set, lists all tests that will be run.

  • --list_tests_attr: If set, lists all tests that will be run and all of their attributes.

  • --list_suites: If set, lists all suites that will be run.

Command-line completion #

The kunit_tool comes with a bash completion script:

source tools/testing/kunit/kunit-completion.sh

Tips For Running KUnit Tests

Peios Kernel / Kernel development / Development tools / kunit

Using kunit.py run ("kunit tool") #

Running from any directory #

It can be handy to create a bash function like:

function run_kunit() {
  ( cd "$(git rev-parse --show-toplevel)" && ./tools/testing/kunit/kunit.py run "$@" )
}

Note

Early versions of kunit.py (before 5.6) didn't work unless run from the kernel root, hence the use of a subshell and cd.

Running a subset of tests #

kunit.py run accepts an optional glob argument to filter tests. The format is "<suite_glob>[.test_glob]".

Say that we wanted to run the sysctl tests, we could do so via:

$ echo -e 'CONFIG_KUNIT=y\nCONFIG_KUNIT_ALL_TESTS=y' > .kunit/.kunitconfig
$ ./tools/testing/kunit/kunit.py run 'sysctl*'

We can filter down to just the "write" tests via:

$ echo -e 'CONFIG_KUNIT=y\nCONFIG_KUNIT_ALL_TESTS=y' > .kunit/.kunitconfig
$ ./tools/testing/kunit/kunit.py run 'sysctl*.*write*'

We're paying the cost of building more tests than we need this way, but it's easier than fiddling with .kunitconfig files or commenting out kunit_suite's.

However, if we wanted to define a set of tests in a less ad hoc way, the next tip is useful.

Defining a set of tests #

kunit.py run (along with build, and config) supports a --kunitconfig flag. So if you have a set of tests that you want to run on a regular basis (especially if they have other dependencies), you can create a specific .kunitconfig for them.

E.g. kunit has one for its tests:

$ ./tools/testing/kunit/kunit.py run --kunitconfig=lib/kunit/.kunitconfig

Alternatively, if you're following the convention of naming your file .kunitconfig, you can just pass in the dir, e.g.

$ ./tools/testing/kunit/kunit.py run --kunitconfig=lib/kunit

Note

This is a relatively new feature (5.12+) so we don't have any conventions yet about on what files should be checked in versus just kept around locally. It's up to you and your maintainer to decide if a config is useful enough to submit (and therefore have to maintain).

Note

Having .kunitconfig fragments in a parent and child directory is iffy. There's discussion about adding an "import" statement in these files to make it possible to have a top-level config run tests from all child directories. But that would mean .kunitconfig files are no longer just simple .config fragments.

One alternative would be to have kunit tool recursively combine configs automagically, but tests could theoretically depend on incompatible options, so handling that would be tricky.

Setting kernel commandline parameters #

You can use --kernel_args to pass arbitrary kernel arguments, e.g.

$ ./tools/testing/kunit/kunit.py run --kernel_args=param=42 --kernel_args=param2=false

Generating code coverage reports under UML #

Note

TODO(brendanhiggins@google.com): There are various issues with UML and versions of gcc 7 and up. You're likely to run into missing .gcda files or compile errors.

This is different from the "normal" way of getting coverage information that is documented in Documentation/dev-tools/gcov.rst.

Instead of enabling CONFIG_GCOV_KERNEL=y, we can set these options:

CONFIG_DEBUG_KERNEL=y
CONFIG_DEBUG_INFO=y
CONFIG_DEBUG_INFO_DWARF_TOOLCHAIN_DEFAULT=y
CONFIG_GCOV=y

Putting it together into a copy-pastable sequence of commands:

# Append coverage options to the current config
$ ./tools/testing/kunit/kunit.py run --kunitconfig=.kunit/ --kunitconfig=tools/testing/kunit/configs/coverage_uml.config
# Extract the coverage information from the build dir (.kunit/)
$ lcov -t "my_kunit_tests" -o coverage.info -c -d .kunit/

# From here on, it's the same process as with CONFIG_GCOV_KERNEL=y
# E.g. can generate an HTML report in a tmp dir like so:
$ genhtml -o /tmp/coverage_html coverage.info

If your installed version of gcc doesn't work, you can tweak the steps:

$ ./tools/testing/kunit/kunit.py run --make_options=CC=/usr/bin/gcc-6
$ lcov -t "my_kunit_tests" -o coverage.info -c -d .kunit/ --gcov-tool=/usr/bin/gcov-6

Alternatively, LLVM-based toolchains can also be used:

# Build with LLVM and append coverage options to the current config
$ ./tools/testing/kunit/kunit.py run --make_options LLVM=1 --kunitconfig=.kunit/ --kunitconfig=tools/testing/kunit/configs/coverage_uml.config
$ llvm-profdata merge -sparse default.profraw -o default.profdata
$ llvm-cov export --format=lcov .kunit/vmlinux -instr-profile default.profdata > coverage.info
# The coverage.info file is in lcov-compatible format and it can be used to e.g. generate HTML report
$ genhtml -o /tmp/coverage_html coverage.info

Running tests manually #

Running tests without using kunit.py run is also an important use case. Currently it's your only option if you want to test on architectures other than UML.

As running the tests under UML is fairly straightforward (configure and compile the kernel, run the ./linux binary), this section will focus on testing non-UML architectures.

Running built-in tests #

When setting tests to =y, the tests will run as part of boot and print results to dmesg in TAP format. So you just need to add your tests to your .config, build and boot your kernel as normal.

So if we compiled our kernel with:

CONFIG_KUNIT=y
CONFIG_KUNIT_EXAMPLE_TEST=y

Then we'd see output like this in dmesg signaling the test ran and passed:

TAP version 14
1..1
    # Subtest: example
    1..1
    # example_simple_test: initializing
    ok 1 - example_simple_test
ok 1 - example

Running tests as modules #

Depending on the tests, you can build them as loadable modules.

For example, we'd change the config options from before to

CONFIG_KUNIT=y
CONFIG_KUNIT_EXAMPLE_TEST=m

Then after booting into our kernel, we can run the test via

$ modprobe kunit-example-test

This will then cause it to print TAP output to stdout.

Note

The modprobe will not have a non-zero exit code if any test failed (as of 5.13). But kunit.py parse would, see below.

Note

You can set CONFIG_KUNIT=m as well, however, some features will not work and thus some tests might break. Ideally tests would specify they depend on KUNIT=y in their Kconfig's, but this is an edge case most test authors won't think about. As of 5.13, the only difference is that current->kunit_test will not exist.

Pretty-printing results #

You can use kunit.py parse to parse dmesg for test output and print out results in the same familiar format that kunit.py run does.

$ ./tools/testing/kunit/kunit.py parse /var/log/dmesg

Retrieving per suite results #

Regardless of how you're running your tests, you can enable CONFIG_KUNIT_DEBUGFS to expose per-suite TAP-formatted results:

CONFIG_KUNIT=y
CONFIG_KUNIT_EXAMPLE_TEST=m
CONFIG_KUNIT_DEBUGFS=y

The results for each suite will be exposed under /sys/kernel/debug/kunit/<suite>/results. So using our example config:

$ modprobe kunit-example-test > /dev/null
$ cat /sys/kernel/debug/kunit/example/results
... <TAP output> ...

# After removing the module, the corresponding files will go away
$ modprobe -r kunit-example-test
$ cat /sys/kernel/debug/kunit/example/results
/sys/kernel/debug/kunit/example/results: No such file or directory

Generating code coverage reports #

See Documentation/dev-tools/gcov.rst for details on how to do this.

The only vaguely KUnit-specific advice here is that you probably want to build your tests as modules. That way you can isolate the coverage from tests from other code executed during boot, e.g.

# Reset coverage counters before running the test.
$ echo 0 > /sys/kernel/debug/gcov/reset
$ modprobe kunit-example-test

Test Attributes and Filtering #

Test suites and cases can be marked with test attributes, such as speed of test. These attributes will later be printed in test output and can be used to filter test execution.

Marking Test Attributes #

Tests are marked with an attribute by including a kunit_attributes object in the test definition.

Test cases can be marked using the KUNIT_CASE_ATTR(test_name, attributes) macro to define the test case instead of KUNIT_CASE(test_name).

static const struct kunit_attributes example_attr = {
        .speed = KUNIT_VERY_SLOW,
};

static struct kunit_case example_test_cases[] = {
        KUNIT_CASE_ATTR(example_test, example_attr),
};

Note

To mark a test case as slow, you can also use KUNIT_CASE_SLOW(test_name). This is a helpful macro as the slow attribute is the most commonly used.

Test suites can be marked with an attribute by setting the "attr" field in the suite definition.

static const struct kunit_attributes example_attr = {
        .speed = KUNIT_VERY_SLOW,
};

static struct kunit_suite example_test_suite = {
        ...,
        .attr = example_attr,
};

Note

Not all attributes need to be set in a kunit_attributes object. Unset attributes will remain uninitialized and act as though the attribute is set to 0 or NULL. Thus, if an attribute is set to 0, it is treated as unset. These unset attributes will not be reported and may act as a default value for filtering purposes.

Reporting Attributes #

When a user runs tests, attributes will be present in the raw kernel output (in KTAP format). Note that attributes will be hidden by default in kunit.py output for all passing tests but the raw kernel output can be accessed using the --raw_output flag. This is an example of how test attributes for test cases will be formatted in kernel output:

# example_test.speed: slow
ok 1 example_test

This is an example of how test attributes for test suites will be formatted in kernel output:

  KTAP version 2
  # Subtest: example_suite
  # module: kunit_example_test
  1..3
  ...
ok 1 example_suite

Additionally, users can output a full attribute report of tests with their attributes, using the command line flag --list_tests_attr:

kunit.py run "example" --list_tests_attr

Note

This report can be accessed when running KUnit manually by passing in the module_param kunit.action=list_attr.

Filtering #

Users can filter tests using the --filter command line flag when running tests. As an example:

kunit.py run --filter speed=slow

You can also use the following operations on filters: "<", ">", "<=", ">=", "!=", and "=". Example:

kunit.py run --filter "speed>slow"

This example will run all tests with speeds faster than slow. Note that the characters < and > are often interpreted by the shell, so they may need to be quoted or escaped, as above.

Additionally, you can use multiple filters at once. Simply separate filters using commas. Example:

kunit.py run --filter "speed>slow, module=kunit_example_test"

Note

You can use this filtering feature when running KUnit manually by passing the filter as a module param: kunit.filter="speed>slow, speed<=normal".

Filtered tests will not run or show up in the test output. You can use the --filter_action=skip flag to skip filtered tests instead. These tests will be shown in the test output in the test but will not run. To use this feature when running KUnit manually, use the module param kunit.filter_action=skip.

Rules of Filtering Procedure #

Since both suites and test cases can have attributes, there may be conflicts between attributes during filtering. The process of filtering follows these rules:

  • Filtering always operates at a per-test level.

  • If a test has an attribute set, then the test's value is filtered on.

  • Otherwise, the value falls back to the suite's value.

  • If neither are set, the attribute has a global "default" value, which is used.

List of Current Attributes #

speed

This attribute indicates the speed of a test's execution (how slow or fast the test is).

This attribute is saved as an enum with the following categories: "normal", "slow", or "very_slow". The assumed default speed for tests is "normal". This indicates that the test takes a relatively trivial amount of time (less than 1 second), regardless of the machine it is running on. Any test slower than this could be marked as "slow" or "very_slow".

The macro KUNIT_CASE_SLOW(test_name) can be easily used to set the speed of a test case to "slow".

module

This attribute indicates the name of the module associated with the test.

This attribute is automatically saved as a string and is printed for each suite. Tests can also be filtered using this attribute.

is_init

This attribute indicates whether the test uses init data or functions.

This attribute is automatically saved as a boolean and tests can also be filtered using this attribute.

Getting Started

Peios Kernel / Kernel development / Development tools / kunit

Peios: Use Building Peios for the repository build, toolchain, configuration and test entry points. This article describes the underlying Linux machinery or upstream workflow. Its standalone build/install commands do not establish a qualified Peios kernel or signed release modules.

This page contains an overview of the kunit_tool and KUnit framework, teaching how to run existing tests and then how to write a simple test case, and covers common problems users face when using KUnit for the first time.

Installing Dependencies #

KUnit has the same dependencies as the Linux kernel. As long as you can build the kernel, you can run KUnit.

Running tests with kunit_tool #

kunit_tool is a Python script, which configures and builds a kernel, runs tests, and formats the test results. From the kernel repository, you can run kunit_tool:

./tools/testing/kunit/kunit.py run

Note

You may see the following error: "The source tree is not clean, please run 'make ARCH=um mrproper'"

This happens because internally kunit.py specifies .kunit (default option) as the build directory in the command make O=output/dir through the argument --build_dir. Hence, before starting an out-of-tree build, the source tree must be clean.

There is also the same caveat mentioned in the "Build directory for the kernel" section of the admin-guide, that is, its use, it must be used for all invocations of make. The good news is that it can indeed be solved by running make ARCH=um mrproper, just be aware that this will delete the current configuration and all generated files.

If everything worked correctly, you should see the following:

Configuring KUnit Kernel ...
Building KUnit Kernel ...
Starting KUnit Kernel ...

The tests will pass or fail.

Note

Because it is building a lot of sources for the first time, the Building KUnit Kernel step may take a while.

For detailed information on this wrapper, see: Documentation/dev-tools/kunit/run_wrapper.rst.

Selecting which tests to run #

By default, kunit_tool runs all tests reachable with minimal configuration, that is, using default values for most of the kconfig options. However, you can select which tests to run by:

  • Customizing Kconfig used to compile the kernel, or

  • Filtering tests by name to select specifically which compiled tests to run.

Customizing Kconfig #

A good starting point for the .kunitconfig is the KUnit default config. If you didn't run kunit.py run yet, you can generate it by running:

cd $PATH_TO_LINUX_REPO
tools/testing/kunit/kunit.py config
cat .kunit/.kunitconfig

Note

.kunitconfig lives in the --build_dir used by kunit.py, which is .kunit by default.

Before running the tests, kunit_tool ensures that all config options set in .kunitconfig are set in the kernel .config. It will warn you if you have not included dependencies for the options used.

There are many ways to customize the configurations:

  • a. Edit .kunit/.kunitconfig. The file should contain the list of kconfig options required to run the desired tests, including their dependencies. You may want to remove CONFIG_KUNIT_ALL_TESTS from the .kunitconfig as it will enable a number of additional tests that you may not want. If you need to run on an architecture other than UML see Running tests on QEMU.

  • b. Enable additional kconfig options on top of .kunit/.kunitconfig. For example, to include the kernel's linked-list test you can run:

    ./tools/testing/kunit/kunit.py run \
            --kconfig_add CONFIG_LIST_KUNIT_TEST=y
    
  • c. Provide the path of one or more .kunitconfig files from the tree. For example, to run only FAT_FS and EXT4 tests you can run:

    ./tools/testing/kunit/kunit.py run \
            --kunitconfig ./fs/fat/.kunitconfig \
            --kunitconfig ./fs/ext4/.kunitconfig
    
  • d. If you change the .kunitconfig, kunit.py will trigger a rebuild of the .config file. But you can edit the .config file directly or with tools like make menuconfig O=.kunit. As long as its a superset of .kunitconfig, kunit.py won't overwrite your changes.

Note

To save a .kunitconfig after finding a satisfactory configuration:

make savedefconfig O=.kunit
cp .kunit/defconfig .kunit/.kunitconfig

Filtering tests by name #

If you want to be more specific than Kconfig can provide, it is also possible to select which tests to execute at boot-time by passing a glob filter (read instructions regarding the pattern in the manpage glob(7)). If there is a "." (period) in the filter, it will be interpreted as a separator between the name of the test suite and the test case, otherwise, it will be interpreted as the name of the test suite. For example, let's assume we are using the default config:

  • a. inform the name of a test suite, like "kunit_executor_test", to run every test case it contains:

    ./tools/testing/kunit/kunit.py run "kunit_executor_test"
    
  • b. inform the name of a test case prefixed by its test suite, like "example.example_simple_test", to run specifically that test case:

    ./tools/testing/kunit/kunit.py run "example.example_simple_test"
    
  • c. use wildcard characters (*?[) to run any test case that matches the pattern, like "*.*64*" to run test cases containing "64" in the name inside any test suite:

    ./tools/testing/kunit/kunit.py run "*.*64*"
    

Running Tests without the KUnit Wrapper #

If you do not want to use the KUnit Wrapper (for example: you want code under test to integrate with other systems, or use a different/ unsupported architecture or configuration), KUnit can be included in any kernel, and the results are read out and parsed manually.

Note

CONFIG_KUNIT should not be enabled in a production environment. Enabling KUnit disables Kernel Address-Space Layout Randomization (KASLR), and tests may affect the state of the kernel in ways not suitable for production.

Configuring the Kernel #

To enable KUnit itself, you need to enable the CONFIG_KUNIT Kconfig option (under Kernel Hacking/Kernel Testing and Coverage in menuconfig). From there, you can enable any KUnit tests. They usually have config options ending in _KUNIT_TEST.

KUnit and KUnit tests can be compiled as modules. The tests in a module will run when the module is loaded.

Running Tests (without KUnit Wrapper) #

Build and run your kernel. In the kernel log, the test output is printed out in the TAP format. This will only happen by default if KUnit/tests are built-in. Otherwise the module will need to be loaded.

Note

Some lines and/or data may get interspersed in the TAP output.

Writing Your First Test #

In your kernel repository, let's add some code that we can test.

  1. Create a file drivers/misc/example.h, which includes:
int misc_example_add(int left, int right);
  1. Create a file drivers/misc/example.c, which includes:
#include <linux/errno.h>

#include "example.h"

int misc_example_add(int left, int right)
{
        return left + right;
}
  1. Add the following lines to drivers/misc/Kconfig:
config MISC_EXAMPLE
        bool "My example"
  1. Add the following lines to drivers/misc/Makefile:
obj-$(CONFIG_MISC_EXAMPLE) += example.o

Now we are ready to write the test cases.

  1. Add the below test case in drivers/misc/example_test.c:
#include <kunit/test.h>
#include "example.h"

/* Define the test cases. */

static void misc_example_add_test_basic(struct kunit *test)
{
        KUNIT_EXPECT_EQ(test, 1, misc_example_add(1, 0));
        KUNIT_EXPECT_EQ(test, 2, misc_example_add(1, 1));
        KUNIT_EXPECT_EQ(test, 0, misc_example_add(-1, 1));
        KUNIT_EXPECT_EQ(test, INT_MAX, misc_example_add(0, INT_MAX));
        KUNIT_EXPECT_EQ(test, -1, misc_example_add(INT_MAX, INT_MIN));
}

static void misc_example_test_failure(struct kunit *test)
{
        KUNIT_FAIL(test, "This test never passes.");
}

static struct kunit_case misc_example_test_cases[] = {
        KUNIT_CASE(misc_example_add_test_basic),
        KUNIT_CASE(misc_example_test_failure),
        {}
};

static struct kunit_suite misc_example_test_suite = {
        .name = "misc-example",
        .test_cases = misc_example_test_cases,
};
kunit_test_suite(misc_example_test_suite);

MODULE_LICENSE("GPL");
  1. Add the following lines to drivers/misc/Kconfig:
config MISC_EXAMPLE_TEST
        tristate "Test for my example" if !KUNIT_ALL_TESTS
        depends on MISC_EXAMPLE && KUNIT
        default KUNIT_ALL_TESTS

Note: If your test does not support being built as a loadable module (which is discouraged), replace tristate by bool, and depend on KUNIT=y instead of KUNIT.

  1. Add the following lines to drivers/misc/Makefile:
obj-$(CONFIG_MISC_EXAMPLE_TEST) += example_test.o
  1. Add the following lines to .kunit/.kunitconfig:
CONFIG_MISC_EXAMPLE=y
CONFIG_MISC_EXAMPLE_TEST=y
  1. Run the test:
./tools/testing/kunit/kunit.py run

You should see the following failure:

...
[16:08:57] [PASSED] misc-example:misc_example_add_test_basic
[16:08:57] [FAILED] misc-example:misc_example_test_failure
[16:08:57] EXPECTATION FAILED at drivers/misc/example-test.c:17
[16:08:57]      This test never passes.
...

Congrats! You just wrote your first KUnit test.

Next Steps #

If you're interested in using some of the more advanced features of kunit.py, take a look at Documentation/dev-tools/kunit/run_wrapper.rst

If you'd like to run tests without using kunit.py, check out Documentation/dev-tools/kunit/run_manual.rst

For more information on writing KUnit tests (including some common techniques for testing different things), see Documentation/dev-tools/kunit/usage.rst

Test Style and Nomenclature

Peios Kernel / Kernel development / Development tools / kunit

To make finding, writing, and using KUnit tests as simple as possible, it is strongly encouraged that they are named and written according to the guidelines below. While it is possible to write KUnit tests which do not follow these rules, they may break some tooling, may conflict with other tests, and may not be run automatically by testing systems.

It is recommended that you only deviate from these guidelines when:

  1. Porting tests to KUnit which are already known with an existing name.

  2. Writing tests which would cause serious problems if automatically run. For example, non-deterministically producing false positives or negatives, or taking a long time to run.

Subsystems, Suites, and Tests #

To make tests easy to find, they are grouped into suites and subsystems. A test suite is a group of tests which test a related area of the kernel. A subsystem is a set of test suites which test different parts of a kernel subsystem or a driver.

Subsystems #

Every test suite must belong to a subsystem. A subsystem is a collection of one or more KUnit test suites which test the same driver or part of the kernel. A test subsystem should match a single kernel module. If the code being tested cannot be compiled as a module, in many cases the subsystem should correspond to a directory in the source tree or an entry in the MAINTAINERS file. If unsure, follow the conventions set by tests in similar areas.

Test subsystems should be named after the code being tested, either after the module (wherever possible), or after the directory or files being tested. Test subsystems should be named to avoid ambiguity where necessary.

If a test subsystem name has multiple components, they should be separated by underscores. Do not include "test" or "kunit" directly in the subsystem name unless we are actually testing other tests or the kunit framework itself. For example, subsystems could be called:

  • ext4

    Matches the module and filesystem name.

  • apparmor

    Matches the module name and LSM name.

  • kasan

    Common name for the tool, prominent part of the path mm/kasan

  • snd_hda_codec_hdmi

    Has several components (snd, hda, codec, hdmi) separated by underscores. Matches the module name.

Avoid names as shown in examples below:

  • linear-ranges

    Names should use underscores, not dashes, to separate words. Prefer linear_ranges.

  • qos-kunit-test

    This name should use underscores, and not have "kunit-test" as a suffix. qos is also ambiguous as a subsystem name, because several parts of the kernel have a qos subsystem. power_qos would be a better name.

  • pc_parallel_port

    The corresponding module name is parport_pc, so this subsystem should also be named parport_pc.

Note

The KUnit API and tools do not explicitly know about subsystems. They are a way of categorizing test suites and naming modules which provides a simple, consistent way for humans to find and run tests. This may change in the future.

Suites #

KUnit tests are grouped into test suites, which cover a specific area of functionality being tested. Test suites can have shared initialization and shutdown code which is run for all tests in the suite. Not all subsystems need to be split into multiple test suites (for example, simple drivers).

Test suites are named after the subsystem they are part of. If a subsystem contains several suites, the specific area under test should be appended to the subsystem name, separated by an underscore.

In the event that there are multiple types of test using KUnit within a subsystem (for example, both unit tests and integration tests), they should be put into separate suites, with the type of test as the last element in the suite name. Unless these tests are actually present, avoid using _test, _unittest or similar in the suite name.

The full test suite name (including the subsystem name) should be specified as the .name member of the kunit_suite struct, and forms the base for the module name. For example, test suites could include:

  • ext4_inode

    Part of the ext4 subsystem, testing the inode area.

  • kunit_try_catch

    Part of the kunit implementation itself, testing the try_catch area.

  • apparmor_property_entry

    Part of the apparmor subsystem, testing the property_entry area.

  • kasan

    The kasan subsystem has only one suite, so the suite name is the same as the subsystem name.

Avoid names, for example:

  • ext4_ext4_inode

    There is no reason to state the subsystem twice.

  • property_entry

    The suite name is ambiguous without the subsystem name.

  • kasan_integration_test

    Because there is only one suite in the kasan subsystem, the suite should just be called as kasan. Do not redundantly add integration_test. It should be a separate test suite. For example, if the unit tests are added, then that suite could be named as kasan_unittest or similar.

Test Cases #

Individual tests consist of a single function which tests a constrained codepath, property, or function. In the test output, an individual test's results will show up as subtests of the suite's results.

Tests should be named after what they are testing. This is often the name of the function being tested, with a description of the input or codepath being tested. As tests are C functions, they should be named and written in accordance with the kernel coding style.

Note

As tests are themselves functions, their names cannot conflict with other C identifiers in the kernel. This may require some creative naming. It is a good idea to make your test functions static to avoid polluting the global namespace.

Example test names include:

  • unpack_u32_with_null_name

    Tests the unpack_u32 function when a NULL name is passed in.

  • test_list_splice

    Tests the list_splice macro. It has the prefix test_ to avoid a name conflict with the macro itself.

Should it be necessary to refer to a test outside the context of its test suite, the fully-qualified name of a test should be the suite name followed by the test name, separated by a colon (i.e. suite:test).

Test Kconfig Entries #

Every test suite should be tied to a Kconfig entry.

This Kconfig entry must:

  • be named CONFIG_<name>_KUNIT_TEST: where <name> is the name of the test suite.

  • be listed either alongside the config entries for the driver/subsystem being tested, or be under [Kernel Hacking]->[Kernel Testing and Coverage]

  • depend on CONFIG_KUNIT.

  • be visible only if CONFIG_KUNIT_ALL_TESTS is not enabled.

  • have a default value of CONFIG_KUNIT_ALL_TESTS.

  • have a brief description of KUnit in the help text.

If we are not able to meet above conditions (for example, the test is unable to be built as a module), Kconfig entries for tests should be tristate.

For example, a Kconfig entry might look like:

config FOO_KUNIT_TEST
        tristate "KUnit test for foo" if !KUNIT_ALL_TESTS
        depends on KUNIT
        default KUNIT_ALL_TESTS
        help
          This builds unit tests for foo.

          For more information on KUnit and unit tests in general,
          please refer to the KUnit documentation in Documentation/dev-tools/kunit/.

          If unsure, say N.

Test File and Module Names #

KUnit tests are often compiled as a separate module. To avoid conflicting with regular modules, KUnit modules should be named after the test suite, followed by _kunit (e.g. if "foobar" is the core module, then "foobar_kunit" is the KUnit test module).

Test source files, whether compiled as a separate module or an #include in another source file, are best kept in a tests/ subdirectory to not conflict with other source files (e.g. for tab-completion).

Note that the _test suffix has also been used in some existing tests. The _kunit suffix is preferred, as it makes the distinction between KUnit and non-KUnit tests clearer.

So for the common case, name the file containing the test suite tests/<suite>_kunit.c. The tests directory should be placed at the same level as the code under test. For example, tests for lib/string.c live in lib/tests/string_kunit.c.

If the suite name contains some or all of the name of the test's parent directory, it may make sense to modify the source filename to reduce redundancy. For example, a foo_firmware suite could be in the foo/tests/firmware_kunit.c file.

Writing Tests

Peios Kernel / Kernel development / Development tools / kunit

Writing Tests #

Test Cases #

The fundamental unit in KUnit is the test case. A test case is a function with the signature void (*)(struct kunit *test). It calls the function under test and then sets expectations for what should happen. For example:

void example_test_success(struct kunit *test)
{
}

void example_test_failure(struct kunit *test)
{
        KUNIT_FAIL(test, "This test never passes.");
}

In the above example, example_test_success always passes because it does nothing; no expectations are set, and therefore all expectations pass. On the other hand example_test_failure always fails because it calls KUNIT_FAIL, which is a special expectation that logs a message and causes the test case to fail.

Expectations #

An expectation specifies that we expect a piece of code to do something in a test. An expectation is called like a function. A test is made by setting expectations about the behavior of a piece of code under test. When one or more expectations fail, the test case fails and information about the failure is logged. For example:

void add_test_basic(struct kunit *test)
{
        KUNIT_EXPECT_EQ(test, 1, add(1, 0));
        KUNIT_EXPECT_EQ(test, 2, add(1, 1));
}

In the above example, add_test_basic makes a number of assertions about the behavior of a function called add. The first parameter is always of type struct kunit *, which contains information about the current test context. The second parameter, in this case, is what the value is expected to be. The last value is what the value actually is. If add passes all of these expectations, the test case, add_test_basic will pass; if any one of these expectations fails, the test case will fail.

A test case fails when any expectation is violated; however, the test will continue to run, and try other expectations until the test case ends or is otherwise terminated. This is as opposed to assertions which are discussed later.

To learn about more KUnit expectations, see Documentation/dev-tools/kunit/api/test.rst.

Note

A single test case should be short, easy to understand, and focused on a single behavior.

For example, if we want to rigorously test the add function above, create additional tests cases which would test each property that an add function should have as shown below:

void add_test_basic(struct kunit *test)
{
        KUNIT_EXPECT_EQ(test, 1, add(1, 0));
        KUNIT_EXPECT_EQ(test, 2, add(1, 1));
}

void add_test_negative(struct kunit *test)
{
        KUNIT_EXPECT_EQ(test, 0, add(-1, 1));
}

void add_test_max(struct kunit *test)
{
        KUNIT_EXPECT_EQ(test, INT_MAX, add(0, INT_MAX));
        KUNIT_EXPECT_EQ(test, -1, add(INT_MAX, INT_MIN));
}

void add_test_overflow(struct kunit *test)
{
        KUNIT_EXPECT_EQ(test, INT_MIN, add(INT_MAX, 1));
}

Assertions #

An assertion is like an expectation, except that the assertion immediately terminates the test case if the condition is not satisfied. For example:

static void test_sort(struct kunit *test)
{
        int *a, i, r = 1;
        a = kunit_kmalloc_array(test, TEST_LEN, sizeof(*a), GFP_KERNEL);
        KUNIT_ASSERT_NOT_ERR_OR_NULL(test, a);
        for (i = 0; i < TEST_LEN; i++) {
                r = (r * 725861) % 6599;
                a[i] = r;
        }
        sort(a, TEST_LEN, sizeof(*a), cmpint, NULL);
        for (i = 0; i < TEST_LEN-1; i++)
                KUNIT_EXPECT_LE(test, a[i], a[i + 1]);
}

In this example, we need to be able to allocate an array to test the sort() function. So we use KUNIT_ASSERT_NOT_ERR_OR_NULL() to abort the test if there's an allocation error.

Note

In other test frameworks, ASSERT macros are often implemented by calling return so they only work from the test function. In KUnit, we stop the current kthread on failure, so you can call them from anywhere.

Note

Warning: There is an exception to the above rule. You shouldn't use assertions in the suite's exit() function, or in the free function for a resource. These run when a test is shutting down, and an assertion here prevents further cleanup code from running, potentially leading to a memory leak.

Customizing error messages #

Each of the KUNIT_EXPECT and KUNIT_ASSERT macros have a _MSG variant. These take a format string and arguments to provide additional context to the automatically generated error messages.

char some_str[41];
generate_sha1_hex_string(some_str);

/* Before. Not easy to tell why the test failed. */
KUNIT_EXPECT_EQ(test, strlen(some_str), 40);

/* After. Now we see the offending string. */
KUNIT_EXPECT_EQ_MSG(test, strlen(some_str), 40, "some_str='%s'", some_str);

Alternatively, one can take full control over the error message by using KUNIT_FAIL(), e.g.

/* Before */
KUNIT_EXPECT_EQ(test, some_setup_function(), 0);

/* After: full control over the failure message. */
if (some_setup_function())
        KUNIT_FAIL(test, "Failed to setup thing for testing");

Test Suites #

We need many test cases covering all the unit's behaviors. It is common to have many similar tests. In order to reduce duplication in these closely related tests, most unit testing frameworks (including KUnit) provide the concept of a test suite. A test suite is a collection of test cases for a unit of code with optional setup and teardown functions that run before/after the whole suite and/or every test case.

Note

A test case will only run if it is associated with a test suite.

For example:

static struct kunit_case example_test_cases[] = {
        KUNIT_CASE(example_test_foo),
        KUNIT_CASE(example_test_bar),
        KUNIT_CASE(example_test_baz),
        {}
};

static struct kunit_suite example_test_suite = {
        .name = "example",
        .init = example_test_init,
        .exit = example_test_exit,
        .suite_init = example_suite_init,
        .suite_exit = example_suite_exit,
        .test_cases = example_test_cases,
};
kunit_test_suite(example_test_suite);

In the above example, the test suite example_test_suite would first run example_suite_init, then run the test cases example_test_foo, example_test_bar, and example_test_baz. Each would have example_test_init called immediately before it and example_test_exit called immediately after it. Finally, example_suite_exit would be called after everything else. kunit_test_suite(example_test_suite) registers the test suite with the KUnit test framework.

Note

The exit and suite_exit functions will run even if init or suite_init fail. Make sure that they can handle any inconsistent state which may result from init or suite_init encountering errors or exiting early.

kunit_test_suite(...) is a macro which tells the linker to put the specified test suite in a special linker section so that it can be run by KUnit either after late_init, or when the test module is loaded (if the test was built as a module).

For more information, see Documentation/dev-tools/kunit/api/test.rst.

Writing Tests For Other Architectures #

It is better to write tests that run on UML to tests that only run under a particular architecture. It is better to write tests that run under QEMU or another easy to obtain (and monetarily free) software environment to a specific piece of hardware.

Nevertheless, there are still valid reasons to write a test that is architecture or hardware specific. For example, we might want to test code that really belongs in arch/some-arch/*. Even so, try to write the test so that it does not depend on physical hardware. Some of our test cases may not need hardware, only few tests actually require the hardware to test it. When hardware is not available, instead of disabling tests, we can skip them.

Now that we have narrowed down exactly what bits are hardware specific, the actual procedure for writing and running the tests is same as writing normal KUnit tests.

Important

We may have to reset hardware state. If this is not possible, we may only be able to run one test case per invocation.

Common Patterns #

Isolating Behavior #

Unit testing limits the amount of code under test to a single unit. It controls what code gets run when the unit under test calls a function. Where a function is exposed as part of an API such that the definition of that function can be changed without affecting the rest of the code base. In the kernel, this comes from two constructs: classes, which are structs that contain function pointers provided by the implementer, and architecture-specific functions, which have definitions selected at compile time.

Classes #

Classes are not a construct that is built into the C programming language; however, it is an easily derived concept. Accordingly, in most cases, every project that does not use a standardized object oriented library (like GNOME's GObject) has their own slightly different way of doing object oriented programming; the Linux kernel is no exception.

The central concept in kernel object oriented programming is the class. In the kernel, a class is a struct that contains function pointers. This creates a contract between implementers and users since it forces them to use the same function signature without having to call the function directly. To be a class, the function pointers must specify that a pointer to the class, known as a class handle, be one of the parameters. Thus the member functions (also known as methods) have access to member variables (also known as fields) allowing the same implementation to have multiple instances.

A class can be overridden by child classes by embedding the parent class in the child class. Then when the child class method is called, the child implementation knows that the pointer passed to it is of a parent contained within the child. Thus, the child can compute the pointer to itself because the pointer to the parent is always a fixed offset from the pointer to the child. This offset is the offset of the parent contained in the child struct. For example:

struct shape {
        int (*area)(struct shape *this);
};

struct rectangle {
        struct shape parent;
        int length;
        int width;
};

int rectangle_area(struct shape *this)
{
        struct rectangle *self = container_of(this, struct rectangle, parent);

        return self->length * self->width;
};

void rectangle_new(struct rectangle *self, int length, int width)
{
        self->parent.area = rectangle_area;
        self->length = length;
        self->width = width;
}

In this example, computing the pointer to the child from the pointer to the parent is done by container_of.

Faking Classes #

In order to unit test a piece of code that calls a method in a class, the behavior of the method must be controllable, otherwise the test ceases to be a unit test and becomes an integration test.

A fake class implements a piece of code that is different than what runs in a production instance, but behaves identical from the standpoint of the callers. This is done to replace a dependency that is hard to deal with, or is slow. For example, implementing a fake EEPROM that stores the "contents" in an internal buffer. Assume we have a class that represents an EEPROM:

struct eeprom {
        ssize_t (*read)(struct eeprom *this, size_t offset, char *buffer, size_t count);
        ssize_t (*write)(struct eeprom *this, size_t offset, const char *buffer, size_t count);
};

And we want to test code that buffers writes to the EEPROM:

struct eeprom_buffer {
        ssize_t (*write)(struct eeprom_buffer *this, const char *buffer, size_t count);
        int flush(struct eeprom_buffer *this);
        size_t flush_count; /* Flushes when buffer exceeds flush_count. */
};

struct eeprom_buffer *new_eeprom_buffer(struct eeprom *eeprom);
void destroy_eeprom_buffer(struct eeprom *eeprom);

We can test this code by faking out the underlying EEPROM:

struct fake_eeprom {
        struct eeprom parent;
        char contents[FAKE_EEPROM_CONTENTS_SIZE];
};

ssize_t fake_eeprom_read(struct eeprom *parent, size_t offset, char *buffer, size_t count)
{
        struct fake_eeprom *this = container_of(parent, struct fake_eeprom, parent);

        count = min(count, FAKE_EEPROM_CONTENTS_SIZE - offset);
        memcpy(buffer, this->contents + offset, count);

        return count;
}

ssize_t fake_eeprom_write(struct eeprom *parent, size_t offset, const char *buffer, size_t count)
{
        struct fake_eeprom *this = container_of(parent, struct fake_eeprom, parent);

        count = min(count, FAKE_EEPROM_CONTENTS_SIZE - offset);
        memcpy(this->contents + offset, buffer, count);

        return count;
}

void fake_eeprom_init(struct fake_eeprom *this)
{
        this->parent.read = fake_eeprom_read;
        this->parent.write = fake_eeprom_write;
        memset(this->contents, 0, FAKE_EEPROM_CONTENTS_SIZE);
}

We can now use it to test struct eeprom_buffer:

struct eeprom_buffer_test {
        struct fake_eeprom *fake_eeprom;
        struct eeprom_buffer *eeprom_buffer;
};

static void eeprom_buffer_test_does_not_write_until_flush(struct kunit *test)
{
        struct eeprom_buffer_test *ctx = test->priv;
        struct eeprom_buffer *eeprom_buffer = ctx->eeprom_buffer;
        struct fake_eeprom *fake_eeprom = ctx->fake_eeprom;
        char buffer[] = {0xff};

        eeprom_buffer->flush_count = SIZE_MAX;

        eeprom_buffer->write(eeprom_buffer, buffer, 1);
        KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0);

        eeprom_buffer->write(eeprom_buffer, buffer, 1);
        KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0);

        eeprom_buffer->flush(eeprom_buffer);
        KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0xff);
        KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0xff);
}

static void eeprom_buffer_test_flushes_after_flush_count_met(struct kunit *test)
{
        struct eeprom_buffer_test *ctx = test->priv;
        struct eeprom_buffer *eeprom_buffer = ctx->eeprom_buffer;
        struct fake_eeprom *fake_eeprom = ctx->fake_eeprom;
        char buffer[] = {0xff};

        eeprom_buffer->flush_count = 2;

        eeprom_buffer->write(eeprom_buffer, buffer, 1);
        KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0);

        eeprom_buffer->write(eeprom_buffer, buffer, 1);
        KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0xff);
        KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0xff);
}

static void eeprom_buffer_test_flushes_increments_of_flush_count(struct kunit *test)
{
        struct eeprom_buffer_test *ctx = test->priv;
        struct eeprom_buffer *eeprom_buffer = ctx->eeprom_buffer;
        struct fake_eeprom *fake_eeprom = ctx->fake_eeprom;
        char buffer[] = {0xff, 0xff};

        eeprom_buffer->flush_count = 2;

        eeprom_buffer->write(eeprom_buffer, buffer, 1);
        KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0);

        eeprom_buffer->write(eeprom_buffer, buffer, 2);
        KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0xff);
        KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0xff);
        /* Should have only flushed the first two bytes. */
        KUNIT_EXPECT_EQ(test, fake_eeprom->contents[2], 0);
}

static int eeprom_buffer_test_init(struct kunit *test)
{
        struct eeprom_buffer_test *ctx;

        ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL);
        KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx);

        ctx->fake_eeprom = kunit_kzalloc(test, sizeof(*ctx->fake_eeprom), GFP_KERNEL);
        KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->fake_eeprom);
        fake_eeprom_init(ctx->fake_eeprom);

        ctx->eeprom_buffer = new_eeprom_buffer(&ctx->fake_eeprom->parent);
        KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->eeprom_buffer);

        test->priv = ctx;

        return 0;
}

static void eeprom_buffer_test_exit(struct kunit *test)
{
        struct eeprom_buffer_test *ctx = test->priv;

        destroy_eeprom_buffer(ctx->eeprom_buffer);
}

Testing Against Multiple Inputs #

Testing just a few inputs is not enough to ensure that the code works correctly, for example: testing a hash function.

We can write a helper macro or function. The function is called for each input. For example, to test sha1sum(1), we can write:

#define TEST_SHA1(in, want) \
        sha1sum(in, out); \
        KUNIT_EXPECT_STREQ_MSG(test, out, want, "sha1sum(%s)", in);

char out[40];
TEST_SHA1("hello world",  "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed");
TEST_SHA1("hello world!", "430ce34d020724ed75a196dfc2ad67c77772d169");

Note the use of the _MSG version of KUNIT_EXPECT_STREQ to print a more detailed error and make the assertions clearer within the helper macros.

The _MSG variants are useful when the same expectation is called multiple times (in a loop or helper function) and thus the line number is not enough to identify what failed, as shown below.

In complicated cases, we recommend using a table-driven test compared to the helper macro variation, for example:

int i;
char out[40];

struct sha1_test_case {
        const char *str;
        const char *sha1;
};

struct sha1_test_case cases[] = {
        {
                .str = "hello world",
                .sha1 = "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed",
        },
        {
                .str = "hello world!",
                .sha1 = "430ce34d020724ed75a196dfc2ad67c77772d169",
        },
};
for (i = 0; i < ARRAY_SIZE(cases); ++i) {
        sha1sum(cases[i].str, out);
        KUNIT_EXPECT_STREQ_MSG(test, out, cases[i].sha1,
                              "sha1sum(%s)", cases[i].str);
}

There is more boilerplate code involved, but it can:

  • be more readable when there are multiple inputs/outputs (due to field names).

    • For example, see fs/ext4/inode-test.c.
  • reduce duplication if test cases are shared across multiple tests.

    • For example: if we want to test sha256sum, we could add a sha256 field and reuse cases.
  • be converted to a "parameterized test".

Parameterized Testing #

To run a test case against multiple inputs, KUnit provides a parameterized testing framework. This feature formalizes and extends the concept of table-driven tests discussed previously.

A KUnit test is determined to be parameterized if a parameter generator function is provided when registering the test case. A test user can either write their own generator function or use one that is provided by KUnit. The generator function is stored in kunit_case->generate_params and can be set using the macros described in the section below.

To establish the terminology, a "parameterized test" is a test which is run multiple times (once per "parameter" or "parameter run"). Each parameter run has both its own independent struct kunit (the "parameter run context") and access to a shared parent struct kunit (the "parameterized test context").

Passing Parameters to a Test #

There are three ways to provide the parameters to a test:

Array Parameter Macros:

KUnit provides special support for the common table-driven testing pattern. By applying either KUNIT_ARRAY_PARAM or KUNIT_ARRAY_PARAM_DESC to the cases array from the previous section, we can create a parameterized test as shown below:

// This is copy-pasted from above.
struct sha1_test_case {
        const char *str;
        const char *sha1;
};
static const struct sha1_test_case cases[] = {
        {
                .str = "hello world",
                .sha1 = "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed",
        },
        {
                .str = "hello world!",
                .sha1 = "430ce34d020724ed75a196dfc2ad67c77772d169",
        },
};

// Creates `sha1_gen_params()` to iterate over `cases` while using
// the struct member `str` for the case description.
KUNIT_ARRAY_PARAM_DESC(sha1, cases, str);

// Looks no different from a normal test.
static void sha1_test(struct kunit *test)
{
        // This function can just contain the body of the for-loop.
        // The former `cases[i]` is accessible under test->param_value.
        char out[40];
        struct sha1_test_case *test_param = (struct sha1_test_case *)(test->param_value);

        sha1sum(test_param->str, out);
        KUNIT_EXPECT_STREQ_MSG(test, out, test_param->sha1,
                              "sha1sum(%s)", test_param->str);
}

// Instead of KUNIT_CASE, we use KUNIT_CASE_PARAM and pass in the
// function declared by KUNIT_ARRAY_PARAM or KUNIT_ARRAY_PARAM_DESC.
static struct kunit_case sha1_test_cases[] = {
        KUNIT_CASE_PARAM(sha1_test, sha1_gen_params),
        {}
};

Custom Parameter Generator Function:

The generator function is responsible for generating parameters one-by-one and has the following signature: const void* (*)(struct kunit *test, const void *prev, char *desc). You can pass the generator function to the KUNIT_CASE_PARAM or KUNIT_CASE_PARAM_WITH_INIT macros.

The function receives the previously generated parameter as the prev argument (which is NULL on the first call) and can also access the parameterized test context passed as the test argument. KUnit calls this function repeatedly until it returns NULL, which signifies that a parameterized test ended.

Below is an example of how it works:

#define MAX_TEST_BUFFER_SIZE 8

// Example generator function. It produces a sequence of buffer sizes that
// are powers of two, starting at 1 (e.g., 1, 2, 4, 8).
static const void *buffer_size_gen_params(struct kunit *test, const void *prev, char *desc)
{
        long prev_buffer_size = (long)prev;
        long next_buffer_size = 1; // Start with an initial size of 1.

        // Stop generating parameters if the limit is reached or exceeded.
        if (prev_buffer_size >= MAX_TEST_BUFFER_SIZE)
                return NULL;

        // For subsequent calls, calculate the next size by doubling the previous one.
        if (prev)
                next_buffer_size = prev_buffer_size << 1;

        return (void *)next_buffer_size;
}

// Simple test to validate that kunit_kzalloc provides zeroed memory.
static void buffer_zero_test(struct kunit *test)
{
        long buffer_size = (long)test->param_value;
        // Use kunit_kzalloc to allocate a zero-initialized buffer. This makes the
        // memory "parameter run managed," meaning it's automatically cleaned up at
        // the end of each parameter run.
        int *buf = kunit_kzalloc(test, buffer_size * sizeof(int), GFP_KERNEL);

        // Ensure the allocation was successful.
        KUNIT_ASSERT_NOT_NULL(test, buf);

        // Loop through the buffer and confirm every element is zero.
        for (int i = 0; i < buffer_size; i++)
                KUNIT_EXPECT_EQ(test, buf[i], 0);
}

static struct kunit_case buffer_test_cases[] = {
        KUNIT_CASE_PARAM(buffer_zero_test, buffer_size_gen_params),
        {}
};

Runtime Parameter Array Registration in the Init Function:

For scenarios where you might need to initialize a parameterized test, you can directly register a parameter array to the parameterized test context.

To do this, you must pass the parameterized test context, the array itself, the array size, and a get_description() function to the kunit_register_params_array() macro. This macro populates struct kunit_params within the parameterized test context, effectively storing a parameter array object. The get_description() function will be used for populating parameter descriptions and has the following signature: void (*)(struct kunit *test, const void *param, char *desc). Note that it also has access to the parameterized test context.

Important

When using this way to register a parameter array, you will need to manually pass kunit_array_gen_params() as the generator function to KUNIT_CASE_PARAM_WITH_INIT. kunit_array_gen_params() is a KUnit helper that will use the registered array to generate the parameters.

If needed, instead of passing the KUnit helper, you can also pass your own custom generator function that utilizes the parameter array. To access the parameter array from within the parameter generator function use test->params_array.params.

The kunit_register_params_array() macro should be called within a param_init() function that initializes the parameterized test and has the following signature int (*)(struct kunit *test). For a detailed explanation of this mechanism please refer to the "Adding Shared Resources" section that is after this one. This method supports registering both dynamically built and static parameter arrays.

The code snippet below shows the example_param_init_dynamic_arr test that utilizes make_fibonacci_params() to create a dynamic array, which is then registered using kunit_register_params_array(). To see the full code please refer to lib/kunit/kunit-example-test.c.

/*
* Example of a parameterized test param_init() function that registers a dynamic
* array of parameters.
*/
static int example_param_init_dynamic_arr(struct kunit *test)
{
        size_t seq_size;
        int *fibonacci_params;

        kunit_info(test, "initializing parameterized test\n");

        seq_size = 6;
        fibonacci_params = make_fibonacci_params(test, seq_size);
        if (!fibonacci_params)
                return -ENOMEM;
        /*
        * Passes the dynamic parameter array information to the parameterized test
        * context struct kunit. The array and its metadata will be stored in
        * test->parent->params_array. The array itself will be located in
        * params_data.params.
        */
        kunit_register_params_array(test, fibonacci_params, seq_size,
                                example_param_dynamic_arr_get_desc);
        return 0;
}

static struct kunit_case example_test_cases[] = {
        /*
         * Note how we pass kunit_array_gen_params() to use the array we
         * registered in example_param_init_dynamic_arr() to generate
         * parameters.
         */
        KUNIT_CASE_PARAM_WITH_INIT(example_params_test_with_init_dynamic_arr,
                                   kunit_array_gen_params,
                                   example_param_init_dynamic_arr,
                                   example_param_exit_dynamic_arr),
        {}
};

Adding Shared Resources #

All parameter runs in this framework hold a reference to the parameterized test context, which can be accessed using the parent struct kunit pointer. The parameterized test context is not used to execute any test logic itself; instead, it serves as a container for shared resources.

It's possible to add resources to share between parameter runs within a parameterized test by using KUNIT_CASE_PARAM_WITH_INIT, to which you pass custom param_init() and param_exit() functions. These functions run once before and once after the parameterized test, respectively.

The param_init() function, with the signature int (*)(struct kunit *test), can be used for adding resources to the resources or priv fields of the parameterized test context, registering the parameter array, and any other initialization logic.

The param_exit() function, with the signature void (*)(struct kunit *test), can be used to release any resources that were not parameterized test managed (i.e. not automatically cleaned up after the parameterized test ends) and for any other exit logic.

Both param_init() and param_exit() are passed the parameterized test context behind the scenes. However, the test case function receives the parameter run context. Therefore, to manage and access shared resources from within a test case function, you must use test->parent.

For instance, finding a shared resource allocated by the Resource API requires passing test->parent to kunit_find_resource(). This principle extends to all other APIs that might be used in the test case function, including kunit_kzalloc(), kunit_kmalloc_array(), and others (see Documentation/dev-tools/kunit/api/test.rst and the Documentation/dev-tools/kunit/api/resource.rst).

Note

The suite->init() function, which executes before each parameter run, receives the parameter run context. Therefore, any resources set up in suite->init() are cleaned up after each parameter run.

The code below shows how you can add the shared resources. Note that this code utilizes the Resource API, which you can read more about here: Documentation/dev-tools/kunit/api/resource.rst. To see the full version of this code please refer to lib/kunit/kunit-example-test.c.

static int example_resource_init(struct kunit_resource *res, void *context)
{
        ... /* Code that allocates memory and stores context in res->data. */
}

/* This function deallocates memory for the kunit_resource->data field. */
static void example_resource_free(struct kunit_resource *res)
{
        kfree(res->data);
}

/* This match function locates a test resource based on defined criteria. */
static bool example_resource_alloc_match(struct kunit *test, struct kunit_resource *res,
                                         void *match_data)
{
        return res->data && res->free == example_resource_free;
}

/* Function to initialize the parameterized test. */
static int example_param_init(struct kunit *test)
{
        int ctx = 3; /* Data to be stored. */
        void *data = kunit_alloc_resource(test, example_resource_init,
                                          example_resource_free,
                                          GFP_KERNEL, &ctx);
        if (!data)
                return -ENOMEM;
        kunit_register_params_array(test, example_params_array,
                                    ARRAY_SIZE(example_params_array));
        return 0;
}

/* Example test that uses shared resources in test->resources. */
static void example_params_test_with_init(struct kunit *test)
{
        int threshold;
        const struct example_param *param = test->param_value;
        /*  Here we pass test->parent to access the parameterized test context. */
        struct kunit_resource *res = kunit_find_resource(test->parent,
                                                         example_resource_alloc_match,
                                                         NULL);

        threshold = *((int *)res->data);
        KUNIT_ASSERT_LE(test, param->value, threshold);
        kunit_put_resource(res);
}

static struct kunit_case example_test_cases[] = {
        KUNIT_CASE_PARAM_WITH_INIT(example_params_test_with_init, kunit_array_gen_params,
                                   example_param_init, NULL),
        {}
};

As an alternative to using the KUnit Resource API for sharing resources, you can place them in test->parent->priv. This serves as a more lightweight method for resource storage, best for scenarios where complex resource management is not required.

As stated previously param_init() and param_exit() get the parameterized test context. So, you can directly use test->priv within param_init/exit to manage shared resources. However, from within the test case function, you must navigate up to the parent struct kunit i.e. the parameterized test context. Therefore, you need to use test->parent->priv to access those same resources.

The resources placed in test->parent->priv will need to be allocated in memory to persist across the parameter runs. If memory is allocated using the KUnit memory allocation APIs (described more in the "Allocating Memory" section below), you won't need to worry about deallocation. The APIs will make the memory parameterized test 'managed', ensuring that it will automatically get cleaned up after the parameterized test concludes.

The code below demonstrates example usage of the priv field for shared resources:

static const struct example_param {
        int value;
} example_params_array[] = {
        { .value = 3, },
        { .value = 2, },
        { .value = 1, },
        { .value = 0, },
};

/* Initialize the parameterized test context. */
static int example_param_init_priv(struct kunit *test)
{
        int ctx = 3; /* Data to be stored. */
        int arr_size = ARRAY_SIZE(example_params_array);

        /*
         * Allocate memory using kunit_kzalloc(). Since the `param_init`
         * function receives the parameterized test context, this memory
         * allocation will be scoped to the lifetime of the parameterized test.
         */
        test->priv = kunit_kzalloc(test, sizeof(int), GFP_KERNEL);

        /* Assign the context value to test->priv.*/
        *((int *)test->priv) = ctx;

        /* Register the parameter array. */
        kunit_register_params_array(test, example_params_array, arr_size, NULL);
        return 0;
}

static void example_params_test_with_init_priv(struct kunit *test)
{
        int threshold;
        const struct example_param *param = test->param_value;

        /* By design, test->parent will not be NULL. */
        KUNIT_ASSERT_NOT_NULL(test, test->parent);

        /* Here we use test->parent->priv to access the shared resource. */
        threshold = *(int *)test->parent->priv;

        KUNIT_ASSERT_LE(test, param->value, threshold);
}

static struct kunit_case example_tests[] = {
        KUNIT_CASE_PARAM_WITH_INIT(example_params_test_with_init_priv,
                                   kunit_array_gen_params,
                                   example_param_init_priv, NULL),
        {}
};

Allocating Memory #

Where you might use kzalloc, you can instead use kunit_kzalloc as KUnit will then ensure that the memory is freed once the test completes.

This is useful because it lets us use the KUNIT_ASSERT_EQ macros to exit early from a test without having to worry about remembering to call kfree. For example:

void example_test_allocation(struct kunit *test)
{
        char *buffer = kunit_kzalloc(test, 16, GFP_KERNEL);
        /* Ensure allocation succeeded. */
        KUNIT_ASSERT_NOT_ERR_OR_NULL(test, buffer);

        KUNIT_ASSERT_STREQ(test, buffer, "");
}

Registering Cleanup Actions #

If you need to perform some cleanup beyond simple use of kunit_kzalloc, you can register a custom "deferred action", which is a cleanup function run when the test exits (whether cleanly, or via a failed assertion).

Actions are simple functions with no return value, and a single void* context argument, and fulfill the same role as "cleanup" functions in Python and Go tests, "defer" statements in languages which support them, and (in some cases) destructors in RAII languages.

These are very useful for unregistering things from global lists, closing files or other resources, or freeing resources.

For example:

static void cleanup_device(void *ctx)
{
        struct device *dev = (struct device *)ctx;

        device_unregister(dev);
}

void example_device_test(struct kunit *test)
{
        struct my_device dev;

        device_register(&dev);

        kunit_add_action(test, &cleanup_device, &dev);
}

Note that, for functions like device_unregister which only accept a single pointer-sized argument, it's possible to automatically generate a wrapper with the KUNIT_DEFINE_ACTION_WRAPPER() macro, for example:

KUNIT_DEFINE_ACTION_WRAPPER(device_unregister, device_unregister_wrapper, struct device *);
kunit_add_action(test, &device_unregister_wrapper, &dev);

You should do this in preference to manually casting to the kunit_action_t type, as casting function pointers will break Control Flow Integrity (CFI).

kunit_add_action can fail if, for example, the system is out of memory. You can use kunit_add_action_or_reset instead which runs the action immediately if it cannot be deferred.

If you need more control over when the cleanup function is called, you can trigger it early using kunit_release_action, or cancel it entirely with kunit_remove_action.

Testing Static Functions #

If you want to test static functions without exposing those functions outside of testing, one option is conditionally export the symbol. When KUnit is enabled, the symbol is exposed but remains static otherwise. To use this method, follow the template below.

/* In the file containing functions to test "my_file.c" */

#include <kunit/visibility.h>
#include <my_file.h>
...
VISIBLE_IF_KUNIT int do_interesting_thing()
{
...
}
EXPORT_SYMBOL_IF_KUNIT(do_interesting_thing);

/* In the header file "my_file.h" */

#if IS_ENABLED(CONFIG_KUNIT)
        int do_interesting_thing(void);
#endif

/* In the KUnit test file "my_file_test.c" */

#include <kunit/visibility.h>
#include <my_file.h>
...
MODULE_IMPORT_NS("EXPORTED_FOR_KUNIT_TESTING");
...
// Use do_interesting_thing() in tests

For a full example, see this patch where a test is modified to conditionally expose static functions for testing using the macros above.

As an alternative to the method above, you could conditionally #include the test file at the end of your .c file. This is not recommended but works if needed. For example:

/* In "my_file.c" */

static int do_interesting_thing();

#ifdef CONFIG_MY_KUNIT_TEST
#include "my_kunit_test.c"
#endif

Injecting Test-Only Code #

Similar to as shown above, we can add test-specific logic. For example:

/* In my_file.h */

#ifdef CONFIG_MY_KUNIT_TEST
/* Defined in my_kunit_test.c */
void test_only_hook(void);
#else
void test_only_hook(void) { }
#endif

This test-only code can be made more useful by accessing the current kunit_test as shown in next section: Accessing The Current Test.

Accessing The Current Test #

In some cases, we need to call test-only code from outside the test file. This is helpful, for example, when providing a fake implementation of a function, or to fail any current test from within an error handler. We can do this via the kunit_test field in task_struct, which we can access using the kunit_get_current_test() function in kunit/test-bug.h.

kunit_get_current_test() is safe to call even if KUnit is not enabled. If KUnit is not enabled, or if no test is running in the current task, it will return NULL. This compiles down to either a no-op or a static key check, so will have a negligible performance impact when no test is running.

The example below uses this to implement a "mock" implementation of a function, foo:

#include <kunit/test-bug.h> /* for kunit_get_current_test */

struct test_data {
        int foo_result;
        int want_foo_called_with;
};

static int fake_foo(int arg)
{
        struct kunit *test = kunit_get_current_test();
        struct test_data *test_data = test->priv;

        KUNIT_EXPECT_EQ(test, test_data->want_foo_called_with, arg);
        return test_data->foo_result;
}

static void example_simple_test(struct kunit *test)
{
        /* Assume priv (private, a member used to pass test data from
         * the init function) is allocated in the suite's .init */
        struct test_data *test_data = test->priv;

        test_data->foo_result = 42;
        test_data->want_foo_called_with = 1;

        /* In a real test, we'd probably pass a pointer to fake_foo somewhere
         * like an ops struct, etc. instead of calling it directly. */
        KUNIT_EXPECT_EQ(test, fake_foo(1), 42);
}

In this example, we are using the priv member of struct kunit as a way of passing data to the test from the init function. In general priv is pointer that can be used for any user data. This is preferred over static variables, as it avoids concurrency issues.

Had we wanted something more flexible, we could have used a named kunit_resource. Each test can have multiple resources which have string names providing the same flexibility as a priv member, but also, for example, allowing helper functions to create resources without conflicting with each other. It is also possible to define a clean up function for each resource, making it easy to avoid resource leaks. For more information, see Documentation/dev-tools/kunit/api/resource.rst.

Failing The Current Test #

If we want to fail the current test, we can use kunit_fail_current_test(fmt, args...) which is defined in <kunit/test-bug.h> and does not require pulling in <kunit/test.h>. For example, we have an option to enable some extra debug checks on some data structures as shown below:

#include <kunit/test-bug.h>

#ifdef CONFIG_EXTRA_DEBUG_CHECKS
static void validate_my_data(struct data *data)
{
        if (is_valid(data))
                return;

        kunit_fail_current_test("data %p is invalid", data);

        /* Normal, non-KUnit, error reporting code here. */
}
#else
static void my_debug_function(void) { }
#endif

kunit_fail_current_test() is safe to call even if KUnit is not enabled. If KUnit is not enabled, or if no test is running in the current task, it will do nothing. This compiles down to either a no-op or a static key check, so will have a negligible performance impact when no test is running.

Managing Fake Devices and Drivers #

When testing drivers or code which interacts with drivers, many functions will require a struct device or struct device_driver. In many cases, setting up a real device is not required to test any given function, so a fake device can be used instead.

KUnit provides helper functions to create and manage these fake devices, which are internally of type struct kunit_device, and are attached to a special kunit_bus. These devices support managed device resources (devres), as described in Documentation/driver-api/driver-model/devres.rst

To create a KUnit-managed struct device_driver, use kunit_driver_create(), which will create a driver with the given name, on the kunit_bus. This driver will automatically be destroyed when the corresponding test finishes, but can also be manually destroyed with driver_unregister().

To create a fake device, use the kunit_device_register(), which will create and register a device, using a new KUnit-managed driver created with kunit_driver_create(). To provide a specific, non-KUnit-managed driver, use kunit_device_register_with_driver() instead. Like with managed drivers, KUnit-managed fake devices are automatically cleaned up when the test finishes, but can be manually cleaned up early with kunit_device_unregister().

The KUnit devices should be used in preference to root_device_register(), and instead of platform_device_register() in cases where the device is not otherwise a platform device.

For example:

#include <kunit/device.h>

static void test_my_device(struct kunit *test)
{
        struct device *fake_device;
        const char *dev_managed_string;

        // Create a fake device.
        fake_device = kunit_device_register(test, "my_device");
        KUNIT_ASSERT_NOT_ERR_OR_NULL(test, fake_device)

        // Pass it to functions which need a device.
        dev_managed_string = devm_kstrdup(fake_device, "Hello, World!");

        // Everything is cleaned up automatically when the test ends.
}

API Reference

Peios Kernel / Kernel development / Development tools / kunit / api

  • Test API
  • Resource API
  • Function Redirection API
  • Clk API
  • Device Tree (OF) API
  • Platform Device API

This page documents the KUnit kernel testing API. It is divided into the following sections:

Core KUnit API #

Documentation/dev-tools/kunit/api/test.rst

  • Documents all of the standard testing API

Documentation/dev-tools/kunit/api/resource.rst

  • Documents the KUnit resource API

Documentation/dev-tools/kunit/api/functionredirection.rst

  • Documents the KUnit Function Redirection API

Driver KUnit API #

Documentation/dev-tools/kunit/api/clk.rst

  • Documents the KUnit clk API

Documentation/dev-tools/kunit/api/of.rst

  • Documents the KUnit device tree (OF) API

Documentation/dev-tools/kunit/api/platformdevice.rst

  • Documents the KUnit platform device API

Clk API

Peios Kernel / Kernel development / Development tools / kunit / api

The KUnit clk API is used to test clk providers and clk consumers.

clk_prepare_enable_kunit() #

int clk_prepare_enable_kunit(struct kunit *test, struct clk *clk)

Test managed clk_prepare_enable()

Parameters

  • struct kunit *test: The test context
  • struct clk *clk: clk to prepare and enable

Return

0 on success, or negative errno on failure.

clk_get_kunit() #

struct clk * clk_get_kunit(struct kunit *test, struct device *dev, const char *con_id)

Test managed clk_get()

Parameters

  • struct kunit *test: The test context
  • struct device *dev: device for clock "consumer"
  • const char *con_id: clock consumer ID

Description

Just like clk_get(), except the clk is managed by the test case and is automatically put with clk_put() after the test case concludes.

Return

new clk consumer or ERR_PTR on failure.

of_clk_get_kunit() #

struct clk * of_clk_get_kunit(struct kunit *test, struct device_node *np, int index)

Test managed of_clk_get()

Parameters

  • struct kunit *test: The test context
  • struct device_node *np: device_node for clock "consumer"
  • int index: index in 'clocks' property of np

Description

Just like of_clk_get(), except the clk is managed by the test case and is automatically put with clk_put() after the test case concludes.

Return

new clk consumer or ERR_PTR on failure.

clk_hw_get_clk_kunit() #

struct clk * clk_hw_get_clk_kunit(struct kunit *test, struct clk_hw *hw, const char *con_id)

Test managed clk_hw_get_clk()

Parameters

  • struct kunit *test: The test context
  • struct clk_hw *hw: clk_hw associated with the clk being consumed
  • const char *con_id: connection ID string on device

Description

Just like clk_hw_get_clk(), except the clk is managed by the test case and is automatically put with clk_put() after the test case concludes.

Return

new clk consumer or ERR_PTR on failure.

clk_hw_get_clk_prepared_enabled_kunit() #

struct clk * clk_hw_get_clk_prepared_enabled_kunit(struct kunit *test, struct clk_hw *hw, const char *con_id)

Test managed clk_hw_get_clk() + clk_prepare_enable()

Parameters

  • struct kunit *test: The test context
  • struct clk_hw *hw: clk_hw associated with the clk being consumed
  • const char *con_id: connection ID string on device

Description

Just like

struct clk *clk = clk_hw_get_clk(...);
clk_prepare_enable(clk);

except the clk is managed by the test case and is automatically disabled and unprepared with clk_disable_unprepare() and put with clk_put() after the test case concludes.

Return

new clk consumer that is prepared and enabled or ERR_PTR on failure.

clk_hw_register_kunit() #

int clk_hw_register_kunit(struct kunit *test, struct device *dev, struct clk_hw *hw)

Test managed clk_hw_register()

Parameters

  • struct kunit *test: The test context
  • struct device *dev: device that is registering this clock
  • struct clk_hw *hw: link to hardware-specific clock data

Description

Just like clk_hw_register(), except the clk registration is managed by the test case and is automatically unregistered after the test case concludes.

Return

0 on success or a negative errno value on failure.

of_clk_hw_register_kunit() #

int of_clk_hw_register_kunit(struct kunit *test, struct device_node *node, struct clk_hw *hw)

Test managed of_clk_hw_register()

Parameters

  • struct kunit *test: The test context
  • struct device_node *node: device_node of device that is registering this clock
  • struct clk_hw *hw: link to hardware-specific clock data

Description

Just like of_clk_hw_register(), except the clk registration is managed by the test case and is automatically unregistered after the test case concludes.

Return

0 on success or a negative errno value on failure.

of_clk_add_hw_provider_kunit() #

int of_clk_add_hw_provider_kunit(struct kunit *test, struct device_node *np, struct clk_hw *(*get)(struct of_phandle_args *clkspec, void *data), void *data)

Test managed of_clk_add_hw_provider()

Parameters

  • struct kunit *test: The test context
  • struct device_node *np: Device node pointer associated with clock provider
  • struct clk_hw *(*get)(struct of_phandle_args *clkspec, void *data): Callback for decoding clk_hw
  • void *data: Context pointer for get callback.

Description

Just like of_clk_add_hw_provider(), except the clk_hw provider is managed by the test case and is automatically unregistered after the test case concludes.

Return

0 on success or a negative errno value on failure.

Function Redirection API

Peios Kernel / Kernel development / Development tools / kunit / api

Overview #

When writing unit tests, it's important to be able to isolate the code being tested from other parts of the kernel. This ensures the reliability of the test (it won't be affected by external factors), reduces dependencies on specific hardware or config options (making the test easier to run), and protects the stability of the rest of the system (making it less likely for test-specific state to interfere with the rest of the system).

While for some code (typically generic data structures, helpers, and other "pure functions") this is trivial, for others (like device drivers, filesystems, core subsystems) the code is heavily coupled with other parts of the kernel.

This coupling is often due to global state in some way: be it a global list of devices, the filesystem, or some hardware state. Tests need to either carefully manage, isolate, and restore state, or they can avoid it altogether by replacing access to and mutation of this state with a "fake" or "mock" variant.

By refactoring access to such state, such as by introducing a layer of indirection which can use or emulate a separate set of test state. However, such refactoring comes with its own costs (and undertaking significant refactoring before being able to write tests is suboptimal).

A simpler way to intercept and replace some of the function calls is to use function redirection via static stubs.

Static Stubs #

Static stubs are a way of redirecting calls to one function (the "real" function) to another function (the "replacement" function).

It works by adding a macro to the "real" function which checks to see if a test is running, and if a replacement function is available. If so, that function is called in place of the original.

Using static stubs is pretty straightforward:

  1. Add the KUNIT_STATIC_STUB_REDIRECT() macro to the start of the "real" function.

    This should be the first statement in the function, after any variable declarations. KUNIT_STATIC_STUB_REDIRECT() takes the name of the function, followed by all of the arguments passed to the real function.

    For example:

    void send_data_to_hardware(const char *str)
    {
            KUNIT_STATIC_STUB_REDIRECT(send_data_to_hardware, str);
            /* real implementation */
    }
    
  2. Write one or more replacement functions.

    These functions should have the same function signature as the real function. In the event they need to access or modify test-specific state, they can use kunit_get_current_test() to get a struct kunit pointer. This can then be passed to the expectation/assertion macros, or used to look up KUnit resources.

    For example:

    void fake_send_data_to_hardware(const char *str)
    {
            struct kunit *test = kunit_get_current_test();
            KUNIT_EXPECT_STREQ(test, str, "Hello World!");
    }
    
  3. Activate the static stub from your test.

    From within a test, the redirection can be enabled with kunit_activate_static_stub(), which accepts a struct kunit pointer, the real function, and the replacement function. You can call this several times with different replacement functions to swap out implementations of the function.

    In our example, this would be

    kunit_activate_static_stub(test,
                               send_data_to_hardware,
                               fake_send_data_to_hardware);
    
  4. Call (perhaps indirectly) the real function.

    Once the redirection is activated, any call to the real function will call the replacement function instead. Such calls may be buried deep in the implementation of another function, but must occur from the test's kthread.

    For example:

    send_data_to_hardware("Hello World!"); /* Succeeds */
    send_data_to_hardware("Something else"); /* Fails the test. */
    
  5. (Optionally) disable the stub.

    When you no longer need it, disable the redirection (and hence resume the original behaviour of the 'real' function) using kunit_deactivate_static_stub(). Otherwise, it will be automatically disabled when the test exits.

    For example:

    kunit_deactivate_static_stub(test, send_data_to_hardware);
    

It's also possible to use these replacement functions to test to see if a function is called at all, for example:

void send_data_to_hardware(const char *str)
{
        KUNIT_STATIC_STUB_REDIRECT(send_data_to_hardware, str);
        /* real implementation */
}

/* In test file */
int times_called = 0;
void fake_send_data_to_hardware(const char *str)
{
        times_called++;
}
...
/* In the test case, redirect calls for the duration of the test */
kunit_activate_static_stub(test, send_data_to_hardware, fake_send_data_to_hardware);

send_data_to_hardware("hello");
KUNIT_EXPECT_EQ(test, times_called, 1);

/* Can also deactivate the stub early, if wanted */
kunit_deactivate_static_stub(test, send_data_to_hardware);

send_data_to_hardware("hello again");
KUNIT_EXPECT_EQ(test, times_called, 1);

API Reference #

KUNIT_STATIC_STUB_REDIRECT() #

KUNIT_STATIC_STUB_REDIRECT(real_fn_name, args...)

call a replacement 'static stub' if one exists

Parameters

  • real_fn_name: The name of this function (as an identifier, not a string)
  • args...: All of the arguments passed to this function

Description

This is a function prologue which is used to allow calls to the current function to be redirected by a KUnit test. KUnit tests can call kunit_activate_static_stub() to pass a replacement function in. The replacement function will be called by KUNIT_STATIC_STUB_REDIRECT(), which will then return from the function. If the caller is not in a KUnit context, the function will continue execution as normal.

Example

int real_func(int n)
{
        KUNIT_STATIC_STUB_REDIRECT(real_func, n);
        return 0;
}

int replacement_func(int n)
{
        return 42;
}

void example_test(struct kunit *test)
{
        kunit_activate_static_stub(test, real_func, replacement_func);
        KUNIT_EXPECT_EQ(test, real_func(1), 42);
}

kunit_activate_static_stub() #

kunit_activate_static_stub(test, real_fn_addr, replacement_addr)

replace a function using static stubs.

Parameters

  • test: A pointer to the 'struct kunit' test context for the current test.
  • real_fn_addr: The address of the function to replace.
  • replacement_addr: The address of the function to replace it with.

Description

When activated, calls to real_fn_addr from within this test (even if called indirectly) will instead call replacement_addr. The function pointed to by real_fn_addr must begin with the static stub prologue in KUNIT_STATIC_STUB_REDIRECT() for this to work. real_fn_addr and replacement_addr must have the same type.

The redirection can be disabled again with kunit_deactivate_static_stub().

kunit_deactivate_static_stub() #

void kunit_deactivate_static_stub(struct kunit *test, void *real_fn_addr)

disable a function redirection

Parameters

  • struct kunit *test: A pointer to the 'struct kunit' test context for the current test.
  • void *real_fn_addr: The address of the function to no-longer redirect

Description

Deactivates a redirection configured with kunit_activate_static_stub(). After this function returns, calls to real_fn_addr() will execute the original real_fn, not any previously-configured replacement.

Device Tree (OF) API

Peios Kernel / Kernel development / Development tools / kunit / api

The KUnit device tree API is used to test device tree (of_*) dependent code.

__of_overlay_apply_kunit() #

int __of_overlay_apply_kunit(struct kunit *test, u8 *overlay_begin, const u8 *overlay_end)

Test managed of_overlay_fdt_apply() variant

Parameters

  • struct kunit *test: test context
  • u8 *overlay_begin: start address of overlay to apply
  • const u8 *overlay_end: end address of overlay to apply

Description

This is mostly internal API. See of_overlay_apply_kunit() for the wrapper that makes this easier to use.

Similar to of_overlay_fdt_apply(), except the overlay is managed by the test case and is automatically removed with of_overlay_remove() after the test case concludes.

Return

0 on success, negative errno on failure

of_overlay_apply_kunit() #

of_overlay_apply_kunit(test, overlay_name)

Test managed of_overlay_fdt_apply() for built-in overlays

Parameters

  • test: test context
  • overlay_name: name of overlay to apply

Description

This macro is used to apply a device tree overlay built with the cmd_dt_S_dtbo rule in scripts/Makefile.lib that has been compiled into the kernel image or KUnit test module. The overlay is automatically removed when the test is finished.

Unit tests that need device tree nodes should compile an overlay file with overlay_name.dtbo.o in their Makefile along with their unit test and then load the overlay during their test. The overlay_name matches the filename of the overlay without the dtbo filename extension. If CONFIG_OF_OVERLAY is not enabled, the test will be skipped.

In the Makefile

obj-$(CONFIG_OF_OVERLAY_KUNIT_TEST) += overlay_test.o kunit_overlay_test.dtbo.o

In the test

static void of_overlay_kunit_of_overlay_apply(struct kunit *test)
{
        struct device_node *np;

        KUNIT_ASSERT_EQ(test, 0,
                        of_overlay_apply_kunit(test, kunit_overlay_test));

        np = of_find_node_by_name(NULL, "test-kunit");
        KUNIT_EXPECT_NOT_ERR_OR_NULL(test, np);
        of_node_put(np);
}

Return

0 on success, negative errno on failure.

of_root_kunit_skip() #

void of_root_kunit_skip(struct kunit *test)

Skip test if the root node isn't populated

Parameters

  • struct kunit *test: test to skip if the root node isn't populated

of_overlay_fdt_apply_kunit() #

int of_overlay_fdt_apply_kunit(struct kunit *test, void *overlay_fdt, u32 overlay_fdt_size, int *ovcs_id)

Test managed of_overlay_fdt_apply()

Parameters

  • struct kunit *test: test context
  • void *overlay_fdt: device tree overlay to apply
  • u32 overlay_fdt_size: size in bytes of overlay_fdt
  • int *ovcs_id: identifier of overlay, used to remove the overlay

Description

Just like of_overlay_fdt_apply(), except the overlay is managed by the test case and is automatically removed with of_overlay_remove() after the test case concludes.

Return

0 on success, negative errno on failure

of_node_put_kunit() #

void of_node_put_kunit(struct kunit *test, struct device_node *node)

Test managed of_node_put()

Parameters

  • struct kunit *test: test context
  • struct device_node *node: node to pass to of_node_put()

Description

Just like of_node_put(), except the node is managed by the test case and is automatically put with of_node_put() after the test case concludes.

Platform Device API

Peios Kernel / Kernel development / Development tools / kunit / api

The KUnit platform device API is used to test platform devices.

kunit_platform_device_alloc() #

struct platform_device * kunit_platform_device_alloc(struct kunit *test, const char *name, int id)

Allocate a KUnit test managed platform device

Parameters

  • struct kunit *test: test context
  • const char *name: device name of platform device to alloc
  • int id: identifier of platform device to alloc.

Description

Allocate a test managed platform device. The device is put when the test completes.

Return

Allocated platform device on success, NULL on failure.

kunit_platform_device_add() #

int kunit_platform_device_add(struct kunit *test, struct platform_device *pdev)

Register a KUnit test managed platform device

Parameters

  • struct kunit *test: test context
  • struct platform_device *pdev: platform device to add

Description

Register a test managed platform device. The device is unregistered when the test completes.

Return

0 on success, negative errno on failure.

kunit_platform_device_prepare_wait_for_probe() #

int kunit_platform_device_prepare_wait_for_probe(struct kunit *test, struct platform_device *pdev, struct completion *x)

Prepare a completion variable to wait for a platform device to probe

Parameters

  • struct kunit *test: test context
  • struct platform_device *pdev: platform device to prepare to wait for probe of
  • struct completion *x: completion variable completed when dev has probed

Description

Prepare a completion variable x to wait for pdev to probe. Waiting on the completion forces a preemption, allowing the platform driver to probe.

Example

static int kunit_platform_driver_probe(struct platform_device *pdev)
{
        return 0;
}

static void kunit_platform_driver_test(struct kunit *test)
{
        struct platform_device *pdev;
        struct platform_driver *pdrv;
        DECLARE_COMPLETION_ONSTACK(comp);

        pdev = kunit_platform_device_alloc(test, "kunit-platform", -1);
        KUNIT_ASSERT_NOT_ERR_OR_NULL(test, pdev);
        KUNIT_ASSERT_EQ(test, 0, kunit_platform_device_add(test, pdev));

        pdrv = kunit_kzalloc(test, sizeof(*pdrv), GFP_KERNEL);
        KUNIT_ASSERT_NOT_ERR_OR_NULL(test, pdrv);

        pdrv->probe = kunit_platform_driver_probe;
        pdrv->driver.name = "kunit-platform";
        pdrv->driver.owner = THIS_MODULE;

        KUNIT_ASSERT_EQ(test, 0, kunit_platform_device_prepare_wait_for_probe(test, pdev, &comp));
        KUNIT_ASSERT_EQ(test, 0, kunit_platform_driver_register(test, pdrv));

        KUNIT_EXPECT_NE(test, 0, wait_for_completion_timeout(&comp, 3 * HZ));
}

Return

0 on success, negative errno on failure.

kunit_platform_driver_register() #

int kunit_platform_driver_register(struct kunit *test, struct platform_driver *drv)

Register a KUnit test managed platform driver

Parameters

  • struct kunit *test: test context
  • struct platform_driver *drv: platform driver to register

Description

Register a test managed platform driver. This allows callers to embed the drv in a container structure and use container_of() in the probe function to pass information to KUnit tests.

Example

struct kunit_test_context {
        struct platform_driver pdrv;
        const char *data;
};

static inline struct kunit_test_context *
to_test_context(struct platform_device *pdev)
{
        return container_of(to_platform_driver(pdev->dev.driver),
                            struct kunit_test_context,
                            pdrv);
}

static int kunit_platform_driver_probe(struct platform_device *pdev)
{
        struct kunit_test_context *ctx;

        ctx = to_test_context(pdev);
        ctx->data = "test data";

        return 0;
}

static void kunit_platform_driver_test(struct kunit *test)
{
        struct kunit_test_context *ctx;

        ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL);
        KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx);

        ctx->pdrv.probe = kunit_platform_driver_probe;
        ctx->pdrv.driver.name = "kunit-platform";
        ctx->pdrv.driver.owner = THIS_MODULE;

        KUNIT_EXPECT_EQ(test, 0, kunit_platform_driver_register(test, &ctx->pdrv));
        <... wait for driver to probe ...>
        KUNIT_EXPECT_STREQ(test, ctx->data, "test data");
}

Return

0 on success, negative errno on failure.

Resource API

Peios Kernel / Kernel development / Development tools / kunit / api

This file documents the KUnit resource API.

Most users won't need to use this API directly, power users can use it to store state on a per-test basis, register custom cleanup actions, and more.

struct kunit_resource #

represents a test managed resource

Definition

struct kunit_resource {
    void *data;
    const char *name;
    kunit_resource_free_t free;
};

Members

  • data: for the user to store arbitrary data.
  • name: optional name
  • free: a user supplied function to free the resource.

Description

Represents a test managed resource, a resource which will automatically be cleaned up at the end of a test case. This cleanup is performed by the 'free' function. The struct kunit_resource itself is freed automatically with kfree() if it was allocated by KUnit (e.g., by kunit_alloc_resource()), but must be freed by the user otherwise.

Resources are reference counted so if a resource is retrieved via kunit_alloc_and_get_resource() or kunit_find_resource(), we need to call kunit_put_resource() to reduce the resource reference count when finished with it. Note that kunit_alloc_resource() does not require a kunit_resource_put() because it does not retrieve the resource itself.

Example

struct kunit_kmalloc_params {
        size_t size;
        gfp_t gfp;
};

static int kunit_kmalloc_init(struct kunit_resource *res, void *context)
{
        struct kunit_kmalloc_params *params = context;
        res->data = kmalloc(params->size, params->gfp);

        if (!res->data)
                return -ENOMEM;

        return 0;
}

static void kunit_kmalloc_free(struct kunit_resource *res)
{
        kfree(res->data);
}

void *kunit_kmalloc(struct kunit *test, size_t size, gfp_t gfp)
{
        struct kunit_kmalloc_params params;

        params.size = size;
        params.gfp = gfp;

        return kunit_alloc_resource(test, kunit_kmalloc_init,
                kunit_kmalloc_free, gfp, &params);
}

Resources can also be named, with lookup/removal done on a name basis also. kunit_add_named_resource(), kunit_find_named_resource() and kunit_destroy_named_resource(). Resource names must be unique within the test instance.

kunit_get_resource() #

void kunit_get_resource(struct kunit_resource *res)

Hold resource for use. Should not need to be used by most users as we automatically get resources retrieved by kunit_find_resource*().

Parameters

  • struct kunit_resource *res: resource

kunit_put_resource() #

void kunit_put_resource(struct kunit_resource *res)

When caller is done with retrieved resource, kunit_put_resource() should be called to drop reference count. The resource list maintains a reference count on resources, so if no users are utilizing a resource and it is removed from the resource list, it will be freed via the associated free function (if any). Only needs to be used if we alloc_and_get() or find() resource.

Parameters

  • struct kunit_resource *res: resource

__kunit_add_resource() #

int __kunit_add_resource(struct kunit *test, kunit_resource_init_t init, kunit_resource_free_t free, struct kunit_resource *res, void *data)

Internal helper to add a resource.

Parameters

  • struct kunit *test: The test context object.
  • kunit_resource_init_t init: a user-supplied function to initialize the result (if needed). If none is supplied, the resource data value is simply set to data. If an init function is supplied, data is passed to it instead.
  • kunit_resource_free_t free: a user-supplied function to free the resource (if needed).
  • struct kunit_resource *res: The resource.
  • void *data: value to pass to init function or set in resource data field.

Description

res->should_kfree is not initialised.

kunit_add_resource() #

int kunit_add_resource(struct kunit *test, kunit_resource_init_t init, kunit_resource_free_t free, struct kunit_resource *res, void *data)

Add a test managed resource.

Parameters

  • struct kunit *test: The test context object.
  • kunit_resource_init_t init: a user-supplied function to initialize the result (if needed). If none is supplied, the resource data value is simply set to data. If an init function is supplied, data is passed to it instead.
  • kunit_resource_free_t free: a user-supplied function to free the resource (if needed).
  • struct kunit_resource *res: The resource.
  • void *data: value to pass to init function or set in resource data field.

kunit_add_named_resource() #

int kunit_add_named_resource(struct kunit *test, kunit_resource_init_t init, kunit_resource_free_t free, struct kunit_resource *res, const char *name, void *data)

Add a named test managed resource.

Parameters

  • struct kunit *test: The test context object.
  • kunit_resource_init_t init: a user-supplied function to initialize the resource data, if needed.
  • kunit_resource_free_t free: a user-supplied function to free the resource data, if needed.
  • struct kunit_resource *res: The resource.
  • const char *name: name to be set for resource.
  • void *data: value to pass to init function or set in resource data field.

kunit_alloc_and_get_resource() #

struct kunit_resource * kunit_alloc_and_get_resource(struct kunit *test, kunit_resource_init_t init, kunit_resource_free_t free, gfp_t internal_gfp, void *context)

Allocates and returns a test managed resource.

Parameters

  • struct kunit *test: The test context object.
  • kunit_resource_init_t init: a user supplied function to initialize the resource.
  • kunit_resource_free_t free: a user supplied function to free the resource (if needed).
  • gfp_t internal_gfp: gfp to use for internal allocations, if unsure, use GFP_KERNEL
  • void *context: for the user to pass in arbitrary data to the init function.

Description

Allocates a test managed resource, a resource which will automatically be cleaned up at the end of a test case. See struct kunit_resource for an example.

This is effectively identical to kunit_alloc_resource, but returns the struct kunit_resource pointer, not just the 'data' pointer. It therefore also increments the resource's refcount, so kunit_put_resource() should be called when you've finished with it.

Note

KUnit needs to allocate memory for a kunit_resource object. You must specify an internal_gfp that is compatible with the use context of your resource.

kunit_alloc_resource() #

void * kunit_alloc_resource(struct kunit *test, kunit_resource_init_t init, kunit_resource_free_t free, gfp_t internal_gfp, void *context)

Allocates a test managed resource.

Parameters

  • struct kunit *test: The test context object.
  • kunit_resource_init_t init: a user supplied function to initialize the resource.
  • kunit_resource_free_t free: a user supplied function to free the resource (if needed).
  • gfp_t internal_gfp: gfp to use for internal allocations, if unsure, use GFP_KERNEL
  • void *context: for the user to pass in arbitrary data to the init function.

Description

Allocates a test managed resource, a resource which will automatically be cleaned up at the end of a test case. See struct kunit_resource for an example.

Note

KUnit needs to allocate memory for a kunit_resource object. You must specify an internal_gfp that is compatible with the use context of your resource.

kunit_resource_name_match() #

bool kunit_resource_name_match(struct kunit *test, struct kunit_resource *res, void *match_name)

Match a resource with the same name.

Parameters

  • struct kunit *test: Test case to which the resource belongs.
  • struct kunit_resource *res: The resource.
  • void *match_name: The name to match against.

kunit_find_resource() #

struct kunit_resource * kunit_find_resource(struct kunit *test, kunit_resource_match_t match, void *match_data)

Find a resource using match function/data.

Parameters

  • struct kunit *test: Test case to which the resource belongs.
  • kunit_resource_match_t match: match function to be applied to resources/match data.
  • void *match_data: data to be used in matching.

kunit_find_named_resource() #

struct kunit_resource * kunit_find_named_resource(struct kunit *test, const char *name)

Find a resource using match name.

Parameters

  • struct kunit *test: Test case to which the resource belongs.
  • const char *name: match name.

kunit_destroy_resource() #

int kunit_destroy_resource(struct kunit *test, kunit_resource_match_t match, void *match_data)

Find a kunit_resource and destroy it.

Parameters

  • struct kunit *test: Test case to which the resource belongs.
  • kunit_resource_match_t match: Match function. Returns whether a given resource matches match_data.
  • void *match_data: Data passed into match.

Return

0 if kunit_resource is found and freed, -ENOENT if not found.

kunit_remove_resource() #

void kunit_remove_resource(struct kunit *test, struct kunit_resource *res)

remove resource from resource list associated with test.

Parameters

  • struct kunit *test: The test context object.
  • struct kunit_resource *res: The resource to be removed.

Description

Note that the resource will not be immediately freed since it is likely the caller has a reference to it via alloc_and_get() or find(); in this case a final call to kunit_put_resource() is required.

KUNIT_DEFINE_ACTION_WRAPPER() #

KUNIT_DEFINE_ACTION_WRAPPER(wrapper, orig, arg_type)

Wrap a function for use as a deferred action.

Parameters

  • wrapper: The name of the new wrapper function define.
  • orig: The original function to wrap.
  • arg_type: The type of the argument accepted by orig.

Description

Defines a wrapper for a function which accepts a single, pointer-sized argument. This wrapper can then be passed to kunit_add_action() and similar. This should be used in preference to casting a function directly to kunit_action_t, as casting function pointers will break control flow integrity (CFI), leading to crashes.

kunit_add_action() #

int kunit_add_action(struct kunit *test, kunit_action_t *action, void *ctx)

Call a function when the test ends.

Parameters

  • struct kunit *test: Test case to associate the action with.
  • kunit_action_t *action: The function to run on test exit
  • void *ctx: Data passed into func

Description

Defer the execution of a function until the test exits, either normally or due to a failure. ctx is passed as additional context. All functions registered with kunit_add_action() will execute in the opposite order to that they were registered in.

This is useful for cleaning up allocated memory and resources, as these functions are called even if the test aborts early due to, e.g., a failed assertion.

See also: devm_add_action() for the devres equivalent.

Return

0 on success, an error if the action could not be deferred.

kunit_add_action_or_reset() #

int kunit_add_action_or_reset(struct kunit *test, kunit_action_t *action, void *ctx)

Call a function when the test ends.

Parameters

  • struct kunit *test: Test case to associate the action with.
  • kunit_action_t *action: The function to run on test exit
  • void *ctx: Data passed into func

Description

Defer the execution of a function until the test exits, either normally or due to a failure. ctx is passed as additional context. All functions registered with kunit_add_action() will execute in the opposite order to that they were registered in.

This is useful for cleaning up allocated memory and resources, as these functions are called even if the test aborts early due to, e.g., a failed assertion.

If the action cannot be created (e.g., due to the system being out of memory), then action(ctx) will be called immediately, and an error will be returned.

See also: devm_add_action_or_reset() for the devres equivalent.

Return

0 on success, an error if the action could not be deferred.

kunit_remove_action() #

void kunit_remove_action(struct kunit *test, kunit_action_t *action, void *ctx)

Cancel a matching deferred action.

Parameters

  • struct kunit *test: Test case the action is associated with.
  • kunit_action_t *action: The deferred function to cancel.
  • void *ctx: The context passed to the deferred function to trigger.

Description

Prevent an action deferred via kunit_add_action() from executing when the test terminates.

If the function/context pair was deferred multiple times, only the most recent one will be cancelled.

See also: devm_remove_action() for the devres equivalent.

kunit_release_action() #

void kunit_release_action(struct kunit *test, kunit_action_t *action, void *ctx)

Run a matching action call immediately.

Parameters

  • struct kunit *test: Test case the action is associated with.
  • kunit_action_t *action: The deferred function to trigger.
  • void *ctx: The context passed to the deferred function to trigger.

Description

Execute a function deferred via kunit_add_action()) immediately, rather than when the test ends.

If the function/context pair was deferred multiple times, it will only be executed once here. The most recent deferral will no longer execute when the test ends.

kunit_release_action(test, func, ctx); is equivalent to func(ctx); kunit_remove_action(test, func, ctx);

See also: devm_release_action() for the devres equivalent.

Managed Devices #

Functions for using KUnit-managed struct device and struct device_driver. Include kunit/device.h to use these.

kunit_driver_create() #

struct device_driver * kunit_driver_create(struct kunit *test, const char *name)

Create a struct device_driver attached to the kunit_bus

Parameters

  • struct kunit *test: The test context object.
  • const char *name: The name to give the created driver.

Description

Creates a struct device_driver attached to the kunit_bus, with the name name. This driver will automatically be cleaned up on test exit.

Return

a stub struct device_driver, managed by KUnit, with the name name.

kunit_device_register() #

struct device * kunit_device_register(struct kunit *test, const char *name)

Create a struct device for use in KUnit tests

Parameters

  • struct kunit *test: The test context object.
  • const char *name: The name to give the created device.

Description

Creates a struct kunit_device (which is a struct device) with the given name, and a corresponding driver. The device and driver will be cleaned up on test exit, or when kunit_device_unregister is called. See also kunit_device_register_with_driver, if you wish to provide your own struct device_driver.

Return

a pointer to a struct device which will be cleaned up when the test exits, or an error pointer if the device could not be allocated or registered.

kunit_device_register_with_driver() #

struct device * kunit_device_register_with_driver(struct kunit *test, const char *name, const struct device_driver *drv)

Create a struct device for use in KUnit tests

Parameters

  • struct kunit *test: The test context object.
  • const char *name: The name to give the created device.
  • const struct device_driver *drv: The struct device_driver to associate with the device.

Description

Creates a struct kunit_device (which is a struct device) with the given name, and driver. The device will be cleaned up on test exit, or when kunit_device_unregister is called. See also kunit_device_register, if you wish KUnit to create and manage a driver for you.

Return

a pointer to a struct device which will be cleaned up when the test exits, or an error pointer if the device could not be allocated or registered.

kunit_device_unregister() #

void kunit_device_unregister(struct kunit *test, struct device *dev)

Unregister a KUnit-managed device

Parameters

  • struct kunit *test: The test context object which created the device
  • struct device *dev: The device.

Description

Unregisters and destroys a struct device which was created with kunit_device_register or kunit_device_register_with_driver. If KUnit created a driver, cleans it up as well.

Test API

Peios Kernel / Kernel development / Development tools / kunit / api

This file documents all of the standard testing API.

enum kunit_status #

Type of result for a test or test suite

Constants

  • KUNIT_SUCCESS: Denotes the test suite has not failed nor been skipped
  • KUNIT_FAILURE: Denotes the test has failed.
  • KUNIT_SKIPPED: Denotes the test has been skipped.

struct kunit_case #

represents an individual test case.

Definition

struct kunit_case {
    void (*run_case)(struct kunit *test);
    const char *name;
    const void* (*generate_params)(struct kunit *test, const void *prev, char *desc);
    struct kunit_attributes attr;
    int (*param_init)(struct kunit *test);
    void (*param_exit)(struct kunit *test);
};

Members

  • run_case: the function representing the actual test case.
  • name: the name of the test case.
  • generate_params: the generator function for parameterized tests.
  • attr: the attributes associated with the test
  • param_init: The init function to run before a parameterized test.
  • param_exit: The exit function to run after a parameterized test.

Description

A test case is a function with the signature, void (*)(struct kunit *) that makes expectations and assertions (see KUNIT_EXPECT_TRUE() and KUNIT_ASSERT_TRUE()) about code under test. Each test case is associated with a struct kunit_suite and will be run after the suite's init function and followed by the suite's exit function.

A test case should be static and should only be created with the KUNIT_CASE() macro; additionally, every array of test cases should be terminated with an empty test case.

Example

void add_test_basic(struct kunit *test)
{
        KUNIT_EXPECT_EQ(test, 1, add(1, 0));
        KUNIT_EXPECT_EQ(test, 2, add(1, 1));
        KUNIT_EXPECT_EQ(test, 0, add(-1, 1));
        KUNIT_EXPECT_EQ(test, INT_MAX, add(0, INT_MAX));
        KUNIT_EXPECT_EQ(test, -1, add(INT_MAX, INT_MIN));
}

static struct kunit_case example_test_cases[] = {
        KUNIT_CASE(add_test_basic),
        {}
};

KUNIT_CASE() #

KUNIT_CASE(test_name)

A helper for creating a struct kunit_case

Parameters

  • test_name: a reference to a test case function.

Description

Takes a symbol for a function representing a test case and creates a struct kunit_case object from it. See the documentation for struct kunit_case for an example on how to use it.

KUNIT_CASE_ATTR() #

KUNIT_CASE_ATTR(test_name, attributes)

A helper for creating a struct kunit_case with attributes

Parameters

  • test_name: a reference to a test case function.
  • attributes: a reference to a struct kunit_attributes object containing test attributes

KUNIT_CASE_SLOW() #

KUNIT_CASE_SLOW(test_name)

A helper for creating a struct kunit_case with the slow attribute

Parameters

  • test_name: a reference to a test case function.

KUNIT_CASE_PARAM() #

KUNIT_CASE_PARAM(test_name, gen_params)

A helper for creation a parameterized struct kunit_case

Parameters

  • test_name: a reference to a test case function.
  • gen_params: a reference to a parameter generator function.

Description

The generator function:

const void* gen_params(const void *prev, char *desc)

is used to lazily generate a series of arbitrarily typed values that fit into a void*. The argument prev is the previously returned value, which should be used to derive the next value; prev is set to NULL on the initial generator call. When no more values are available, the generator must return NULL. Optionally write a string into desc (size of KUNIT_PARAM_DESC_SIZE) describing the parameter.

KUNIT_CASE_PARAM_ATTR() #

KUNIT_CASE_PARAM_ATTR(test_name, gen_params, attributes)

A helper for creating a parameterized struct kunit_case with attributes

Parameters

  • test_name: a reference to a test case function.
  • gen_params: a reference to a parameter generator function.
  • attributes: a reference to a struct kunit_attributes object containing test attributes

KUNIT_CASE_PARAM_WITH_INIT() #

KUNIT_CASE_PARAM_WITH_INIT(test_name, gen_params, init, exit)

Define a parameterized KUnit test case with custom param_init() and param_exit() functions.

Parameters

  • test_name: The function implementing the test case.
  • gen_params: The function to generate parameters for the test case.
  • init: A reference to the param_init() function to run before a parameterized test.
  • exit: A reference to the param_exit() function to run after a parameterized test.

Description

Provides the option to register param_init() and param_exit() functions. param_init/exit will be passed the parameterized test context and run once before and once after the parameterized test. The init function can be used to add resources to share between parameter runs, pass parameter arrays, and any other setup logic. The exit function can be used to clean up resources that were not managed by the parameterized test, and any other teardown logic.

Note

If you are registering a parameter array in param_init() with kunit_register_param_array() then you need to pass kunit_array_gen_params() to this as the generator function.

struct kunit_suite #

describes a related collection of struct kunit_case

Definition

struct kunit_suite {
    const char name[256];
    int (*suite_init)(struct kunit_suite *suite);
    void (*suite_exit)(struct kunit_suite *suite);
    int (*init)(struct kunit *test);
    void (*exit)(struct kunit *test);
    struct kunit_case *test_cases;
    struct kunit_attributes attr;
};

Members

  • name: the name of the test. Purely informational.
  • suite_init: called once per test suite before the test cases.
  • suite_exit: called once per test suite after all test cases.
  • init: called before every test case.
  • exit: called after every test case.
  • test_cases: a null terminated array of test cases.
  • attr: the attributes associated with the test suite

Description

A kunit_suite is a collection of related struct kunit_case s, such that init is called before every test case and exit is called after every test case, similar to the notion of a test fixture or a test class in other unit testing frameworks like JUnit or Googletest.

Note that exit and suite_exit will run even if init or suite_init fail: make sure they can handle any inconsistent state which may result.

Every struct kunit_case must be associated with a kunit_suite for KUnit to run it.

struct kunit #

represents a running instance of a test.

Definition

struct kunit {
    void *priv;
    struct kunit *parent;
    struct kunit_params params_array;
};

Members

  • priv: for user to store arbitrary data. Commonly used to pass data created in the init function (see struct kunit_suite).
  • parent: reference to the parent context of type struct kunit that can be used for storing shared resources.
  • params_array: for storing the parameter array.

Description

Used to store information about the current context under which the test is running. Most of this data is private and should only be accessed indirectly via public functions; the exceptions are priv, parent and params_array which can be used by the test writer to store arbitrary data, access the parent context, and to store the parameter array, respectively.

kunit_test_suites() #

kunit_test_suites(__suites...)

used to register one or more struct kunit_suite with KUnit.

Parameters

  • __suites...: a statically allocated list of struct kunit_suite.

Description

Registers suites with the test framework. This is done by placing the array of struct kunit_suite * in the .kunit_test_suites ELF section.

When builtin, KUnit tests are all run via the executor at boot, and when built as a module, they run on module load.

kunit_test_init_section_suites() #

kunit_test_init_section_suites(__suites...)

used to register one or more struct kunit_suite containing init functions or init data.

Parameters

  • __suites...: a statically allocated list of struct kunit_suite.

Description

This functions similar to kunit_test_suites() except that it compiles the list of suites during init phase.

This macro also suffixes the array and suite declarations it makes with _probe; so that modpost suppresses warnings about referencing init data for symbols named in this manner.

Note

these init tests are not able to be run after boot so there is no "run" debugfs file generated for these tests.

Also, do not mark the suite or test case structs with __initdata because they will be used after the init phase with debugfs.

kunit_kmalloc_array() #

void * kunit_kmalloc_array(struct kunit *test, size_t n, size_t size, gfp_t gfp)

Like kmalloc_array() except the allocation is test managed.

Parameters

  • struct kunit *test: The test context object.
  • size_t n: number of elements.
  • size_t size: The size in bytes of the desired memory.
  • gfp_t gfp: flags passed to underlying kmalloc().

Description

Just like kmalloc_array(...), except the allocation is managed by the test case and is automatically cleaned up after the test case concludes. See kunit_add_action() for more information.

Note that some internal context data is also allocated with GFP_KERNEL, regardless of the gfp passed in.

kunit_kmalloc() #

void * kunit_kmalloc(struct kunit *test, size_t size, gfp_t gfp)

Like kmalloc() except the allocation is test managed.

Parameters

  • struct kunit *test: The test context object.
  • size_t size: The size in bytes of the desired memory.
  • gfp_t gfp: flags passed to underlying kmalloc().

Description

See kmalloc() and kunit_kmalloc_array() for more information.

Note that some internal context data is also allocated with GFP_KERNEL, regardless of the gfp passed in.

kunit_kfree() #

void kunit_kfree(struct kunit *test, const void *ptr)

Like kfree except for allocations managed by KUnit.

Parameters

  • struct kunit *test: The test case to which the resource belongs.
  • const void *ptr: The memory allocation to free.

kunit_kzalloc() #

void * kunit_kzalloc(struct kunit *test, size_t size, gfp_t gfp)

Just like kunit_kmalloc(), but zeroes the allocation.

Parameters

  • struct kunit *test: The test context object.
  • size_t size: The size in bytes of the desired memory.
  • gfp_t gfp: flags passed to underlying kmalloc().

Description

See kzalloc() and kunit_kmalloc_array() for more information.

kunit_kcalloc() #

void * kunit_kcalloc(struct kunit *test, size_t n, size_t size, gfp_t gfp)

Just like kunit_kmalloc_array(), but zeroes the allocation.

Parameters

  • struct kunit *test: The test context object.
  • size_t n: number of elements.
  • size_t size: The size in bytes of the desired memory.
  • gfp_t gfp: flags passed to underlying kmalloc().

Description

See kcalloc() and kunit_kmalloc_array() for more information.

kunit_kfree_const() #

void kunit_kfree_const(struct kunit *test, const void *x)

conditionally free test managed memory

Parameters

  • struct kunit *test: The test context object.
  • const void *x: pointer to the memory

Description

Calls kunit_kfree() only if x is not in .rodata section. See kunit_kstrdup_const() for more information.

kunit_kstrdup() #

char * kunit_kstrdup(struct kunit *test, const char *str, gfp_t gfp)

Duplicates a string into a test managed allocation.

Parameters

  • struct kunit *test: The test context object.
  • const char *str: The NULL-terminated string to duplicate.
  • gfp_t gfp: flags passed to underlying kmalloc().

Description

See kstrdup() and kunit_kmalloc_array() for more information.

kunit_kstrdup_const() #

const char * kunit_kstrdup_const(struct kunit *test, const char *str, gfp_t gfp)

Conditionally duplicates a string into a test managed allocation.

Parameters

  • struct kunit *test: The test context object.
  • const char *str: The NULL-terminated string to duplicate.
  • gfp_t gfp: flags passed to underlying kmalloc().

Description

Calls kunit_kstrdup() only if str is not in the rodata section. Must be freed with kunit_kfree_const() -- not kunit_kfree(). See kstrdup_const() and kunit_kmalloc_array() for more information.

kunit_attach_mm() #

int kunit_attach_mm(void)

Create and attach a new mm if it doesn't already exist.

Parameters

  • void: no arguments

Description

Allocates a struct mm_struct and attaches it to current. In most cases, call kunit_vm_mmap() without calling kunit_attach_mm() directly. Only necessary when code under test accesses the mm before executing the mmap (e.g., to perform additional initialization beforehand).

Return

0 on success, -errno on failure.

kunit_vm_mmap() #

unsigned long kunit_vm_mmap(struct kunit *test, struct file *file, unsigned long addr, unsigned long len, unsigned long prot, unsigned long flag, unsigned long offset)

Allocate KUnit-tracked vm_mmap() area

Parameters

  • struct kunit *test: The test context object.
  • struct file *file: struct file pointer to map from, if any
  • unsigned long addr: desired address, if any
  • unsigned long len: how many bytes to allocate
  • unsigned long prot: mmap PROT_* bits
  • unsigned long flag: mmap flags
  • unsigned long offset: offset into file to start mapping from.

Description

See vm_mmap() for more information.

kunit_mark_skipped() #

kunit_mark_skipped(test, fmt, ...)

Marks test as skipped

Parameters

  • test: The test context object.
  • fmt: A printk() style format string.
  • ...: variable arguments

Description

Marks the test as skipped. fmt is given output as the test status comment, typically the reason the test was skipped.

Test execution continues after kunit_mark_skipped() is called.

kunit_skip() #

kunit_skip(test, fmt, ...)

Marks test as skipped

Parameters

  • test: The test context object.
  • fmt: A printk() style format string.
  • ...: variable arguments

Description

Skips the test. fmt is given output as the test status comment, typically the reason the test was skipped.

Test execution is halted after kunit_skip() is called.

kunit_info() #

kunit_info(test, fmt, ...)

Prints an INFO level message associated with test.

Parameters

  • test: The test context object.
  • fmt: A printk() style format string.
  • ...: variable arguments

Description

Prints an info level message associated with the test suite being run. Takes a variable number of format parameters just like printk().

kunit_warn() #

kunit_warn(test, fmt, ...)

Prints a WARN level message associated with test.

Parameters

  • test: The test context object.
  • fmt: A printk() style format string.
  • ...: variable arguments

Description

Prints a warning level message.

kunit_err() #

kunit_err(test, fmt, ...)

Prints an ERROR level message associated with test.

Parameters

  • test: The test context object.
  • fmt: A printk() style format string.
  • ...: variable arguments

Description

Prints an error level message.

KUNIT_SUCCEED() #

KUNIT_SUCCEED(test)

A no-op expectation. Only exists for code clarity.

Parameters

  • test: The test context object.

Description

The opposite of KUNIT_FAIL(), it is an expectation that cannot fail. In other words, it does nothing and only exists for code clarity. See KUNIT_EXPECT_TRUE() for more information.

KUNIT_FAIL() #

KUNIT_FAIL(test, fmt, ...)

Always causes a test to fail when evaluated.

Parameters

  • test: The test context object.
  • fmt: an informational message to be printed when the assertion is made.
  • ...: string format arguments.

Description

The opposite of KUNIT_SUCCEED(), it is an expectation that always fails. In other words, it always results in a failed expectation, and consequently always causes the test case to fail when evaluated. See KUNIT_EXPECT_TRUE() for more information.

KUNIT_EXPECT_TRUE() #

KUNIT_EXPECT_TRUE(test, condition)

Causes a test failure when the expression is not true.

Parameters

  • test: The test context object.
  • condition: an arbitrary boolean expression. The test fails when this does not evaluate to true.

Description

This and expectations of the form KUNIT_EXPECT_* will cause the test case to fail when the specified condition is not met; however, it will not prevent the test case from continuing to run; this is otherwise known as an expectation failure.

KUNIT_EXPECT_FALSE() #

KUNIT_EXPECT_FALSE(test, condition)

Makes a test failure when the expression is not false.

Parameters

  • test: The test context object.
  • condition: an arbitrary boolean expression. The test fails when this does not evaluate to false.

Description

Sets an expectation that condition evaluates to false. See KUNIT_EXPECT_TRUE() for more information.

KUNIT_EXPECT_EQ() #

KUNIT_EXPECT_EQ(test, left, right)

Sets an expectation that left and right are equal.

Parameters

  • test: The test context object.
  • left: an arbitrary expression that evaluates to a primitive C type.
  • right: an arbitrary expression that evaluates to a primitive C type.

Description

Sets an expectation that the values that left and right evaluate to are equal. This is semantically equivalent to KUNIT_EXPECT_TRUE(test, (left) == (right)). See KUNIT_EXPECT_TRUE() for more information.

KUNIT_EXPECT_PTR_EQ() #

KUNIT_EXPECT_PTR_EQ(test, left, right)

Expects that pointers left and right are equal.

Parameters

  • test: The test context object.
  • left: an arbitrary expression that evaluates to a pointer.
  • right: an arbitrary expression that evaluates to a pointer.

Description

Sets an expectation that the values that left and right evaluate to are equal. This is semantically equivalent to KUNIT_EXPECT_TRUE(test, (left) == (right)). See KUNIT_EXPECT_TRUE() for more information.

KUNIT_EXPECT_NE() #

KUNIT_EXPECT_NE(test, left, right)

An expectation that left and right are not equal.

Parameters

  • test: The test context object.
  • left: an arbitrary expression that evaluates to a primitive C type.
  • right: an arbitrary expression that evaluates to a primitive C type.

Description

Sets an expectation that the values that left and right evaluate to are not equal. This is semantically equivalent to KUNIT_EXPECT_TRUE(test, (left) != (right)). See KUNIT_EXPECT_TRUE() for more information.

KUNIT_EXPECT_PTR_NE() #

KUNIT_EXPECT_PTR_NE(test, left, right)

Expects that pointers left and right are not equal.

Parameters

  • test: The test context object.
  • left: an arbitrary expression that evaluates to a pointer.
  • right: an arbitrary expression that evaluates to a pointer.

Description

Sets an expectation that the values that left and right evaluate to are not equal. This is semantically equivalent to KUNIT_EXPECT_TRUE(test, (left) != (right)). See KUNIT_EXPECT_TRUE() for more information.

KUNIT_EXPECT_LT() #

KUNIT_EXPECT_LT(test, left, right)

An expectation that left is less than right.

Parameters

  • test: The test context object.
  • left: an arbitrary expression that evaluates to a primitive C type.
  • right: an arbitrary expression that evaluates to a primitive C type.

Description

Sets an expectation that the value that left evaluates to is less than the value that right evaluates to. This is semantically equivalent to KUNIT_EXPECT_TRUE(test, (left) < (right)). See KUNIT_EXPECT_TRUE() for more information.

KUNIT_EXPECT_LE() #

KUNIT_EXPECT_LE(test, left, right)

Expects that left is less than or equal to right.

Parameters

  • test: The test context object.
  • left: an arbitrary expression that evaluates to a primitive C type.
  • right: an arbitrary expression that evaluates to a primitive C type.

Description

Sets an expectation that the value that left evaluates to is less than or equal to the value that right evaluates to. Semantically this is equivalent to KUNIT_EXPECT_TRUE(test, (left) <= (right)). See KUNIT_EXPECT_TRUE() for more information.

KUNIT_EXPECT_GT() #

KUNIT_EXPECT_GT(test, left, right)

An expectation that left is greater than right.

Parameters

  • test: The test context object.
  • left: an arbitrary expression that evaluates to a primitive C type.
  • right: an arbitrary expression that evaluates to a primitive C type.

Description

Sets an expectation that the value that left evaluates to is greater than the value that right evaluates to. This is semantically equivalent to KUNIT_EXPECT_TRUE(test, (left) > (right)). See KUNIT_EXPECT_TRUE() for more information.

KUNIT_EXPECT_GE() #

KUNIT_EXPECT_GE(test, left, right)

Expects that left is greater than or equal to right.

Parameters

  • test: The test context object.
  • left: an arbitrary expression that evaluates to a primitive C type.
  • right: an arbitrary expression that evaluates to a primitive C type.

Description

Sets an expectation that the value that left evaluates to is greater than the value that right evaluates to. This is semantically equivalent to KUNIT_EXPECT_TRUE(test, (left) >= (right)). See KUNIT_EXPECT_TRUE() for more information.

KUNIT_EXPECT_STREQ() #

KUNIT_EXPECT_STREQ(test, left, right)

Expects that strings left and right are equal.

Parameters

  • test: The test context object.
  • left: an arbitrary expression that evaluates to a null terminated string.
  • right: an arbitrary expression that evaluates to a null terminated string.

Description

Sets an expectation that the values that left and right evaluate to are equal. This is semantically equivalent to KUNIT_EXPECT_TRUE(test, !strcmp((left), (right))). See KUNIT_EXPECT_TRUE() for more information.

KUNIT_EXPECT_STRNEQ() #

KUNIT_EXPECT_STRNEQ(test, left, right)

Expects that strings left and right are not equal.

Parameters

  • test: The test context object.
  • left: an arbitrary expression that evaluates to a null terminated string.
  • right: an arbitrary expression that evaluates to a null terminated string.

Description

Sets an expectation that the values that left and right evaluate to are not equal. This is semantically equivalent to KUNIT_EXPECT_TRUE(test, strcmp((left), (right))). See KUNIT_EXPECT_TRUE() for more information.

KUNIT_EXPECT_MEMEQ() #

KUNIT_EXPECT_MEMEQ(test, left, right, size)

Expects that the first size bytes of left and right are equal.

Parameters

  • test: The test context object.
  • left: An arbitrary expression that evaluates to the specified size.
  • right: An arbitrary expression that evaluates to the specified size.
  • size: Number of bytes compared.

Description

Sets an expectation that the values that left and right evaluate to are equal. This is semantically equivalent to KUNIT_EXPECT_TRUE(test, !memcmp((left), (right), (size))). See KUNIT_EXPECT_TRUE() for more information.

Although this expectation works for any memory block, it is not recommended for comparing more structured data, such as structs. This expectation is recommended for comparing, for example, data arrays.

KUNIT_EXPECT_MEMNEQ() #

KUNIT_EXPECT_MEMNEQ(test, left, right, size)

Expects that the first size bytes of left and right are not equal.

Parameters

  • test: The test context object.
  • left: An arbitrary expression that evaluates to the specified size.
  • right: An arbitrary expression that evaluates to the specified size.
  • size: Number of bytes compared.

Description

Sets an expectation that the values that left and right evaluate to are not equal. This is semantically equivalent to KUNIT_EXPECT_TRUE(test, memcmp((left), (right), (size))). See KUNIT_EXPECT_TRUE() for more information.

Although this expectation works for any memory block, it is not recommended for comparing more structured data, such as structs. This expectation is recommended for comparing, for example, data arrays.

KUNIT_EXPECT_NULL() #

KUNIT_EXPECT_NULL(test, ptr)

Expects that ptr is null.

Parameters

  • test: The test context object.
  • ptr: an arbitrary pointer.

Description

Sets an expectation that the value that ptr evaluates to is null. This is semantically equivalent to KUNIT_EXPECT_PTR_EQ(test, ptr, NULL). See KUNIT_EXPECT_TRUE() for more information.

KUNIT_EXPECT_NOT_NULL() #

KUNIT_EXPECT_NOT_NULL(test, ptr)

Expects that ptr is not null.

Parameters

  • test: The test context object.
  • ptr: an arbitrary pointer.

Description

Sets an expectation that the value that ptr evaluates to is not null. This is semantically equivalent to KUNIT_EXPECT_PTR_NE(test, ptr, NULL). See KUNIT_EXPECT_TRUE() for more information.

KUNIT_EXPECT_NOT_ERR_OR_NULL() #

KUNIT_EXPECT_NOT_ERR_OR_NULL(test, ptr)

Expects that ptr is not null and not err.

Parameters

  • test: The test context object.
  • ptr: an arbitrary pointer.

Description

Sets an expectation that the value that ptr evaluates to is not null and not an errno stored in a pointer. This is semantically equivalent to KUNIT_EXPECT_TRUE(test, !IS_ERR_OR_NULL(ptr)). See KUNIT_EXPECT_TRUE() for more information.

KUNIT_FAIL_AND_ABORT() #

KUNIT_FAIL_AND_ABORT(test, fmt, ...)

Always causes a test to fail and abort when evaluated.

Parameters

  • test: The test context object.
  • fmt: an informational message to be printed when the assertion is made.
  • ...: string format arguments.

Description

The opposite of KUNIT_SUCCEED(), it is an assertion that always fails. In other words, it always results in a failed assertion, and consequently always causes the test case to fail and abort when evaluated. See KUNIT_ASSERT_TRUE() for more information.

KUNIT_ASSERT_TRUE() #

KUNIT_ASSERT_TRUE(test, condition)

Sets an assertion that condition is true.

Parameters

  • test: The test context object.
  • condition: an arbitrary boolean expression. The test fails and aborts when this does not evaluate to true.

Description

This and assertions of the form KUNIT_ASSERT_* will cause the test case to fail and immediately abort when the specified condition is not met. Unlike an expectation failure, it will prevent the test case from continuing to run; this is otherwise known as an assertion failure.

KUNIT_ASSERT_FALSE() #

KUNIT_ASSERT_FALSE(test, condition)

Sets an assertion that condition is false.

Parameters

  • test: The test context object.
  • condition: an arbitrary boolean expression.

Description

Sets an assertion that the value that condition evaluates to is false. This is the same as KUNIT_EXPECT_FALSE(), except it causes an assertion failure (see KUNIT_ASSERT_TRUE()) when the assertion is not met.

KUNIT_ASSERT_EQ() #

KUNIT_ASSERT_EQ(test, left, right)

Sets an assertion that left and right are equal.

Parameters

  • test: The test context object.
  • left: an arbitrary expression that evaluates to a primitive C type.
  • right: an arbitrary expression that evaluates to a primitive C type.

Description

Sets an assertion that the values that left and right evaluate to are equal. This is the same as KUNIT_EXPECT_EQ(), except it causes an assertion failure (see KUNIT_ASSERT_TRUE()) when the assertion is not met.

KUNIT_ASSERT_PTR_EQ() #

KUNIT_ASSERT_PTR_EQ(test, left, right)

Asserts that pointers left and right are equal.

Parameters

  • test: The test context object.
  • left: an arbitrary expression that evaluates to a pointer.
  • right: an arbitrary expression that evaluates to a pointer.

Description

Sets an assertion that the values that left and right evaluate to are equal. This is the same as KUNIT_EXPECT_EQ(), except it causes an assertion failure (see KUNIT_ASSERT_TRUE()) when the assertion is not met.

KUNIT_ASSERT_NE() #

KUNIT_ASSERT_NE(test, left, right)

An assertion that left and right are not equal.

Parameters

  • test: The test context object.
  • left: an arbitrary expression that evaluates to a primitive C type.
  • right: an arbitrary expression that evaluates to a primitive C type.

Description

Sets an assertion that the values that left and right evaluate to are not equal. This is the same as KUNIT_EXPECT_NE(), except it causes an assertion failure (see KUNIT_ASSERT_TRUE()) when the assertion is not met.

KUNIT_ASSERT_PTR_NE() #

KUNIT_ASSERT_PTR_NE(test, left, right)

Asserts that pointers left and right are not equal. KUNIT_ASSERT_PTR_EQ() - Asserts that pointers left and right are equal.

Parameters

  • test: The test context object.
  • left: an arbitrary expression that evaluates to a pointer.
  • right: an arbitrary expression that evaluates to a pointer.

Description

Sets an assertion that the values that left and right evaluate to are not equal. This is the same as KUNIT_EXPECT_NE(), except it causes an assertion failure (see KUNIT_ASSERT_TRUE()) when the assertion is not met.

KUNIT_ASSERT_LT() #

KUNIT_ASSERT_LT(test, left, right)

An assertion that left is less than right.

Parameters

  • test: The test context object.
  • left: an arbitrary expression that evaluates to a primitive C type.
  • right: an arbitrary expression that evaluates to a primitive C type.

Description

Sets an assertion that the value that left evaluates to is less than the value that right evaluates to. This is the same as KUNIT_EXPECT_LT(), except it causes an assertion failure (see KUNIT_ASSERT_TRUE()) when the assertion is not met.

KUNIT_ASSERT_LE() #

KUNIT_ASSERT_LE(test, left, right)

An assertion that left is less than or equal to right.

Parameters

  • test: The test context object.
  • left: an arbitrary expression that evaluates to a primitive C type.
  • right: an arbitrary expression that evaluates to a primitive C type.

Description

Sets an assertion that the value that left evaluates to is less than or equal to the value that right evaluates to. This is the same as KUNIT_EXPECT_LE(), except it causes an assertion failure (see KUNIT_ASSERT_TRUE()) when the assertion is not met.

KUNIT_ASSERT_GT() #

KUNIT_ASSERT_GT(test, left, right)

An assertion that left is greater than right.

Parameters

  • test: The test context object.
  • left: an arbitrary expression that evaluates to a primitive C type.
  • right: an arbitrary expression that evaluates to a primitive C type.

Description

Sets an assertion that the value that left evaluates to is greater than the value that right evaluates to. This is the same as KUNIT_EXPECT_GT(), except it causes an assertion failure (see KUNIT_ASSERT_TRUE()) when the assertion is not met.

KUNIT_ASSERT_GE() #

KUNIT_ASSERT_GE(test, left, right)

Assertion that left is greater than or equal to right.

Parameters

  • test: The test context object.
  • left: an arbitrary expression that evaluates to a primitive C type.
  • right: an arbitrary expression that evaluates to a primitive C type.

Description

Sets an assertion that the value that left evaluates to is greater than the value that right evaluates to. This is the same as KUNIT_EXPECT_GE(), except it causes an assertion failure (see KUNIT_ASSERT_TRUE()) when the assertion is not met.

KUNIT_ASSERT_STREQ() #

KUNIT_ASSERT_STREQ(test, left, right)

An assertion that strings left and right are equal.

Parameters

  • test: The test context object.
  • left: an arbitrary expression that evaluates to a null terminated string.
  • right: an arbitrary expression that evaluates to a null terminated string.

Description

Sets an assertion that the values that left and right evaluate to are equal. This is the same as KUNIT_EXPECT_STREQ(), except it causes an assertion failure (see KUNIT_ASSERT_TRUE()) when the assertion is not met.

KUNIT_ASSERT_STRNEQ() #

KUNIT_ASSERT_STRNEQ(test, left, right)

An assertion that strings left and right are not equal.

Parameters

  • test: The test context object.
  • left: an arbitrary expression that evaluates to a null terminated string.
  • right: an arbitrary expression that evaluates to a null terminated string.

Description

Sets an assertion that the values that left and right evaluate to are not equal. This is semantically equivalent to KUNIT_ASSERT_TRUE(test, strcmp((left), (right))). See KUNIT_ASSERT_TRUE() for more information.

KUNIT_ASSERT_MEMEQ() #

KUNIT_ASSERT_MEMEQ(test, left, right, size)

Asserts that the first size bytes of left and right are equal.

Parameters

  • test: The test context object.
  • left: An arbitrary expression that evaluates to the specified size.
  • right: An arbitrary expression that evaluates to the specified size.
  • size: Number of bytes compared.

Description

Sets an assertion that the values that left and right evaluate to are equal. This is semantically equivalent to KUNIT_ASSERT_TRUE(test, !memcmp((left), (right), (size))). See KUNIT_ASSERT_TRUE() for more information.

Although this assertion works for any memory block, it is not recommended for comparing more structured data, such as structs. This assertion is recommended for comparing, for example, data arrays.

KUNIT_ASSERT_MEMNEQ() #

KUNIT_ASSERT_MEMNEQ(test, left, right, size)

Asserts that the first size bytes of left and right are not equal.

Parameters

  • test: The test context object.
  • left: An arbitrary expression that evaluates to the specified size.
  • right: An arbitrary expression that evaluates to the specified size.
  • size: Number of bytes compared.

Description

Sets an assertion that the values that left and right evaluate to are not equal. This is semantically equivalent to KUNIT_ASSERT_TRUE(test, memcmp((left), (right), (size))). See KUNIT_ASSERT_TRUE() for more information.

Although this assertion works for any memory block, it is not recommended for comparing more structured data, such as structs. This assertion is recommended for comparing, for example, data arrays.

KUNIT_ASSERT_NULL() #

KUNIT_ASSERT_NULL(test, ptr)

Asserts that pointers ptr is null.

Parameters

  • test: The test context object.
  • ptr: an arbitrary pointer.

Description

Sets an assertion that the values that ptr evaluates to is null. This is the same as KUNIT_EXPECT_NULL(), except it causes an assertion failure (see KUNIT_ASSERT_TRUE()) when the assertion is not met.

KUNIT_ASSERT_NOT_NULL() #

KUNIT_ASSERT_NOT_NULL(test, ptr)

Asserts that pointers ptr is not null.

Parameters

  • test: The test context object.
  • ptr: an arbitrary pointer.

Description

Sets an assertion that the values that ptr evaluates to is not null. This is the same as KUNIT_EXPECT_NOT_NULL(), except it causes an assertion failure (see KUNIT_ASSERT_TRUE()) when the assertion is not met.

KUNIT_ASSERT_NOT_ERR_OR_NULL() #

KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr)

Assertion that ptr is not null and not err.

Parameters

  • test: The test context object.
  • ptr: an arbitrary pointer.

Description

Sets an assertion that the value that ptr evaluates to is not null and not an errno stored in a pointer. This is the same as KUNIT_EXPECT_NOT_ERR_OR_NULL(), except it causes an assertion failure (see KUNIT_ASSERT_TRUE()) when the assertion is not met.

KUNIT_ARRAY_PARAM() #

KUNIT_ARRAY_PARAM(name, array, get_desc)

Define test parameter generator from an array.

Parameters

  • name: prefix for the test parameter generator function.
  • array: array of test parameters.
  • get_desc: function to convert param to description; NULL to use default

Description

Define function name_gen_params which uses array to generate parameters.

KUNIT_ARRAY_PARAM_DESC() #

KUNIT_ARRAY_PARAM_DESC(name, array, desc_member)

Define test parameter generator from an array.

Parameters

  • name: prefix for the test parameter generator function.
  • array: array of test parameters.
  • desc_member: structure member from array element to use as description

Description

Define function name_gen_params which uses array to generate parameters.

kunit_register_params_array() #

kunit_register_params_array(test, array, param_count, get_desc)

Register parameter array for a KUnit test.

Parameters

  • test: The KUnit test structure to which parameters will be added.
  • array: An array of test parameters.
  • param_count: Number of parameters.
  • get_desc: Function that generates a string description for a given parameter element.

Description

This macro initializes the test's parameter array data, storing information including the parameter array, its count, the element size, and the parameter description function within test->params_array.

Note

If using this macro in param_init(), kunit_array_gen_params() will then need to be manually provided as the parameter generator function to KUNIT_CASE_PARAM_WITH_INIT(). kunit_array_gen_params() is a KUnit function that uses the registered array to generate parameters

Linux Kernel Memory Consistency Model (LKMM)

Peios Kernel / Kernel development / Development tools / lkmm

This section literally renders documents under tools/memory-model/ and tools/memory-model/Documentation/, which are maintained in the pure plain text form.

  • readme
  • Documentation

README (for LKMM)

Peios Kernel / Kernel development / Development tools / lkmm

Literal include of tools/memory-model/README.


                =====================================
                LINUX KERNEL MEMORY CONSISTENCY MODEL
                =====================================

============
INTRODUCTION
============

This directory contains the memory consistency model (memory model, for
short) of the Linux kernel, written in the "cat" language and executable
by the externally provided "herd7" simulator, which exhaustively explores
the state space of small litmus tests.

In addition, the "klitmus7" tool (also externally provided) may be used
to convert a litmus test to a Linux kernel module, which in turn allows
that litmus test to be exercised within the Linux kernel.


============
REQUIREMENTS
============

Version 7.58 or higher of the "herd7" and "klitmus7" tools must be
downloaded separately:

  https://github.com/herd/herdtools7

See "herdtools7/INSTALL.md" for installation instructions.

Note that although these tools usually provide backwards compatibility,
this is not absolutely guaranteed.

For example, a future version of herd7 might not work with the model
in this release.  A compatible model will likely be made available in
a later release of Linux kernel.

If you absolutely need to run the model in this particular release,
please try using the exact version called out above.

klitmus7 is independent of the model provided here.  It has its own
dependency on a target kernel release where converted code is built
and executed.  Any change in kernel APIs essential to klitmus7 will
necessitate an upgrade of klitmus7.

If you find any compatibility issues in klitmus7, please inform the
memory model maintainers.

klitmus7 Compatibility Table
----------------------------

        ============  ==========
        target Linux  herdtools7
        ------------  ----------
             -- 4.14  7.48 --
        4.15 -- 4.19  7.49 --
        4.20 -- 5.5   7.54 --
        5.6  -- 5.16  7.56 --
        5.17 --       7.56.1 --
        ============  ==========


==================
BASIC USAGE: HERD7
==================

The memory model is used, in conjunction with "herd7", to exhaustively
explore the state space of small litmus tests.  Documentation describing
the format, features, capabilities and limitations of these litmus
tests is available in tools/memory-model/Documentation/litmus-tests.txt.

Example litmus tests may be found in the Linux-kernel source tree:

        tools/memory-model/litmus-tests/
        Documentation/litmus-tests/

Several thousand more example litmus tests are available here:

        https://github.com/paulmckrcu/litmus
        https://git.kernel.org/pub/scm/linux/kernel/git/paulmck/perfbook.git/tree/CodeSamples/formal/herd
        https://git.kernel.org/pub/scm/linux/kernel/git/paulmck/perfbook.git/tree/CodeSamples/formal/litmus

Documentation describing litmus tests and how to use them may be found
here:

        tools/memory-model/Documentation/litmus-tests.txt

The remainder of this section uses the SB+fencembonceonces.litmus test
located in the tools/memory-model directory.

To run SB+fencembonceonces.litmus against the memory model:

  $ cd $LINUX_SOURCE_TREE/tools/memory-model
  $ herd7 -conf linux-kernel.cfg litmus-tests/SB+fencembonceonces.litmus

Here is the corresponding output:

  Test SB+fencembonceonces Allowed
  States 3
  0:r0=0; 1:r0=1;
  0:r0=1; 1:r0=0;
  0:r0=1; 1:r0=1;
  No
  Witnesses
  Positive: 0 Negative: 3
  Condition exists (0:r0=0 /\ 1:r0=0)
  Observation SB+fencembonceonces Never 0 3
  Time SB+fencembonceonces 0.01
  Hash=d66d99523e2cac6b06e66f4c995ebb48

The "Positive: 0 Negative: 3" and the "Never 0 3" each indicate that
this litmus test's "exists" clause can not be satisfied.

See "herd7 -help" or "herdtools7/doc/" for more information on running the
tool itself, but please be aware that this documentation is intended for
people who work on the memory model itself, that is, people making changes
to the tools/memory-model/linux-kernel.* files.  It is not intended for
people focusing on writing, understanding, and running LKMM litmus tests.


=====================
BASIC USAGE: KLITMUS7
=====================

The "klitmus7" tool converts a litmus test into a Linux kernel module,
which may then be loaded and run.

For example, to run SB+fencembonceonces.litmus against hardware:

  $ mkdir mymodules
  $ klitmus7 -o mymodules litmus-tests/SB+fencembonceonces.litmus
  $ cd mymodules ; make
  $ sudo sh run.sh

The corresponding output includes:

  Test SB+fencembonceonces Allowed
  Histogram (3 states)
  644580  :>0:r0=1; 1:r0=0;
  644328  :>0:r0=0; 1:r0=1;
  711092  :>0:r0=1; 1:r0=1;
  No
  Witnesses
  Positive: 0, Negative: 2000000
  Condition exists (0:r0=0 /\ 1:r0=0) is NOT validated
  Hash=d66d99523e2cac6b06e66f4c995ebb48
  Observation SB+fencembonceonces Never 0 2000000
  Time SB+fencembonceonces 0.16

The "Positive: 0 Negative: 2000000" and the "Never 0 2000000" indicate
that during two million trials, the state specified in this litmus
test's "exists" clause was not reached.

And, as with "herd7", please see "klitmus7 -help" or "herdtools7/doc/"
for more information.  And again, please be aware that this documentation
is intended for people who work on the memory model itself, that is,
people making changes to the tools/memory-model/linux-kernel.* files.
It is not intended for people focusing on writing, understanding, and
running LKMM litmus tests.


====================
DESCRIPTION OF FILES
====================

Documentation/README
        Guide to the other documents in the Documentation/ directory.

linux-kernel.bell
        Categorizes the relevant instructions, including memory
        references, memory barriers, atomic read-modify-write operations,
        lock acquisition/release, and RCU operations.

        More formally, this file (1) lists the subtypes of the various
        event types used by the memory model and (2) performs RCU
        read-side critical section nesting analysis.

linux-kernel.cat
        Specifies what reorderings are forbidden by memory references,
        memory barriers, atomic read-modify-write operations, and RCU.

        More formally, this file specifies what executions are forbidden
        by the memory model.  Allowed executions are those which
        satisfy the model's "coherence", "atomic", "happens-before",
        "propagation", and "rcu" axioms, which are defined in the file.

linux-kernel.cfg
        Convenience file that gathers the common-case herd7 command-line
        arguments.

linux-kernel.def
        Maps from C-like syntax to herd7's internal litmus-test
        instruction-set architecture.

litmus-tests
        Directory containing a few representative litmus tests, which
        are listed in litmus-tests/README.  A great deal more litmus
        tests are available at https://github.com/paulmckrcu/litmus.

        By "representative", it means the one in the litmus-tests
        directory is:

                1) simple, the number of threads should be relatively
                   small and each thread function should be relatively
                   simple.
                2) orthogonal, there should be no two litmus tests
                   describing the same aspect of the memory model.
                3) textbook, developers can easily copy-paste-modify
                   the litmus tests to use the patterns on their own
                   code.

lock.cat
        Provides a front-end analysis of lock acquisition and release,
        for example, associating a lock acquisition with the preceding
        and following releases and checking for self-deadlock.

        More formally, this file defines a performance-enhanced scheme
        for generation of the possible reads-from and coherence order
        relations on the locking primitives.

README
        This file.

scripts Various scripts, see scripts/README.

Documentation

Peios Kernel / Kernel development / Development tools / lkmm / docs

  • readme
  • simple
  • ordering
  • litmus-tests
  • locking
  • recipes
  • control-dependencies
  • access-marking
  • cheatsheet
  • explanation
  • herd-representation
  • glossary
  • references

Access Marking

Peios Kernel / Kernel development / Development tools / lkmm / docs

Literal include of tools/memory-model/Documentation/access-marking.txt.


MARKING SHARED-MEMORY ACCESSES
==============================

This document provides guidelines for marking intentionally concurrent
normal accesses to shared memory, that is "normal" as in accesses that do
not use read-modify-write atomic operations.  It also describes how to
document these accesses, both with comments and with special assertions
processed by the Kernel Concurrency Sanitizer (KCSAN).  This discussion
builds on an earlier LWN article [1] and Linux Foundation mentorship
session [2].


ACCESS-MARKING OPTIONS
======================

The Linux kernel provides the following access-marking options:

1.      Plain C-language accesses (unmarked), for example, "a = b;"

2.      Data-race marking, for example, "data_race(a = b);"

3.      READ_ONCE(), for example, "a = READ_ONCE(b);"
        The various forms of atomic_read() also fit in here.

4.      WRITE_ONCE(), for example, "WRITE_ONCE(a, b);"
        The various forms of atomic_set() also fit in here.

5.      __data_racy, for example "int __data_racy a;"

6.      KCSAN's negative-marking assertions, ASSERT_EXCLUSIVE_ACCESS()
        and ASSERT_EXCLUSIVE_WRITER(), are described in the
        "ACCESS-DOCUMENTATION OPTIONS" section below.

These may be used in combination, as shown in this admittedly improbable
example:

        WRITE_ONCE(a, b + data_race(c + d) + READ_ONCE(e));

Neither plain C-language accesses nor data_race() (#1 and #2 above) place
any sort of constraint on the compiler's choice of optimizations [3].
In contrast, READ_ONCE() and WRITE_ONCE() (#3 and #4 above) restrict the
compiler's use of code-motion and common-subexpression optimizations.
Therefore, if a given access is involved in an intentional data race,
using READ_ONCE() for loads and WRITE_ONCE() for stores is usually
preferable to data_race(), which in turn is usually preferable to plain
C-language accesses.  It is permissible to combine #2 and #3, for example,
data_race(READ_ONCE(a)), which will both restrict compiler optimizations
and disable KCSAN diagnostics.

KCSAN will complain about many types of data races involving plain
C-language accesses, but marking all accesses involved in a given data
race with one of data_race(), READ_ONCE(), or WRITE_ONCE(), will prevent
KCSAN from complaining.  Of course, lack of KCSAN complaints does not
imply correct code.  Therefore, please take a thoughtful approach
when responding to KCSAN complaints.  Churning the code base with
ill-considered additions of data_race(), READ_ONCE(), and WRITE_ONCE()
is unhelpful.

In fact, the following sections describe situations where use of
data_race() and even plain C-language accesses is preferable to
READ_ONCE() and WRITE_ONCE().


Use of the data_race() Macro
----------------------------

Here are some situations where data_race() should be used instead of
READ_ONCE() and WRITE_ONCE():

1.      Data-racy loads from shared variables whose values are used only
        for diagnostic purposes.

2.      Data-racy reads whose values are checked against marked reload.

3.      Reads whose values feed into error-tolerant heuristics.

4.      Writes setting values that feed into error-tolerant heuristics.


Data-Racy Reads for Approximate Diagnostics

Approximate diagnostics include lockdep reports, monitoring/statistics
(including /proc and /sys output), WARN*()/BUG*() checks whose return
values are ignored, and other situations where reads from shared variables
are not an integral part of the core concurrency design.

In fact, use of data_race() instead READ_ONCE() for these diagnostic
reads can enable better checking of the remaining accesses implementing
the core concurrency design.  For example, suppose that the core design
prevents any non-diagnostic reads from shared variable x from running
concurrently with updates to x.  Then using plain C-language writes
to x allows KCSAN to detect reads from x from within regions of code
that fail to exclude the updates.  In this case, it is important to use
data_race() for the diagnostic reads because otherwise KCSAN would give
false-positive warnings about these diagnostic reads.

If it is necessary to both restrict compiler optimizations and disable
KCSAN diagnostics, use both data_race() and READ_ONCE(), for example,
data_race(READ_ONCE(a)).

In theory, plain C-language loads can also be used for this use case.
However, in practice this will have the disadvantage of causing KCSAN
to generate false positives because KCSAN will have no way of knowing
that the resulting data race was intentional.


Data-Racy Reads That Are Checked Against Marked Reload

The values from some reads are not implicitly trusted.  They are instead
fed into some operation that checks the full value against a later marked
load from memory, which means that the occasional arbitrarily bogus value
is not a problem.  For example, if a bogus value is fed into cmpxchg(),
all that happens is that this cmpxchg() fails, which normally results
in a retry.  Unless the race condition that resulted in the bogus value
recurs, this retry will with high probability succeed, so no harm done.

However, please keep in mind that a data_race() load feeding into
a cmpxchg_relaxed() might still be subject to load fusing on some
architectures.  Therefore, it is best to capture the return value from
the failing cmpxchg() for the next iteration of the loop, an approach
that provides the compiler much less scope for mischievous optimizations.
Capturing the return value from cmpxchg() also saves a memory reference
in many cases.

In theory, plain C-language loads can also be used for this use case.
However, in practice this will have the disadvantage of causing KCSAN
to generate false positives because KCSAN will have no way of knowing
that the resulting data race was intentional.


Reads Feeding Into Error-Tolerant Heuristics

Values from some reads feed into heuristics that can tolerate occasional
errors.  Such reads can use data_race(), thus allowing KCSAN to focus on
the other accesses to the relevant shared variables.  But please note
that data_race() loads are subject to load fusing, which can result in
consistent errors, which in turn are quite capable of breaking heuristics.
Therefore use of data_race() should be limited to cases where some other
code (such as a barrier() call) will force the occasional reload.

Note that this use case requires that the heuristic be able to handle
any possible error.  In contrast, if the heuristics might be fatally
confused by one or more of the possible erroneous values, use READ_ONCE()
instead of data_race().

In theory, plain C-language loads can also be used for this use case.
However, in practice this will have the disadvantage of causing KCSAN
to generate false positives because KCSAN will have no way of knowing
that the resulting data race was intentional.


Writes Setting Values Feeding Into Error-Tolerant Heuristics

The values read into error-tolerant heuristics come from somewhere,
for example, from sysfs.  This means that some code in sysfs writes
to this same variable, and these writes can also use data_race().
After all, if the heuristic can tolerate the occasional bogus value
due to compiler-mangled reads, it can also tolerate the occasional
compiler-mangled write, at least assuming that the proper value is in
place once the write completes.

Plain C-language stores can also be used for this use case.  However,
in kernels built with CONFIG_KCSAN_ASSUME_PLAIN_WRITES_ATOMIC=n, this
will have the disadvantage of causing KCSAN to generate false positives
because KCSAN will have no way of knowing that the resulting data race
was intentional.


Use of Plain C-Language Accesses
--------------------------------

Here are some example situations where plain C-language accesses should
used instead of READ_ONCE(), WRITE_ONCE(), and data_race():

1.      Accesses protected by mutual exclusion, including strict locking
        and sequence locking.

2.      Initialization-time and cleanup-time accesses.  This covers a
        wide variety of situations, including the uniprocessor phase of
        system boot, variables to be used by not-yet-spawned kthreads,
        structures not yet published to reference-counted or RCU-protected
        data structures, and the cleanup side of any of these situations.

3.      Per-CPU variables that are not accessed from other CPUs.

4.      Private per-task variables, including on-stack variables, some
        fields in the task_struct structure, and task-private heap data.

5.      Any other loads for which there is not supposed to be a concurrent
        store to that same variable.

6.      Any other stores for which there should be neither concurrent
        loads nor concurrent stores to that same variable.

        But note that KCSAN makes two explicit exceptions to this rule
        by default, refraining from flagging plain C-language stores:

        a.      No matter what.  You can override this default by building
                with CONFIG_KCSAN_ASSUME_PLAIN_WRITES_ATOMIC=n.

        b.      When the store writes the value already contained in
                that variable.  You can override this default by building
                with CONFIG_KCSAN_REPORT_VALUE_CHANGE_ONLY=n.

        c.      When one of the stores is in an interrupt handler and
                the other in the interrupted code.  You can override this
                default by building with CONFIG_KCSAN_INTERRUPT_WATCHER=y.

Note that it is important to use plain C-language accesses in these cases,
because doing otherwise prevents KCSAN from detecting violations of your
code's synchronization rules.


Use of __data_racy
------------------

Adding the __data_racy type qualifier to the declaration of a variable
causes KCSAN to treat all accesses to that variable as if they were
enclosed by data_race().  However, __data_racy does not affect the
compiler, though one could imagine hardened kernel builds treating the
__data_racy type qualifier as if it was the volatile keyword.

Note well that __data_racy is subject to the same pointer-declaration
rules as are other type qualifiers such as const and volatile.
For example:

        int __data_racy *p; // Pointer to data-racy data.
        int *__data_racy p; // Data-racy pointer to non-data-racy data.


ACCESS-DOCUMENTATION OPTIONS
============================

It is important to comment marked accesses so that people reading your
code, yourself included, are reminded of the synchronization design.
However, it is even more important to comment plain C-language accesses
that are intentionally involved in data races.  Such comments are
needed to remind people reading your code, again, yourself included,
of how the compiler has been prevented from optimizing those accesses
into concurrency bugs.

It is also possible to tell KCSAN about your synchronization design.
For example, ASSERT_EXCLUSIVE_ACCESS(foo) tells KCSAN that any
concurrent access to variable foo by any other CPU is an error, even
if that concurrent access is marked with READ_ONCE().  In addition,
ASSERT_EXCLUSIVE_WRITER(foo) tells KCSAN that although it is OK for there
to be concurrent reads from foo from other CPUs, it is an error for some
other CPU to be concurrently writing to foo, even if that concurrent
write is marked with data_race() or WRITE_ONCE().

Note that although KCSAN will call out data races involving either
ASSERT_EXCLUSIVE_ACCESS() or ASSERT_EXCLUSIVE_WRITER() on the one hand
and data_race() writes on the other, KCSAN will not report the location
of these data_race() writes.


EXAMPLES
========

As noted earlier, the goal is to prevent the compiler from destroying
your concurrent algorithm, to help the human reader, and to inform
KCSAN of aspects of your concurrency design.  This section looks at a
few examples showing how this can be done.


Lock Protection With Lockless Diagnostic Access
-----------------------------------------------

For example, suppose a shared variable "foo" is read only while a
reader-writer spinlock is read-held, written only while that same
spinlock is write-held, except that it is also read locklessly for
diagnostic purposes.  The code might look as follows:

        int foo;
        DEFINE_RWLOCK(foo_rwlock);

        void update_foo(int newval)
        {
                write_lock(&foo_rwlock);
                foo = newval;
                do_something(newval);
                write_unlock(&foo_rwlock);
        }

        int read_foo(void)
        {
                int ret;

                read_lock(&foo_rwlock);
                do_something_else();
                ret = foo;
                read_unlock(&foo_rwlock);
                return ret;
        }

        void read_foo_diagnostic(void)
        {
                pr_info("Current value of foo: %d\n", data_race(foo));
        }

The reader-writer lock prevents the compiler from introducing concurrency
bugs into any part of the main algorithm using foo, which means that
the accesses to foo within both update_foo() and read_foo() can (and
should) be plain C-language accesses.  One benefit of making them be
plain C-language accesses is that KCSAN can detect any erroneous lockless
reads from or updates to foo.  The data_race() in read_foo_diagnostic()
tells KCSAN that data races are expected, and should be silently
ignored.  This data_race() also tells the human reading the code that
read_foo_diagnostic() might sometimes return a bogus value.

If it is necessary to suppress compiler optimization and also detect
buggy lockless writes, read_foo_diagnostic() can be updated as follows:

        void read_foo_diagnostic(void)
        {
                pr_info("Current value of foo: %d\n", data_race(READ_ONCE(foo)));
        }

Alternatively, given that KCSAN is to ignore all accesses in this function,
this function can be marked __no_kcsan and the data_race() can be dropped:

        void __no_kcsan read_foo_diagnostic(void)
        {
                pr_info("Current value of foo: %d\n", READ_ONCE(foo));
        }

However, in order for KCSAN to detect buggy lockless writes, your kernel
must be built with CONFIG_KCSAN_ASSUME_PLAIN_WRITES_ATOMIC=n.  If you
need KCSAN to detect such a write even if that write did not change
the value of foo, you also need CONFIG_KCSAN_REPORT_VALUE_CHANGE_ONLY=n.
If you need KCSAN to detect such a write happening in an interrupt handler
running on the same CPU doing the legitimate lock-protected write, you
also need CONFIG_KCSAN_INTERRUPT_WATCHER=y.  With some or all of these
Kconfig options set properly, KCSAN can be quite helpful, although
it is not necessarily a full replacement for hardware watchpoints.
On the other hand, neither are hardware watchpoints a full replacement
for KCSAN because it is not always easy to tell hardware watchpoint to
conditionally trap on accesses.


Lock-Protected Writes With Lockless Reads
-----------------------------------------

For another example, suppose a shared variable "foo" is updated only
while holding a spinlock, but is read locklessly.  The code might look
as follows:

        int foo;
        DEFINE_SPINLOCK(foo_lock);

        void update_foo(int newval)
        {
                spin_lock(&foo_lock);
                WRITE_ONCE(foo, newval);
                ASSERT_EXCLUSIVE_WRITER(foo);
                do_something(newval);
                spin_unlock(&foo_wlock);
        }

        int read_foo(void)
        {
                do_something_else();
                return READ_ONCE(foo);
        }

Because foo is read locklessly, all accesses are marked.  The purpose
of the ASSERT_EXCLUSIVE_WRITER() is to allow KCSAN to check for a buggy
concurrent write, whether marked or not.


Lock-Protected Writes With Heuristic Lockless Reads
---------------------------------------------------

For another example, suppose that the code can normally make use of
a per-data-structure lock, but there are times when a global lock
is required.  These times are indicated via a global flag.  The code
might look as follows, and is based loosely on nf_conntrack_lock(),
nf_conntrack_all_lock(), and nf_conntrack_all_unlock():

        bool global_flag;
        DEFINE_SPINLOCK(global_lock);
        struct foo {
                spinlock_t f_lock;
                int f_data;
        };

        /* All foo structures are in the following array. */
        int nfoo;
        struct foo *foo_array;

        void do_something_locked(struct foo *fp)
        {
                /* This works even if data_race() returns nonsense. */
                if (!data_race(global_flag)) {
                        spin_lock(&fp->f_lock);
                        if (!smp_load_acquire(&global_flag)) {
                                do_something(fp);
                                spin_unlock(&fp->f_lock);
                                return;
                        }
                        spin_unlock(&fp->f_lock);
                }
                spin_lock(&global_lock);
                /* global_lock held, thus global flag cannot be set. */
                spin_lock(&fp->f_lock);
                spin_unlock(&global_lock);
                /*
                 * global_flag might be set here, but begin_global()
                 * will wait for ->f_lock to be released.
                 */
                do_something(fp);
                spin_unlock(&fp->f_lock);
        }

        void begin_global(void)
        {
                int i;

                spin_lock(&global_lock);
                WRITE_ONCE(global_flag, true);
                for (i = 0; i < nfoo; i++) {
                        /*
                         * Wait for pre-existing local locks.  One at
                         * a time to avoid lockdep limitations.
                         */
                        spin_lock(&fp->f_lock);
                        spin_unlock(&fp->f_lock);
                }
        }

        void end_global(void)
        {
                smp_store_release(&global_flag, false);
                spin_unlock(&global_lock);
        }

All code paths leading from the do_something_locked() function's first
read from global_flag acquire a lock, so endless load fusing cannot
happen.

If the value read from global_flag is true, then global_flag is
rechecked while holding ->f_lock, which, if global_flag is now false,
prevents begin_global() from completing.  It is therefore safe to invoke
do_something().

Otherwise, if either value read from global_flag is true, then after
global_lock is acquired global_flag must be false.  The acquisition of
->f_lock will prevent any call to begin_global() from returning, which
means that it is safe to release global_lock and invoke do_something().

For this to work, only those foo structures in foo_array[] may be passed
to do_something_locked().  The reason for this is that the synchronization
with begin_global() relies on momentarily holding the lock of each and
every foo structure.

The smp_load_acquire() and smp_store_release() are required because
changes to a foo structure between calls to begin_global() and
end_global() are carried out without holding that structure's ->f_lock.
The smp_load_acquire() and smp_store_release() ensure that the next
invocation of do_something() from do_something_locked() will see those
changes.


Lockless Reads and Writes
-------------------------

For another example, suppose a shared variable "foo" is both read and
updated locklessly.  The code might look as follows:

        int foo;

        int update_foo(int newval)
        {
                int ret;

                ret = xchg(&foo, newval);
                do_something(newval);
                return ret;
        }

        int read_foo(void)
        {
                do_something_else();
                return READ_ONCE(foo);
        }

Because foo is accessed locklessly, all accesses are marked.  It does
not make sense to use ASSERT_EXCLUSIVE_WRITER() in this case because
there really can be concurrent lockless writers.  KCSAN would
flag any concurrent plain C-language reads from foo, and given
CONFIG_KCSAN_ASSUME_PLAIN_WRITES_ATOMIC=n, also any concurrent plain
C-language writes to foo.


Lockless Reads and Writes, But With Single-Threaded Initialization
------------------------------------------------------------------

For yet another example, suppose that foo is initialized in a
single-threaded manner, but that a number of kthreads are then created
that locklessly and concurrently access foo.  Some snippets of this code
might look as follows:

        int foo;

        void initialize_foo(int initval, int nkthreads)
        {
                int i;

                foo = initval;
                ASSERT_EXCLUSIVE_ACCESS(foo);
                for (i = 0; i < nkthreads; i++)
                        kthread_run(access_foo_concurrently, ...);
        }

        /* Called from access_foo_concurrently(). */
        int update_foo(int newval)
        {
                int ret;

                ret = xchg(&foo, newval);
                do_something(newval);
                return ret;
        }

        /* Also called from access_foo_concurrently(). */
        int read_foo(void)
        {
                do_something_else();
                return READ_ONCE(foo);
        }

The initialize_foo() uses a plain C-language write to foo because there
are not supposed to be concurrent accesses during initialization.  The
ASSERT_EXCLUSIVE_ACCESS() allows KCSAN to flag buggy concurrent unmarked
reads, and the ASSERT_EXCLUSIVE_ACCESS() call further allows KCSAN to
flag buggy concurrent writes, even if:  (1) Those writes are marked or
(2) The kernel was built with CONFIG_KCSAN_ASSUME_PLAIN_WRITES_ATOMIC=y.


Checking Stress-Test Race Coverage
----------------------------------

When designing stress tests it is important to ensure that race conditions
of interest really do occur.  For example, consider the following code
fragment:

        int foo;

        int update_foo(int newval)
        {
                return xchg(&foo, newval);
        }

        int xor_shift_foo(int shift, int mask)
        {
                int old, new, newold;

                newold = data_race(foo); /* Checked by cmpxchg(). */
                do {
                        old = newold;
                        new = (old << shift) ^ mask;
                        newold = cmpxchg(&foo, old, new);
                } while (newold != old);
                return old;
        }

        int read_foo(void)
        {
                return READ_ONCE(foo);
        }

If it is possible for update_foo(), xor_shift_foo(), and read_foo() to be
invoked concurrently, the stress test should force this concurrency to
actually happen.  KCSAN can evaluate the stress test when the above code
is modified to read as follows:

        int foo;

        int update_foo(int newval)
        {
                ASSERT_EXCLUSIVE_ACCESS(foo);
                return xchg(&foo, newval);
        }

        int xor_shift_foo(int shift, int mask)
        {
                int old, new, newold;

                newold = data_race(foo); /* Checked by cmpxchg(). */
                do {
                        old = newold;
                        new = (old << shift) ^ mask;
                        ASSERT_EXCLUSIVE_ACCESS(foo);
                        newold = cmpxchg(&foo, old, new);
                } while (newold != old);
                return old;
        }


        int read_foo(void)
        {
                ASSERT_EXCLUSIVE_ACCESS(foo);
                return READ_ONCE(foo);
        }

If a given stress-test run does not result in KCSAN complaints from
each possible pair of ASSERT_EXCLUSIVE_ACCESS() invocations, the
stress test needs improvement.  If the stress test was to be evaluated
on a regular basis, it would be wise to place the above instances of
ASSERT_EXCLUSIVE_ACCESS() under #ifdef so that they did not result in
false positives when not evaluating the stress test.


REFERENCES
==========

[1] "Concurrency bugs should fear the big bad data-race detector (part 2)"
    https://lwn.net/Articles/816854/

[2] "The Kernel Concurrency Sanitizer"
    https://www.linuxfoundation.org/webinars/the-kernel-concurrency-sanitizer

[3] "Who's afraid of a big bad optimizing compiler?"
    https://lwn.net/Articles/793253/

Cheatsheet

Peios Kernel / Kernel development / Development tools / lkmm / docs

Literal include of tools/memory-model/Documentation/cheatsheet.txt.


                                  Prior Operation     Subsequent Operation
                                  ---------------  ---------------------------
                               C  Self  R  W  RMW  Self  R  W  DR  DW  RMW  SV
                              --  ----  -  -  ---  ----  -  -  --  --  ---  --

Relaxed store                        Y                                       Y
Relaxed load                         Y                          Y   Y        Y
Relaxed RMW operation                Y                          Y   Y        Y
rcu_dereference()                    Y                          Y   Y        Y
Successful *_acquire()               R                   Y  Y   Y   Y    Y   Y
Successful *_release()         C        Y  Y    Y     W                      Y
smp_rmb()                               Y       R        Y      Y        R
smp_wmb()                                  Y    W           Y       Y    W
smp_mb() & synchronize_rcu()  CP        Y  Y    Y        Y  Y   Y   Y    Y
Successful full non-void RMW  CP     Y  Y  Y    Y     Y  Y  Y   Y   Y    Y   Y
smp_mb__before_atomic()       CP        Y  Y    Y        a  a   a   a    Y
smp_mb__after_atomic()        CP        a  a    Y        Y  Y   Y   Y    Y


Key:    Relaxed:  A relaxed operation is either READ_ONCE(), WRITE_ONCE(),
                  a *_relaxed() RMW operation, an unsuccessful RMW
                  operation, a non-value-returning RMW operation such
                  as atomic_inc(), or one of the atomic*_read() and
                  atomic*_set() family of operations.
        C:        Ordering is cumulative
        P:        Ordering propagates
        R:        Read, for example, READ_ONCE(), or read portion of RMW
        W:        Write, for example, WRITE_ONCE(), or write portion of RMW
        Y:        Provides ordering
        a:        Provides ordering given intervening RMW atomic operation
        DR:       Dependent read (address dependency)
        DW:       Dependent write (address, data, or control dependency)
        RMW:      Atomic read-modify-write operation
        SELF:     Orders self, as opposed to accesses before and/or after
        SV:       Orders later accesses to the same variable

Control Dependencies

Peios Kernel / Kernel development / Development tools / lkmm / docs

Literal include of tools/memory-model/Documentation/control-dependencies.txt.


CONTROL DEPENDENCIES
====================

A major difficulty with control dependencies is that current compilers
do not support them.  One purpose of this document is therefore to
help you prevent your compiler from breaking your code.  However,
control dependencies also pose other challenges, which leads to the
second purpose of this document, namely to help you to avoid breaking
your own code, even in the absence of help from your compiler.

One such challenge is that control dependencies order only later stores.
Therefore, a load-load control dependency will not preserve ordering
unless a read memory barrier is provided.  Consider the following code:

        q = READ_ONCE(a);
        if (q)
                p = READ_ONCE(b);

This is not guaranteed to provide any ordering because some types of CPUs
are permitted to predict the result of the load from "b".  This prediction
can cause other CPUs to see this load as having happened before the load
from "a".  This means that an explicit read barrier is required, for example
as follows:

        q = READ_ONCE(a);
        if (q) {
                smp_rmb();
                p = READ_ONCE(b);
        }

However, stores are not speculated.  This means that ordering is
(usually) guaranteed for load-store control dependencies, as in the
following example:

        q = READ_ONCE(a);
        if (q)
                WRITE_ONCE(b, 1);

Control dependencies can pair with each other and with other types
of ordering.  But please note that neither the READ_ONCE() nor the
WRITE_ONCE() are optional.  Without the READ_ONCE(), the compiler might
fuse the load from "a" with other loads.  Without the WRITE_ONCE(),
the compiler might fuse the store to "b" with other stores.  Worse yet,
the compiler might convert the store into a load and a check followed
by a store, and this compiler-generated load would not be ordered by
the control dependency.

Furthermore, if the compiler is able to prove that the value of variable
"a" is always non-zero, it would be well within its rights to optimize
the original example by eliminating the "if" statement as follows:

        q = a;
        b = 1;  /* BUG: Compiler and CPU can both reorder!!! */

So don't leave out either the READ_ONCE() or the WRITE_ONCE().
In particular, although READ_ONCE() does force the compiler to emit a
load, it does *not* force the compiler to actually use the loaded value.

It is tempting to try use control dependencies to enforce ordering on
identical stores on both branches of the "if" statement as follows:

        q = READ_ONCE(a);
        if (q) {
                barrier();
                WRITE_ONCE(b, 1);
                do_something();
        } else {
                barrier();
                WRITE_ONCE(b, 1);
                do_something_else();
        }

Unfortunately, current compilers will transform this as follows at high
optimization levels:

        q = READ_ONCE(a);
        barrier();
        WRITE_ONCE(b, 1);  /* BUG: No ordering vs. load from a!!! */
        if (q) {
                /* WRITE_ONCE(b, 1); -- moved up, BUG!!! */
                do_something();
        } else {
                /* WRITE_ONCE(b, 1); -- moved up, BUG!!! */
                do_something_else();
        }

Now there is no conditional between the load from "a" and the store to
"b", which means that the CPU is within its rights to reorder them:  The
conditional is absolutely required, and must be present in the final
assembly code, after all of the compiler and link-time optimizations
have been applied.  Therefore, if you need ordering in this example,
you must use explicit memory ordering, for example, smp_store_release():

        q = READ_ONCE(a);
        if (q) {
                smp_store_release(&b, 1);
                do_something();
        } else {
                smp_store_release(&b, 1);
                do_something_else();
        }

Without explicit memory ordering, control-dependency-based ordering is
guaranteed only when the stores differ, for example:

        q = READ_ONCE(a);
        if (q) {
                WRITE_ONCE(b, 1);
                do_something();
        } else {
                WRITE_ONCE(b, 2);
                do_something_else();
        }

The initial READ_ONCE() is still required to prevent the compiler from
knowing too much about the value of "a".

But please note that you need to be careful what you do with the local
variable "q", otherwise the compiler might be able to guess the value
and again remove the conditional branch that is absolutely required to
preserve ordering.  For example:

        q = READ_ONCE(a);
        if (q % MAX) {
                WRITE_ONCE(b, 1);
                do_something();
        } else {
                WRITE_ONCE(b, 2);
                do_something_else();
        }

If MAX is compile-time defined to be 1, then the compiler knows that
(q % MAX) must be equal to zero, regardless of the value of "q".
The compiler is therefore within its rights to transform the above code
into the following:

        q = READ_ONCE(a);
        WRITE_ONCE(b, 2);
        do_something_else();

Given this transformation, the CPU is not required to respect the ordering
between the load from variable "a" and the store to variable "b".  It is
tempting to add a barrier(), but this does not help.  The conditional
is gone, and the barrier won't bring it back.  Therefore, if you need
to relying on control dependencies to produce this ordering, you should
make sure that MAX is greater than one, perhaps as follows:

        q = READ_ONCE(a);
        BUILD_BUG_ON(MAX <= 1); /* Order load from a with store to b. */
        if (q % MAX) {
                WRITE_ONCE(b, 1);
                do_something();
        } else {
                WRITE_ONCE(b, 2);
                do_something_else();
        }

Please note once again that each leg of the "if" statement absolutely
must store different values to "b".  As in previous examples, if the two
values were identical, the compiler could pull this store outside of the
"if" statement, destroying the control dependency's ordering properties.

You must also be careful avoid relying too much on boolean short-circuit
evaluation.  Consider this example:

        q = READ_ONCE(a);
        if (q || 1 > 0)
                WRITE_ONCE(b, 1);

Because the first condition cannot fault and the second condition is
always true, the compiler can transform this example as follows, again
destroying the control dependency's ordering:

        q = READ_ONCE(a);
        WRITE_ONCE(b, 1);

This is yet another example showing the importance of preventing the
compiler from out-guessing your code.  Again, although READ_ONCE() really
does force the compiler to emit code for a given load, the compiler is
within its rights to discard the loaded value.

In addition, control dependencies apply only to the then-clause and
else-clause of the "if" statement in question.  In particular, they do
not necessarily order the code following the entire "if" statement:

        q = READ_ONCE(a);
        if (q) {
                WRITE_ONCE(b, 1);
        } else {
                WRITE_ONCE(b, 2);
        }
        WRITE_ONCE(c, 1);  /* BUG: No ordering against the read from "a". */

It is tempting to argue that there in fact is ordering because the
compiler cannot reorder volatile accesses and also cannot reorder
the writes to "b" with the condition.  Unfortunately for this line
of reasoning, the compiler might compile the two writes to "b" as
conditional-move instructions, as in this fanciful pseudo-assembly
language:

        ld r1,a
        cmp r1,$0
        cmov,ne r4,$1
        cmov,eq r4,$2
        st r4,b
        st $1,c

The control dependencies would then extend only to the pair of cmov
instructions and the store depending on them.  This means that a weakly
ordered CPU would have no dependency of any sort between the load from
"a" and the store to "c".  In short, control dependencies provide ordering
only to the stores in the then-clause and else-clause of the "if" statement
in question (including functions invoked by those two clauses), and not
to code following that "if" statement.


In summary:

  (*) Control dependencies can order prior loads against later stores.
      However, they do *not* guarantee any other sort of ordering:
      Not prior loads against later loads, nor prior stores against
      later anything.  If you need these other forms of ordering, use
      smp_load_acquire(), smp_store_release(), or, in the case of prior
      stores and later loads, smp_mb().

  (*) If both legs of the "if" statement contain identical stores to
      the same variable, then you must explicitly order those stores,
      either by preceding both of them with smp_mb() or by using
      smp_store_release().  Please note that it is *not* sufficient to use
      barrier() at beginning and end of each leg of the "if" statement
      because, as shown by the example above, optimizing compilers can
      destroy the control dependency while respecting the letter of the
      barrier() law.

  (*) Control dependencies require at least one run-time conditional
      between the prior load and the subsequent store, and this
      conditional must involve the prior load.  If the compiler is able
      to optimize the conditional away, it will have also optimized
      away the ordering.  Careful use of READ_ONCE() and WRITE_ONCE()
      can help to preserve the needed conditional.

  (*) Control dependencies require that the compiler avoid reordering the
      dependency into nonexistence.  Careful use of READ_ONCE() or
      atomic{,64}_read() can help to preserve your control dependency.

  (*) Control dependencies apply only to the then-clause and else-clause
      of the "if" statement containing the control dependency, including
      any functions that these two clauses call.  Control dependencies
      do *not* apply to code beyond the end of that "if" statement.

  (*) Control dependencies pair normally with other types of barriers.

  (*) Control dependencies do *not* provide multicopy atomicity.  If you
      need all the CPUs to agree on the ordering of a given store against
      all other accesses, use smp_mb().

  (*) Compilers do not understand control dependencies.  It is therefore
      your job to ensure that they do not break your code.

Explanation

Peios Kernel / Kernel development / Development tools / lkmm / docs

Literal include of tools/memory-model/Documentation/explanation.txt.


Explanation of the Linux-Kernel Memory Consistency Model
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Author: Alan Stern <stern@rowland.harvard.edu>
:Created: October 2017

.. Contents

  1. INTRODUCTION
  2. BACKGROUND
  3. A SIMPLE EXAMPLE
  4. A SELECTION OF MEMORY MODELS
  5. ORDERING AND CYCLES
  6. EVENTS
  7. THE PROGRAM ORDER RELATION: po AND po-loc
  8. A WARNING
  9. DEPENDENCY RELATIONS: data, addr, and ctrl
  10. THE READS-FROM RELATION: rf, rfi, and rfe
  11. CACHE COHERENCE AND THE COHERENCE ORDER RELATION: co, coi, and coe
  12. THE FROM-READS RELATION: fr, fri, and fre
  13. AN OPERATIONAL MODEL
  14. PROPAGATION ORDER RELATION: cumul-fence
  15. DERIVATION OF THE LKMM FROM THE OPERATIONAL MODEL
  16. SEQUENTIAL CONSISTENCY PER VARIABLE
  17. ATOMIC UPDATES: rmw
  18. THE PRESERVED PROGRAM ORDER RELATION: ppo
  19. AND THEN THERE WAS ALPHA
  20. THE HAPPENS-BEFORE RELATION: hb
  21. THE PROPAGATES-BEFORE RELATION: pb
  22. RCU RELATIONS: rcu-link, rcu-gp, rcu-rscsi, rcu-order, rcu-fence, and rb
  23. SRCU READ-SIDE CRITICAL SECTIONS
  24. LOCKING
  25. PLAIN ACCESSES AND DATA RACES
  26. ODDS AND ENDS



INTRODUCTION
------------

The Linux-kernel memory consistency model (LKMM) is rather complex and
obscure.  This is particularly evident if you read through the
linux-kernel.bell and linux-kernel.cat files that make up the formal
version of the model; they are extremely terse and their meanings are
far from clear.

This document describes the ideas underlying the LKMM.  It is meant
for people who want to understand how the model was designed.  It does
not go into the details of the code in the .bell and .cat files;
rather, it explains in English what the code expresses symbolically.

Sections 2 (BACKGROUND) through 5 (ORDERING AND CYCLES) are aimed
toward beginners; they explain what memory consistency models are and
the basic notions shared by all such models.  People already familiar
with these concepts can skim or skip over them.  Sections 6 (EVENTS)
through 12 (THE FROM_READS RELATION) describe the fundamental
relations used in many models.  Starting in Section 13 (AN OPERATIONAL
MODEL), the workings of the LKMM itself are covered.

Warning: The code examples in this document are not written in the
proper format for litmus tests.  They don't include a header line, the
initializations are not enclosed in braces, the global variables are
not passed by pointers, and they don't have an "exists" clause at the
end.  Converting them to the right format is left as an exercise for
the reader.


BACKGROUND
----------

A memory consistency model (or just memory model, for short) is
something which predicts, given a piece of computer code running on a
particular kind of system, what values may be obtained by the code's
load instructions.  The LKMM makes these predictions for code running
as part of the Linux kernel.

In practice, people tend to use memory models the other way around.
That is, given a piece of code and a collection of values specified
for the loads, the model will predict whether it is possible for the
code to run in such a way that the loads will indeed obtain the
specified values.  Of course, this is just another way of expressing
the same idea.

For code running on a uniprocessor system, the predictions are easy:
Each load instruction must obtain the value written by the most recent
store instruction accessing the same location (we ignore complicating
factors such as DMA and mixed-size accesses.)  But on multiprocessor
systems, with multiple CPUs making concurrent accesses to shared
memory locations, things aren't so simple.

Different architectures have differing memory models, and the Linux
kernel supports a variety of architectures.  The LKMM has to be fairly
permissive, in the sense that any behavior allowed by one of these
architectures also has to be allowed by the LKMM.


A SIMPLE EXAMPLE
----------------

Here is a simple example to illustrate the basic concepts.  Consider
some code running as part of a device driver for an input device.  The
driver might contain an interrupt handler which collects data from the
device, stores it in a buffer, and sets a flag to indicate the buffer
is full.  Running concurrently on a different CPU might be a part of
the driver code being executed by a process in the midst of a read(2)
system call.  This code tests the flag to see whether the buffer is
ready, and if it is, copies the data back to userspace.  The buffer
and the flag are memory locations shared between the two CPUs.

We can abstract out the important pieces of the driver code as follows
(the reason for using WRITE_ONCE() and READ_ONCE() instead of simple
assignment statements is discussed later):

        int buf = 0, flag = 0;

        P0()
        {
                WRITE_ONCE(buf, 1);
                WRITE_ONCE(flag, 1);
        }

        P1()
        {
                int r1;
                int r2 = 0;

                r1 = READ_ONCE(flag);
                if (r1)
                        r2 = READ_ONCE(buf);
        }

Here the P0() function represents the interrupt handler running on one
CPU and P1() represents the read() routine running on another.  The
value 1 stored in buf represents input data collected from the device.
Thus, P0 stores the data in buf and then sets flag.  Meanwhile, P1
reads flag into the private variable r1, and if it is set, reads the
data from buf into a second private variable r2 for copying to
userspace.  (Presumably if flag is not set then the driver will wait a
while and try again.)

This pattern of memory accesses, where one CPU stores values to two
shared memory locations and another CPU loads from those locations in
the opposite order, is widely known as the "Message Passing" or MP
pattern.  It is typical of memory access patterns in the kernel.

Please note that this example code is a simplified abstraction.  Real
buffers are usually larger than a single integer, real device drivers
usually use sleep and wakeup mechanisms rather than polling for I/O
completion, and real code generally doesn't bother to copy values into
private variables before using them.  All that is beside the point;
the idea here is simply to illustrate the overall pattern of memory
accesses by the CPUs.

A memory model will predict what values P1 might obtain for its loads
from flag and buf, or equivalently, what values r1 and r2 might end up
with after the code has finished running.

Some predictions are trivial.  For instance, no sane memory model would
predict that r1 = 42 or r2 = -7, because neither of those values ever
gets stored in flag or buf.

Some nontrivial predictions are nonetheless quite simple.  For
instance, P1 might run entirely before P0 begins, in which case r1 and
r2 will both be 0 at the end.  Or P0 might run entirely before P1
begins, in which case r1 and r2 will both be 1.

The interesting predictions concern what might happen when the two
routines run concurrently.  One possibility is that P1 runs after P0's
store to buf but before the store to flag.  In this case, r1 and r2
will again both be 0.  (If P1 had been designed to read buf
unconditionally then we would instead have r1 = 0 and r2 = 1.)

However, the most interesting possibility is where r1 = 1 and r2 = 0.
If this were to occur it would mean the driver contains a bug, because
incorrect data would get sent to the user: 0 instead of 1.  As it
happens, the LKMM does predict this outcome can occur, and the example
driver code shown above is indeed buggy.


A SELECTION OF MEMORY MODELS
----------------------------

The first widely cited memory model, and the simplest to understand,
is Sequential Consistency.  According to this model, systems behave as
if each CPU executed its instructions in order but with unspecified
timing.  In other words, the instructions from the various CPUs get
interleaved in a nondeterministic way, always according to some single
global order that agrees with the order of the instructions in the
program source for each CPU.  The model says that the value obtained
by each load is simply the value written by the most recently executed
store to the same memory location, from any CPU.

For the MP example code shown above, Sequential Consistency predicts
that the undesired result r1 = 1, r2 = 0 cannot occur.  The reasoning
goes like this:

        Since r1 = 1, P0 must store 1 to flag before P1 loads 1 from
        it, as loads can obtain values only from earlier stores.

        P1 loads from flag before loading from buf, since CPUs execute
        their instructions in order.

        P1 must load 0 from buf before P0 stores 1 to it; otherwise r2
        would be 1 since a load obtains its value from the most recent
        store to the same address.

        P0 stores 1 to buf before storing 1 to flag, since it executes
        its instructions in order.

        Since an instruction (in this case, P0's store to flag) cannot
        execute before itself, the specified outcome is impossible.

However, real computer hardware almost never follows the Sequential
Consistency memory model; doing so would rule out too many valuable
performance optimizations.  On ARM and PowerPC architectures, for
instance, the MP example code really does sometimes yield r1 = 1 and
r2 = 0.

x86 and SPARC follow yet a different memory model: TSO (Total Store
Ordering).  This model predicts that the undesired outcome for the MP
pattern cannot occur, but in other respects it differs from Sequential
Consistency.  One example is the Store Buffer (SB) pattern, in which
each CPU stores to its own shared location and then loads from the
other CPU's location:

        int x = 0, y = 0;

        P0()
        {
                int r0;

                WRITE_ONCE(x, 1);
                r0 = READ_ONCE(y);
        }

        P1()
        {
                int r1;

                WRITE_ONCE(y, 1);
                r1 = READ_ONCE(x);
        }

Sequential Consistency predicts that the outcome r0 = 0, r1 = 0 is
impossible.  (Exercise: Figure out the reasoning.)  But TSO allows
this outcome to occur, and in fact it does sometimes occur on x86 and
SPARC systems.

The LKMM was inspired by the memory models followed by PowerPC, ARM,
x86, Alpha, and other architectures.  However, it is different in
detail from each of them.


ORDERING AND CYCLES
-------------------

Memory models are all about ordering.  Often this is temporal ordering
(i.e., the order in which certain events occur) but it doesn't have to
be; consider for example the order of instructions in a program's
source code.  We saw above that Sequential Consistency makes an
important assumption that CPUs execute instructions in the same order
as those instructions occur in the code, and there are many other
instances of ordering playing central roles in memory models.

The counterpart to ordering is a cycle.  Ordering rules out cycles:
It's not possible to have X ordered before Y, Y ordered before Z, and
Z ordered before X, because this would mean that X is ordered before
itself.  The analysis of the MP example under Sequential Consistency
involved just such an impossible cycle:

        W: P0 stores 1 to flag   executes before
        X: P1 loads 1 from flag  executes before
        Y: P1 loads 0 from buf   executes before
        Z: P0 stores 1 to buf    executes before
        W: P0 stores 1 to flag.

In short, if a memory model requires certain accesses to be ordered,
and a certain outcome for the loads in a piece of code can happen only
if those accesses would form a cycle, then the memory model predicts
that outcome cannot occur.

The LKMM is defined largely in terms of cycles, as we will see.


EVENTS
------

The LKMM does not work directly with the C statements that make up
kernel source code.  Instead it considers the effects of those
statements in a more abstract form, namely, events.  The model
includes three types of events:

        Read events correspond to loads from shared memory, such as
        calls to READ_ONCE(), smp_load_acquire(), or
        rcu_dereference().

        Write events correspond to stores to shared memory, such as
        calls to WRITE_ONCE(), smp_store_release(), or atomic_set().

        Fence events correspond to memory barriers (also known as
        fences), such as calls to smp_rmb() or rcu_read_lock().

These categories are not exclusive; a read or write event can also be
a fence.  This happens with functions like smp_load_acquire() or
spin_lock().  However, no single event can be both a read and a write.
Atomic read-modify-write accesses, such as atomic_inc() or xchg(),
correspond to a pair of events: a read followed by a write.  (The
write event is omitted for executions where it doesn't occur, such as
a cmpxchg() where the comparison fails.)

Other parts of the code, those which do not involve interaction with
shared memory, do not give rise to events.  Thus, arithmetic and
logical computations, control-flow instructions, or accesses to
private memory or CPU registers are not of central interest to the
memory model.  They only affect the model's predictions indirectly.
For example, an arithmetic computation might determine the value that
gets stored to a shared memory location (or in the case of an array
index, the address where the value gets stored), but the memory model
is concerned only with the store itself -- its value and its address
-- not the computation leading up to it.

Events in the LKMM can be linked by various relations, which we will
describe in the following sections.  The memory model requires certain
of these relations to be orderings, that is, it requires them not to
have any cycles.


THE PROGRAM ORDER RELATION: po AND po-loc
-----------------------------------------

The most important relation between events is program order (po).  You
can think of it as the order in which statements occur in the source
code after branches are taken into account and loops have been
unrolled.  A better description might be the order in which
instructions are presented to a CPU's execution unit.  Thus, we say
that X is po-before Y (written as "X ->po Y" in formulas) if X occurs
before Y in the instruction stream.

This is inherently a single-CPU relation; two instructions executing
on different CPUs are never linked by po.  Also, it is by definition
an ordering so it cannot have any cycles.

po-loc is a sub-relation of po.  It links two memory accesses when the
first comes before the second in program order and they access the
same memory location (the "-loc" suffix).

Although this may seem straightforward, there is one subtle aspect to
program order we need to explain.  The LKMM was inspired by low-level
architectural memory models which describe the behavior of machine
code, and it retains their outlook to a considerable extent.  The
read, write, and fence events used by the model are close in spirit to
individual machine instructions.  Nevertheless, the LKMM describes
kernel code written in C, and the mapping from C to machine code can
be extremely complex.

Optimizing compilers have great freedom in the way they translate
source code to object code.  They are allowed to apply transformations
that add memory accesses, eliminate accesses, combine them, split them
into pieces, or move them around.  The use of READ_ONCE(), WRITE_ONCE(),
or one of the other atomic or synchronization primitives prevents a
large number of compiler optimizations.  In particular, it is guaranteed
that the compiler will not remove such accesses from the generated code
(unless it can prove the accesses will never be executed), it will not
change the order in which they occur in the code (within limits imposed
by the C standard), and it will not introduce extraneous accesses.

The MP and SB examples above used READ_ONCE() and WRITE_ONCE() rather
than ordinary memory accesses.  Thanks to this usage, we can be certain
that in the MP example, the compiler won't reorder P0's write event to
buf and P0's write event to flag, and similarly for the other shared
memory accesses in the examples.

Since private variables are not shared between CPUs, they can be
accessed normally without READ_ONCE() or WRITE_ONCE().  In fact, they
need not even be stored in normal memory at all -- in principle a
private variable could be stored in a CPU register (hence the convention
that these variables have names starting with the letter 'r').


A WARNING
---------

The protections provided by READ_ONCE(), WRITE_ONCE(), and others are
not perfect; and under some circumstances it is possible for the
compiler to undermine the memory model.  Here is an example.  Suppose
both branches of an "if" statement store the same value to the same
location:

        r1 = READ_ONCE(x);
        if (r1) {
                WRITE_ONCE(y, 2);
                ...  /* do something */
        } else {
                WRITE_ONCE(y, 2);
                ...  /* do something else */
        }

For this code, the LKMM predicts that the load from x will always be
executed before either of the stores to y.  However, a compiler could
lift the stores out of the conditional, transforming the code into
something resembling:

        r1 = READ_ONCE(x);
        WRITE_ONCE(y, 2);
        if (r1) {
                ...  /* do something */
        } else {
                ...  /* do something else */
        }

Given this version of the code, the LKMM would predict that the load
from x could be executed after the store to y.  Thus, the memory
model's original prediction could be invalidated by the compiler.

Another issue arises from the fact that in C, arguments to many
operators and function calls can be evaluated in any order.  For
example:

        r1 = f(5) + g(6);

The object code might call f(5) either before or after g(6); the
memory model cannot assume there is a fixed program order relation
between them.  (In fact, if the function calls are inlined then the
compiler might even interleave their object code.)


DEPENDENCY RELATIONS: data, addr, and ctrl
------------------------------------------

We say that two events are linked by a dependency relation when the
execution of the second event depends in some way on a value obtained
from memory by the first.  The first event must be a read, and the
value it obtains must somehow affect what the second event does.
There are three kinds of dependencies: data, address (addr), and
control (ctrl).

A read and a write event are linked by a data dependency if the value
obtained by the read affects the value stored by the write.  As a very
simple example:

        int x, y;

        r1 = READ_ONCE(x);
        WRITE_ONCE(y, r1 + 5);

The value stored by the WRITE_ONCE obviously depends on the value
loaded by the READ_ONCE.  Such dependencies can wind through
arbitrarily complicated computations, and a write can depend on the
values of multiple reads.

A read event and another memory access event are linked by an address
dependency if the value obtained by the read affects the location
accessed by the other event.  The second event can be either a read or
a write.  Here's another simple example:

        int a[20];
        int i;

        r1 = READ_ONCE(i);
        r2 = READ_ONCE(a[r1]);

Here the location accessed by the second READ_ONCE() depends on the
index value loaded by the first.  Pointer indirection also gives rise
to address dependencies, since the address of a location accessed
through a pointer will depend on the value read earlier from that
pointer.

Finally, a read event X and a write event Y are linked by a control
dependency if Y syntactically lies within an arm of an if statement and
X affects the evaluation of the if condition via a data or address
dependency (or similarly for a switch statement).  Simple example:

        int x, y;

        r1 = READ_ONCE(x);
        if (r1)
                WRITE_ONCE(y, 1984);

Execution of the WRITE_ONCE() is controlled by a conditional expression
which depends on the value obtained by the READ_ONCE(); hence there is
a control dependency from the load to the store.

It should be pretty obvious that events can only depend on reads that
come earlier in program order.  Symbolically, if we have R ->data X,
R ->addr X, or R ->ctrl X (where R is a read event), then we must also
have R ->po X.  It wouldn't make sense for a computation to depend
somehow on a value that doesn't get loaded from shared memory until
later in the code!

Here's a trick question: When is a dependency not a dependency?  Answer:
When it is purely syntactic rather than semantic.  We say a dependency
between two accesses is purely syntactic if the second access doesn't
actually depend on the result of the first.  Here is a trivial example:

        r1 = READ_ONCE(x);
        WRITE_ONCE(y, r1 * 0);

There appears to be a data dependency from the load of x to the store
of y, since the value to be stored is computed from the value that was
loaded.  But in fact, the value stored does not really depend on
anything since it will always be 0.  Thus the data dependency is only
syntactic (it appears to exist in the code) but not semantic (the
second access will always be the same, regardless of the value of the
first access).  Given code like this, a compiler could simply discard
the value returned by the load from x, which would certainly destroy
any dependency.  (The compiler is not permitted to eliminate entirely
the load generated for a READ_ONCE() -- that's one of the nice
properties of READ_ONCE() -- but it is allowed to ignore the load's
value.)

It's natural to object that no one in their right mind would write
code like the above.  However, macro expansions can easily give rise
to this sort of thing, in ways that often are not apparent to the
programmer.

Another mechanism that can lead to purely syntactic dependencies is
related to the notion of "undefined behavior".  Certain program
behaviors are called "undefined" in the C language specification,
which means that when they occur there are no guarantees at all about
the outcome.  Consider the following example:

        int a[1];
        int i;

        r1 = READ_ONCE(i);
        r2 = READ_ONCE(a[r1]);

Access beyond the end or before the beginning of an array is one kind
of undefined behavior.  Therefore the compiler doesn't have to worry
about what will happen if r1 is nonzero, and it can assume that r1
will always be zero regardless of the value actually loaded from i.
(If the assumption turns out to be wrong the resulting behavior will
be undefined anyway, so the compiler doesn't care!)  Thus the value
from the load can be discarded, breaking the address dependency.

The LKMM is unaware that purely syntactic dependencies are different
from semantic dependencies and therefore mistakenly predicts that the
accesses in the two examples above will be ordered.  This is another
example of how the compiler can undermine the memory model.  Be warned.


THE READS-FROM RELATION: rf, rfi, and rfe
-----------------------------------------

The reads-from relation (rf) links a write event to a read event when
the value loaded by the read is the value that was stored by the
write.  In colloquial terms, the load "reads from" the store.  We
write W ->rf R to indicate that the load R reads from the store W.  We
further distinguish the cases where the load and the store occur on
the same CPU (internal reads-from, or rfi) and where they occur on
different CPUs (external reads-from, or rfe).

For our purposes, a memory location's initial value is treated as
though it had been written there by an imaginary initial store that
executes on a separate CPU before the main program runs.

Usage of the rf relation implicitly assumes that loads will always
read from a single store.  It doesn't apply properly in the presence
of load-tearing, where a load obtains some of its bits from one store
and some of them from another store.  Fortunately, use of READ_ONCE()
and WRITE_ONCE() will prevent load-tearing; it's not possible to have:

        int x = 0;

        P0()
        {
                WRITE_ONCE(x, 0x1234);
        }

        P1()
        {
                int r1;

                r1 = READ_ONCE(x);
        }

and end up with r1 = 0x1200 (partly from x's initial value and partly
from the value stored by P0).

On the other hand, load-tearing is unavoidable when mixed-size
accesses are used.  Consider this example:

        union {
                u32     w;
                u16     h[2];
        } x;

        P0()
        {
                WRITE_ONCE(x.h[0], 0x1234);
                WRITE_ONCE(x.h[1], 0x5678);
        }

        P1()
        {
                int r1;

                r1 = READ_ONCE(x.w);
        }

If r1 = 0x56781234 (little-endian!) at the end, then P1 must have read
from both of P0's stores.  It is possible to handle mixed-size and
unaligned accesses in a memory model, but the LKMM currently does not
attempt to do so.  It requires all accesses to be properly aligned and
of the location's actual size.


CACHE COHERENCE AND THE COHERENCE ORDER RELATION: co, coi, and coe
------------------------------------------------------------------

Cache coherence is a general principle requiring that in a
multi-processor system, the CPUs must share a consistent view of the
memory contents.  Specifically, it requires that for each location in
shared memory, the stores to that location must form a single global
ordering which all the CPUs agree on (the coherence order), and this
ordering must be consistent with the program order for accesses to
that location.

To put it another way, for any variable x, the coherence order (co) of
the stores to x is simply the order in which the stores overwrite one
another.  The imaginary store which establishes x's initial value
comes first in the coherence order; the store which directly
overwrites the initial value comes second; the store which overwrites
that value comes third, and so on.

You can think of the coherence order as being the order in which the
stores reach x's location in memory (or if you prefer a more
hardware-centric view, the order in which the stores get written to
x's cache line).  We write W ->co W' if W comes before W' in the
coherence order, that is, if the value stored by W gets overwritten,
directly or indirectly, by the value stored by W'.

Coherence order is required to be consistent with program order.  This
requirement takes the form of four coherency rules:

        Write-write coherence: If W ->po-loc W' (i.e., W comes before
        W' in program order and they access the same location), where W
        and W' are two stores, then W ->co W'.

        Write-read coherence: If W ->po-loc R, where W is a store and R
        is a load, then R must read from W or from some other store
        which comes after W in the coherence order.

        Read-write coherence: If R ->po-loc W, where R is a load and W
        is a store, then the store which R reads from must come before
        W in the coherence order.

        Read-read coherence: If R ->po-loc R', where R and R' are two
        loads, then either they read from the same store or else the
        store read by R comes before the store read by R' in the
        coherence order.

This is sometimes referred to as sequential consistency per variable,
because it means that the accesses to any single memory location obey
the rules of the Sequential Consistency memory model.  (According to
Wikipedia, sequential consistency per variable and cache coherence
mean the same thing except that cache coherence includes an extra
requirement that every store eventually becomes visible to every CPU.)

Any reasonable memory model will include cache coherence.  Indeed, our
expectation of cache coherence is so deeply ingrained that violations
of its requirements look more like hardware bugs than programming
errors:

        int x;

        P0()
        {
                WRITE_ONCE(x, 17);
                WRITE_ONCE(x, 23);
        }

If the final value stored in x after this code ran was 17, you would
think your computer was broken.  It would be a violation of the
write-write coherence rule: Since the store of 23 comes later in
program order, it must also come later in x's coherence order and
thus must overwrite the store of 17.

        int x = 0;

        P0()
        {
                int r1;

                r1 = READ_ONCE(x);
                WRITE_ONCE(x, 666);
        }

If r1 = 666 at the end, this would violate the read-write coherence
rule: The READ_ONCE() load comes before the WRITE_ONCE() store in
program order, so it must not read from that store but rather from one
coming earlier in the coherence order (in this case, x's initial
value).

        int x = 0;

        P0()
        {
                WRITE_ONCE(x, 5);
        }

        P1()
        {
                int r1, r2;

                r1 = READ_ONCE(x);
                r2 = READ_ONCE(x);
        }

If r1 = 5 (reading from P0's store) and r2 = 0 (reading from the
imaginary store which establishes x's initial value) at the end, this
would violate the read-read coherence rule: The r1 load comes before
the r2 load in program order, so it must not read from a store that
comes later in the coherence order.

(As a minor curiosity, if this code had used normal loads instead of
READ_ONCE() in P1, on Itanium it sometimes could end up with r1 = 5
and r2 = 0!  This results from parallel execution of the operations
encoded in Itanium's Very-Long-Instruction-Word format, and it is yet
another motivation for using READ_ONCE() when accessing shared memory
locations.)

Just like the po relation, co is inherently an ordering -- it is not
possible for a store to directly or indirectly overwrite itself!  And
just like with the rf relation, we distinguish between stores that
occur on the same CPU (internal coherence order, or coi) and stores
that occur on different CPUs (external coherence order, or coe).

On the other hand, stores to different memory locations are never
related by co, just as instructions on different CPUs are never
related by po.  Coherence order is strictly per-location, or if you
prefer, each location has its own independent coherence order.


THE FROM-READS RELATION: fr, fri, and fre
-----------------------------------------

The from-reads relation (fr) can be a little difficult for people to
grok.  It describes the situation where a load reads a value that gets
overwritten by a store.  In other words, we have R ->fr W when the
value that R reads is overwritten (directly or indirectly) by W, or
equivalently, when R reads from a store which comes earlier than W in
the coherence order.

For example:

        int x = 0;

        P0()
        {
                int r1;

                r1 = READ_ONCE(x);
                WRITE_ONCE(x, 2);
        }

The value loaded from x will be 0 (assuming cache coherence!), and it
gets overwritten by the value 2.  Thus there is an fr link from the
READ_ONCE() to the WRITE_ONCE().  If the code contained any later
stores to x, there would also be fr links from the READ_ONCE() to
them.

As with rf, rfi, and rfe, we subdivide the fr relation into fri (when
the load and the store are on the same CPU) and fre (when they are on
different CPUs).

Note that the fr relation is determined entirely by the rf and co
relations; it is not independent.  Given a read event R and a write
event W for the same location, we will have R ->fr W if and only if
the write which R reads from is co-before W.  In symbols,

        (R ->fr W) := (there exists W' with W' ->rf R and W' ->co W).


AN OPERATIONAL MODEL
--------------------

The LKMM is based on various operational memory models, meaning that
the models arise from an abstract view of how a computer system
operates.  Here are the main ideas, as incorporated into the LKMM.

The system as a whole is divided into the CPUs and a memory subsystem.
The CPUs are responsible for executing instructions (not necessarily
in program order), and they communicate with the memory subsystem.
For the most part, executing an instruction requires a CPU to perform
only internal operations.  However, loads, stores, and fences involve
more.

When CPU C executes a store instruction, it tells the memory subsystem
to store a certain value at a certain location.  The memory subsystem
propagates the store to all the other CPUs as well as to RAM.  (As a
special case, we say that the store propagates to its own CPU at the
time it is executed.)  The memory subsystem also determines where the
store falls in the location's coherence order.  In particular, it must
arrange for the store to be co-later than (i.e., to overwrite) any
other store to the same location which has already propagated to CPU C.

When a CPU executes a load instruction R, it first checks to see
whether there are any as-yet unexecuted store instructions, for the
same location, that come before R in program order.  If there are, it
uses the value of the po-latest such store as the value obtained by R,
and we say that the store's value is forwarded to R.  Otherwise, the
CPU asks the memory subsystem for the value to load and we say that R
is satisfied from memory.  The memory subsystem hands back the value
of the co-latest store to the location in question which has already
propagated to that CPU.

(In fact, the picture needs to be a little more complicated than this.
CPUs have local caches, and propagating a store to a CPU really means
propagating it to the CPU's local cache.  A local cache can take some
time to process the stores that it receives, and a store can't be used
to satisfy one of the CPU's loads until it has been processed.  On
most architectures, the local caches process stores in
First-In-First-Out order, and consequently the processing delay
doesn't matter for the memory model.  But on Alpha, the local caches
have a partitioned design that results in non-FIFO behavior.  We will
discuss this in more detail later.)

Note that load instructions may be executed speculatively and may be
restarted under certain circumstances.  The memory model ignores these
premature executions; we simply say that the load executes at the
final time it is forwarded or satisfied.

Executing a fence (or memory barrier) instruction doesn't require a
CPU to do anything special other than informing the memory subsystem
about the fence.  However, fences do constrain the way CPUs and the
memory subsystem handle other instructions, in two respects.

First, a fence forces the CPU to execute various instructions in
program order.  Exactly which instructions are ordered depends on the
type of fence:

        Strong fences, including smp_mb() and synchronize_rcu(), force
        the CPU to execute all po-earlier instructions before any
        po-later instructions;

        smp_rmb() forces the CPU to execute all po-earlier loads
        before any po-later loads;

        smp_wmb() forces the CPU to execute all po-earlier stores
        before any po-later stores;

        Acquire fences, such as smp_load_acquire(), force the CPU to
        execute the load associated with the fence (e.g., the load
        part of an smp_load_acquire()) before any po-later
        instructions;

        Release fences, such as smp_store_release(), force the CPU to
        execute all po-earlier instructions before the store
        associated with the fence (e.g., the store part of an
        smp_store_release()).

Second, some types of fence affect the way the memory subsystem
propagates stores.  When a fence instruction is executed on CPU C:

        For each other CPU C', smp_wmb() forces all po-earlier stores
        on C to propagate to C' before any po-later stores do.

        For each other CPU C', any store which propagates to C before
        a release fence is executed (including all po-earlier
        stores executed on C) is forced to propagate to C' before the
        store associated with the release fence does.

        Any store which propagates to C before a strong fence is
        executed (including all po-earlier stores on C) is forced to
        propagate to all other CPUs before any instructions po-after
        the strong fence are executed on C.

The propagation ordering enforced by release fences and strong fences
affects stores from other CPUs that propagate to CPU C before the
fence is executed, as well as stores that are executed on C before the
fence.  We describe this property by saying that release fences and
strong fences are A-cumulative.  By contrast, smp_wmb() fences are not
A-cumulative; they only affect the propagation of stores that are
executed on C before the fence (i.e., those which precede the fence in
program order).

rcu_read_lock(), rcu_read_unlock(), and synchronize_rcu() fences have
other properties which we discuss later.


PROPAGATION ORDER RELATION: cumul-fence
---------------------------------------

The fences which affect propagation order (i.e., strong, release, and
smp_wmb() fences) are collectively referred to as cumul-fences, even
though smp_wmb() isn't A-cumulative.  The cumul-fence relation is
defined to link memory access events E and F whenever:

        E and F are both stores on the same CPU and an smp_wmb() fence
        event occurs between them in program order; or

        F is a release fence and some X comes before F in program order,
        where either X = E or else E ->rf X; or

        A strong fence event occurs between some X and F in program
        order, where either X = E or else E ->rf X.

The operational model requires that whenever W and W' are both stores
and W ->cumul-fence W', then W must propagate to any given CPU
before W' does.  However, for different CPUs C and C', it does not
require W to propagate to C before W' propagates to C'.


DERIVATION OF THE LKMM FROM THE OPERATIONAL MODEL
-------------------------------------------------

The LKMM is derived from the restrictions imposed by the design
outlined above.  These restrictions involve the necessity of
maintaining cache coherence and the fact that a CPU can't operate on a
value before it knows what that value is, among other things.

The formal version of the LKMM is defined by six requirements, or
axioms:

        Sequential consistency per variable: This requires that the
        system obey the four coherency rules.

        Atomicity: This requires that atomic read-modify-write
        operations really are atomic, that is, no other stores can
        sneak into the middle of such an update.

        Happens-before: This requires that certain instructions are
        executed in a specific order.

        Propagation: This requires that certain stores propagate to
        CPUs and to RAM in a specific order.

        Rcu: This requires that RCU read-side critical sections and
        grace periods obey the rules of RCU, in particular, the
        Grace-Period Guarantee.

        Plain-coherence: This requires that plain memory accesses
        (those not using READ_ONCE(), WRITE_ONCE(), etc.) must obey
        the operational model's rules regarding cache coherence.

The first and second are quite common; they can be found in many
memory models (such as those for C11/C++11).  The "happens-before" and
"propagation" axioms have analogs in other memory models as well.  The
"rcu" and "plain-coherence" axioms are specific to the LKMM.

Each of these axioms is discussed below.


SEQUENTIAL CONSISTENCY PER VARIABLE
-----------------------------------

According to the principle of cache coherence, the stores to any fixed
shared location in memory form a global ordering.  We can imagine
inserting the loads from that location into this ordering, by placing
each load between the store that it reads from and the following
store.  This leaves the relative positions of loads that read from the
same store unspecified; let's say they are inserted in program order,
first for CPU 0, then CPU 1, etc.

You can check that the four coherency rules imply that the rf, co, fr,
and po-loc relations agree with this global ordering; in other words,
whenever we have X ->rf Y or X ->co Y or X ->fr Y or X ->po-loc Y, the
X event comes before the Y event in the global ordering.  The LKMM's
"coherence" axiom expresses this by requiring the union of these
relations not to have any cycles.  This means it must not be possible
to find events

        X0 -> X1 -> X2 -> ... -> Xn -> X0,

where each of the links is either rf, co, fr, or po-loc.  This has to
hold if the accesses to the fixed memory location can be ordered as
cache coherence demands.

Although it is not obvious, it can be shown that the converse is also
true: This LKMM axiom implies that the four coherency rules are
obeyed.


ATOMIC UPDATES: rmw
-------------------

What does it mean to say that a read-modify-write (rmw) update, such
as atomic_inc(&x), is atomic?  It means that the memory location (x in
this case) does not get altered between the read and the write events
making up the atomic operation.  In particular, if two CPUs perform
atomic_inc(&x) concurrently, it must be guaranteed that the final
value of x will be the initial value plus two.  We should never have
the following sequence of events:

        CPU 0 loads x obtaining 13;
                                        CPU 1 loads x obtaining 13;
        CPU 0 stores 14 to x;
                                        CPU 1 stores 14 to x;

where the final value of x is wrong (14 rather than 15).

In this example, CPU 0's increment effectively gets lost because it
occurs in between CPU 1's load and store.  To put it another way, the
problem is that the position of CPU 0's store in x's coherence order
is between the store that CPU 1 reads from and the store that CPU 1
performs.

The same analysis applies to all atomic update operations.  Therefore,
to enforce atomicity the LKMM requires that atomic updates follow this
rule: Whenever R and W are the read and write events composing an
atomic read-modify-write and W' is the write event which R reads from,
there must not be any stores coming between W' and W in the coherence
order.  Equivalently,

        (R ->rmw W) implies (there is no X with R ->fr X and X ->co W),

where the rmw relation links the read and write events making up each
atomic update.  This is what the LKMM's "atomic" axiom says.

Atomic rmw updates play one more role in the LKMM: They can form "rmw
sequences".  An rmw sequence is simply a bunch of atomic updates where
each update reads from the previous one.  Written using events, it
looks like this:

        Z0 ->rf Y1 ->rmw Z1 ->rf ... ->rf Yn ->rmw Zn,

where Z0 is some store event and n can be any number (even 0, in the
degenerate case).  We write this relation as: Z0 ->rmw-sequence Zn.
Note that this implies Z0 and Zn are stores to the same variable.

Rmw sequences have a special property in the LKMM: They can extend the
cumul-fence relation.  That is, if we have:

        U ->cumul-fence X -> rmw-sequence Y

then also U ->cumul-fence Y.  Thinking about this in terms of the
operational model, U ->cumul-fence X says that the store U propagates
to each CPU before the store X does.  Then the fact that X and Y are
linked by an rmw sequence means that U also propagates to each CPU
before Y does.  In an analogous way, rmw sequences can also extend
the w-post-bounded relation defined below in the PLAIN ACCESSES AND
DATA RACES section.

(The notion of rmw sequences in the LKMM is similar to, but not quite
the same as, that of release sequences in the C11 memory model.  They
were added to the LKMM to fix an obscure bug; without them, atomic
updates with full-barrier semantics did not always guarantee ordering
at least as strong as atomic updates with release-barrier semantics.)


THE PRESERVED PROGRAM ORDER RELATION: ppo
-----------------------------------------

There are many situations where a CPU is obliged to execute two
instructions in program order.  We amalgamate them into the ppo (for
"preserved program order") relation, which links the po-earlier
instruction to the po-later instruction and is thus a sub-relation of
po.

The operational model already includes a description of one such
situation: Fences are a source of ppo links.  Suppose X and Y are
memory accesses with X ->po Y; then the CPU must execute X before Y if
any of the following hold:

        A strong (smp_mb() or synchronize_rcu()) fence occurs between
        X and Y;

        X and Y are both stores and an smp_wmb() fence occurs between
        them;

        X and Y are both loads and an smp_rmb() fence occurs between
        them;

        X is also an acquire fence, such as smp_load_acquire();

        Y is also a release fence, such as smp_store_release().

Another possibility, not mentioned earlier but discussed in the next
section, is:

        X and Y are both loads, X ->addr Y (i.e., there is an address
        dependency from X to Y), and X is a READ_ONCE() or an atomic
        access.

Dependencies can also cause instructions to be executed in program
order.  This is uncontroversial when the second instruction is a
store; either a data, address, or control dependency from a load R to
a store W will force the CPU to execute R before W.  This is very
simply because the CPU cannot tell the memory subsystem about W's
store before it knows what value should be stored (in the case of a
data dependency), what location it should be stored into (in the case
of an address dependency), or whether the store should actually take
place (in the case of a control dependency).

Dependencies to load instructions are more problematic.  To begin with,
there is no such thing as a data dependency to a load.  Next, a CPU
has no reason to respect a control dependency to a load, because it
can always satisfy the second load speculatively before the first, and
then ignore the result if it turns out that the second load shouldn't
be executed after all.  And lastly, the real difficulties begin when
we consider address dependencies to loads.

To be fair about it, all Linux-supported architectures do execute
loads in program order if there is an address dependency between them.
After all, a CPU cannot ask the memory subsystem to load a value from
a particular location before it knows what that location is.  However,
the split-cache design used by Alpha can cause it to behave in a way
that looks as if the loads were executed out of order (see the next
section for more details).  The kernel includes a workaround for this
problem when the loads come from READ_ONCE(), and therefore the LKMM
includes address dependencies to loads in the ppo relation.

On the other hand, dependencies can indirectly affect the ordering of
two loads.  This happens when there is a dependency from a load to a
store and a second, po-later load reads from that store:

        R ->dep W ->rfi R',

where the dep link can be either an address or a data dependency.  In
this situation we know it is possible for the CPU to execute R' before
W, because it can forward the value that W will store to R'.  But it
cannot execute R' before R, because it cannot forward the value before
it knows what that value is, or that W and R' do access the same
location.  However, if there is merely a control dependency between R
and W then the CPU can speculatively forward W to R' before executing
R; if the speculation turns out to be wrong then the CPU merely has to
restart or abandon R'.

(In theory, a CPU might forward a store to a load when it runs across
an address dependency like this:

        r1 = READ_ONCE(ptr);
        WRITE_ONCE(*r1, 17);
        r2 = READ_ONCE(*r1);

because it could tell that the store and the second load access the
same location even before it knows what the location's address is.
However, none of the architectures supported by the Linux kernel do
this.)

Two memory accesses of the same location must always be executed in
program order if the second access is a store.  Thus, if we have

        R ->po-loc W

(the po-loc link says that R comes before W in program order and they
access the same location), the CPU is obliged to execute W after R.
If it executed W first then the memory subsystem would respond to R's
read request with the value stored by W (or an even later store), in
violation of the read-write coherence rule.  Similarly, if we had

        W ->po-loc W'

and the CPU executed W' before W, then the memory subsystem would put
W' before W in the coherence order.  It would effectively cause W to
overwrite W', in violation of the write-write coherence rule.
(Interestingly, an early ARMv8 memory model, now obsolete, proposed
allowing out-of-order writes like this to occur.  The model avoided
violating the write-write coherence rule by requiring the CPU not to
send the W write to the memory subsystem at all!)


AND THEN THERE WAS ALPHA
------------------------

As mentioned above, the Alpha architecture is unique in that it does
not appear to respect address dependencies to loads.  This means that
code such as the following:

        int x = 0;
        int y = -1;
        int *ptr = &y;

        P0()
        {
                WRITE_ONCE(x, 1);
                smp_wmb();
                WRITE_ONCE(ptr, &x);
        }

        P1()
        {
                int *r1;
                int r2;

                r1 = ptr;
                r2 = READ_ONCE(*r1);
        }

can malfunction on Alpha systems (notice that P1 uses an ordinary load
to read ptr instead of READ_ONCE()).  It is quite possible that r1 = &x
and r2 = 0 at the end, in spite of the address dependency.

At first glance this doesn't seem to make sense.  We know that the
smp_wmb() forces P0's store to x to propagate to P1 before the store
to ptr does.  And since P1 can't execute its second load
until it knows what location to load from, i.e., after executing its
first load, the value x = 1 must have propagated to P1 before the
second load executed.  So why doesn't r2 end up equal to 1?

The answer lies in the Alpha's split local caches.  Although the two
stores do reach P1's local cache in the proper order, it can happen
that the first store is processed by a busy part of the cache while
the second store is processed by an idle part.  As a result, the x = 1
value may not become available for P1's CPU to read until after the
ptr = &x value does, leading to the undesirable result above.  The
final effect is that even though the two loads really are executed in
program order, it appears that they aren't.

This could not have happened if the local cache had processed the
incoming stores in FIFO order.  By contrast, other architectures
maintain at least the appearance of FIFO order.

In practice, this difficulty is solved by inserting a special fence
between P1's two loads when the kernel is compiled for the Alpha
architecture.  In fact, as of version 4.15, the kernel automatically
adds this fence after every READ_ONCE() and atomic load on Alpha.  The
effect of the fence is to cause the CPU not to execute any po-later
instructions until after the local cache has finished processing all
the stores it has already received.  Thus, if the code was changed to:

        P1()
        {
                int *r1;
                int r2;

                r1 = READ_ONCE(ptr);
                r2 = READ_ONCE(*r1);
        }

then we would never get r1 = &x and r2 = 0.  By the time P1 executed
its second load, the x = 1 store would already be fully processed by
the local cache and available for satisfying the read request.  Thus
we have yet another reason why shared data should always be read with
READ_ONCE() or another synchronization primitive rather than accessed
directly.

The LKMM requires that smp_rmb(), acquire fences, and strong fences
share this property: They do not allow the CPU to execute any po-later
instructions (or po-later loads in the case of smp_rmb()) until all
outstanding stores have been processed by the local cache.  In the
case of a strong fence, the CPU first has to wait for all of its
po-earlier stores to propagate to every other CPU in the system; then
it has to wait for the local cache to process all the stores received
as of that time -- not just the stores received when the strong fence
began.

And of course, none of this matters for any architecture other than
Alpha.


THE HAPPENS-BEFORE RELATION: hb
-------------------------------

The happens-before relation (hb) links memory accesses that have to
execute in a certain order.  hb includes the ppo relation and two
others, one of which is rfe.

W ->rfe R implies that W and R are on different CPUs.  It also means
that W's store must have propagated to R's CPU before R executed;
otherwise R could not have read the value stored by W.  Therefore W
must have executed before R, and so we have W ->hb R.

The equivalent fact need not hold if W ->rfi R (i.e., W and R are on
the same CPU).  As we have already seen, the operational model allows
W's value to be forwarded to R in such cases, meaning that R may well
execute before W does.

It's important to understand that neither coe nor fre is included in
hb, despite their similarities to rfe.  For example, suppose we have
W ->coe W'.  This means that W and W' are stores to the same location,
they execute on different CPUs, and W comes before W' in the coherence
order (i.e., W' overwrites W).  Nevertheless, it is possible for W' to
execute before W, because the decision as to which store overwrites
the other is made later by the memory subsystem.  When the stores are
nearly simultaneous, either one can come out on top.  Similarly,
R ->fre W means that W overwrites the value which R reads, but it
doesn't mean that W has to execute after R.  All that's necessary is
for the memory subsystem not to propagate W to R's CPU until after R
has executed, which is possible if W executes shortly before R.

The third relation included in hb is like ppo, in that it only links
events that are on the same CPU.  However it is more difficult to
explain, because it arises only indirectly from the requirement of
cache coherence.  The relation is called prop, and it links two events
on CPU C in situations where a store from some other CPU comes after
the first event in the coherence order and propagates to C before the
second event executes.

This is best explained with some examples.  The simplest case looks
like this:

        int x;

        P0()
        {
                int r1;

                WRITE_ONCE(x, 1);
                r1 = READ_ONCE(x);
        }

        P1()
        {
                WRITE_ONCE(x, 8);
        }

If r1 = 8 at the end then P0's accesses must have executed in program
order.  We can deduce this from the operational model; if P0's load
had executed before its store then the value of the store would have
been forwarded to the load, so r1 would have ended up equal to 1, not
8.  In this case there is a prop link from P0's write event to its read
event, because P1's store came after P0's store in x's coherence
order, and P1's store propagated to P0 before P0's load executed.

An equally simple case involves two loads of the same location that
read from different stores:

        int x = 0;

        P0()
        {
                int r1, r2;

                r1 = READ_ONCE(x);
                r2 = READ_ONCE(x);
        }

        P1()
        {
                WRITE_ONCE(x, 9);
        }

If r1 = 0 and r2 = 9 at the end then P0's accesses must have executed
in program order.  If the second load had executed before the first
then the x = 9 store must have been propagated to P0 before the first
load executed, and so r1 would have been 9 rather than 0.  In this
case there is a prop link from P0's first read event to its second,
because P1's store overwrote the value read by P0's first load, and
P1's store propagated to P0 before P0's second load executed.

Less trivial examples of prop all involve fences.  Unlike the simple
examples above, they can require that some instructions are executed
out of program order.  This next one should look familiar:

        int buf = 0, flag = 0;

        P0()
        {
                WRITE_ONCE(buf, 1);
                smp_wmb();
                WRITE_ONCE(flag, 1);
        }

        P1()
        {
                int r1;
                int r2;

                r1 = READ_ONCE(flag);
                r2 = READ_ONCE(buf);
        }

This is the MP pattern again, with an smp_wmb() fence between the two
stores.  If r1 = 1 and r2 = 0 at the end then there is a prop link
from P1's second load to its first (backwards!).  The reason is
similar to the previous examples: The value P1 loads from buf gets
overwritten by P0's store to buf, the fence guarantees that the store
to buf will propagate to P1 before the store to flag does, and the
store to flag propagates to P1 before P1 reads flag.

The prop link says that in order to obtain the r1 = 1, r2 = 0 result,
P1 must execute its second load before the first.  Indeed, if the load
from flag were executed first, then the buf = 1 store would already
have propagated to P1 by the time P1's load from buf executed, so r2
would have been 1 at the end, not 0.  (The reasoning holds even for
Alpha, although the details are more complicated and we will not go
into them.)

But what if we put an smp_rmb() fence between P1's loads?  The fence
would force the two loads to be executed in program order, and it
would generate a cycle in the hb relation: The fence would create a ppo
link (hence an hb link) from the first load to the second, and the
prop relation would give an hb link from the second load to the first.
Since an instruction can't execute before itself, we are forced to
conclude that if an smp_rmb() fence is added, the r1 = 1, r2 = 0
outcome is impossible -- as it should be.

The formal definition of the prop relation involves a coe or fre link,
followed by an arbitrary number of cumul-fence links, ending with an
rfe link.  You can concoct more exotic examples, containing more than
one fence, although this quickly leads to diminishing returns in terms
of complexity.  For instance, here's an example containing a coe link
followed by two cumul-fences and an rfe link, utilizing the fact that
release fences are A-cumulative:

        int x, y, z;

        P0()
        {
                int r0;

                WRITE_ONCE(x, 1);
                r0 = READ_ONCE(z);
        }

        P1()
        {
                WRITE_ONCE(x, 2);
                smp_wmb();
                WRITE_ONCE(y, 1);
        }

        P2()
        {
                int r2;

                r2 = READ_ONCE(y);
                smp_store_release(&z, 1);
        }

If x = 2, r0 = 1, and r2 = 1 after this code runs then there is a prop
link from P0's store to its load.  This is because P0's store gets
overwritten by P1's store since x = 2 at the end (a coe link), the
smp_wmb() ensures that P1's store to x propagates to P2 before the
store to y does (the first cumul-fence), the store to y propagates to P2
before P2's load and store execute, P2's smp_store_release()
guarantees that the stores to x and y both propagate to P0 before the
store to z does (the second cumul-fence), and P0's load executes after the
store to z has propagated to P0 (an rfe link).

In summary, the fact that the hb relation links memory access events
in the order they execute means that it must not have cycles.  This
requirement is the content of the LKMM's "happens-before" axiom.

The LKMM defines yet another relation connected to times of
instruction execution, but it is not included in hb.  It relies on the
particular properties of strong fences, which we cover in the next
section.


THE PROPAGATES-BEFORE RELATION: pb
----------------------------------

The propagates-before (pb) relation capitalizes on the special
features of strong fences.  It links two events E and F whenever some
store is coherence-later than E and propagates to every CPU and to RAM
before F executes.  The formal definition requires that E be linked to
F via a coe or fre link, an arbitrary number of cumul-fences, an
optional rfe link, a strong fence, and an arbitrary number of hb
links.  Let's see how this definition works out.

Consider first the case where E is a store (implying that the sequence
of links begins with coe).  Then there are events W, X, Y, and Z such
that:

        E ->coe W ->cumul-fence* X ->rfe? Y ->strong-fence Z ->hb* F,

where the * suffix indicates an arbitrary number of links of the
specified type, and the ? suffix indicates the link is optional (Y may
be equal to X).  Because of the cumul-fence links, we know that W will
propagate to Y's CPU before X does, hence before Y executes and hence
before the strong fence executes.  Because this fence is strong, we
know that W will propagate to every CPU and to RAM before Z executes.
And because of the hb links, we know that Z will execute before F.
Thus W, which comes later than E in the coherence order, will
propagate to every CPU and to RAM before F executes.

The case where E is a load is exactly the same, except that the first
link in the sequence is fre instead of coe.

The existence of a pb link from E to F implies that E must execute
before F.  To see why, suppose that F executed first.  Then W would
have propagated to E's CPU before E executed.  If E was a store, the
memory subsystem would then be forced to make E come after W in the
coherence order, contradicting the fact that E ->coe W.  If E was a
load, the memory subsystem would then be forced to satisfy E's read
request with the value stored by W or an even later store,
contradicting the fact that E ->fre W.

A good example illustrating how pb works is the SB pattern with strong
fences:

        int x = 0, y = 0;

        P0()
        {
                int r0;

                WRITE_ONCE(x, 1);
                smp_mb();
                r0 = READ_ONCE(y);
        }

        P1()
        {
                int r1;

                WRITE_ONCE(y, 1);
                smp_mb();
                r1 = READ_ONCE(x);
        }

If r0 = 0 at the end then there is a pb link from P0's load to P1's
load: an fre link from P0's load to P1's store (which overwrites the
value read by P0), and a strong fence between P1's store and its load.
In this example, the sequences of cumul-fence and hb links are empty.
Note that this pb link is not included in hb as an instance of prop,
because it does not start and end on the same CPU.

Similarly, if r1 = 0 at the end then there is a pb link from P1's load
to P0's.  This means that if both r1 and r2 were 0 there would be a
cycle in pb, which is not possible since an instruction cannot execute
before itself.  Thus, adding smp_mb() fences to the SB pattern
prevents the r0 = 0, r1 = 0 outcome.

In summary, the fact that the pb relation links events in the order
they execute means that it cannot have cycles.  This requirement is
the content of the LKMM's "propagation" axiom.


RCU RELATIONS: rcu-link, rcu-gp, rcu-rscsi, rcu-order, rcu-fence, and rb
------------------------------------------------------------------------

RCU (Read-Copy-Update) is a powerful synchronization mechanism.  It
rests on two concepts: grace periods and read-side critical sections.

A grace period is the span of time occupied by a call to
synchronize_rcu().  A read-side critical section (or just critical
section, for short) is a region of code delimited by rcu_read_lock()
at the start and rcu_read_unlock() at the end.  Critical sections can
be nested, although we won't make use of this fact.

As far as memory models are concerned, RCU's main feature is its
Grace-Period Guarantee, which states that a critical section can never
span a full grace period.  In more detail, the Guarantee says:

        For any critical section C and any grace period G, at least
        one of the following statements must hold:

(1)     C ends before G does, and in addition, every store that
        propagates to C's CPU before the end of C must propagate to
        every CPU before G ends.

(2)     G starts before C does, and in addition, every store that
        propagates to G's CPU before the start of G must propagate
        to every CPU before C starts.

In particular, it is not possible for a critical section to both start
before and end after a grace period.

Here is a simple example of RCU in action:

        int x, y;

        P0()
        {
                rcu_read_lock();
                WRITE_ONCE(x, 1);
                WRITE_ONCE(y, 1);
                rcu_read_unlock();
        }

        P1()
        {
                int r1, r2;

                r1 = READ_ONCE(x);
                synchronize_rcu();
                r2 = READ_ONCE(y);
        }

The Grace Period Guarantee tells us that when this code runs, it will
never end with r1 = 1 and r2 = 0.  The reasoning is as follows.  r1 = 1
means that P0's store to x propagated to P1 before P1 called
synchronize_rcu(), so P0's critical section must have started before
P1's grace period, contrary to part (2) of the Guarantee.  On the
other hand, r2 = 0 means that P0's store to y, which occurs before the
end of the critical section, did not propagate to P1 before the end of
the grace period, contrary to part (1).  Together the results violate
the Guarantee.

In the kernel's implementations of RCU, the requirements for stores
to propagate to every CPU are fulfilled by placing strong fences at
suitable places in the RCU-related code.  Thus, if a critical section
starts before a grace period does then the critical section's CPU will
execute an smp_mb() fence after the end of the critical section and
some time before the grace period's synchronize_rcu() call returns.
And if a critical section ends after a grace period does then the
synchronize_rcu() routine will execute an smp_mb() fence at its start
and some time before the critical section's opening rcu_read_lock()
executes.

What exactly do we mean by saying that a critical section "starts
before" or "ends after" a grace period?  Some aspects of the meaning
are pretty obvious, as in the example above, but the details aren't
entirely clear.  The LKMM formalizes this notion by means of the
rcu-link relation.  rcu-link encompasses a very general notion of
"before": If E and F are RCU fence events (i.e., rcu_read_lock(),
rcu_read_unlock(), or synchronize_rcu()) then among other things,
E ->rcu-link F includes cases where E is po-before some memory-access
event X, F is po-after some memory-access event Y, and we have any of
X ->rfe Y, X ->co Y, or X ->fr Y.

The formal definition of the rcu-link relation is more than a little
obscure, and we won't give it here.  It is closely related to the pb
relation, and the details don't matter unless you want to comb through
a somewhat lengthy formal proof.  Pretty much all you need to know
about rcu-link is the information in the preceding paragraph.

The LKMM also defines the rcu-gp and rcu-rscsi relations.  They bring
grace periods and read-side critical sections into the picture, in the
following way:

        E ->rcu-gp F means that E and F are in fact the same event,
        and that event is a synchronize_rcu() fence (i.e., a grace
        period).

        E ->rcu-rscsi F means that E and F are the rcu_read_unlock()
        and rcu_read_lock() fence events delimiting some read-side
        critical section.  (The 'i' at the end of the name emphasizes
        that this relation is "inverted": It links the end of the
        critical section to the start.)

If we think of the rcu-link relation as standing for an extended
"before", then X ->rcu-gp Y ->rcu-link Z roughly says that X is a
grace period which ends before Z begins.  (In fact it covers more than
this, because it also includes cases where some store propagates to
Z's CPU before Z begins but doesn't propagate to some other CPU until
after X ends.)  Similarly, X ->rcu-rscsi Y ->rcu-link Z says that X is
the end of a critical section which starts before Z begins.

The LKMM goes on to define the rcu-order relation as a sequence of
rcu-gp and rcu-rscsi links separated by rcu-link links, in which the
number of rcu-gp links is >= the number of rcu-rscsi links.  For
example:

        X ->rcu-gp Y ->rcu-link Z ->rcu-rscsi T ->rcu-link U ->rcu-gp V

would imply that X ->rcu-order V, because this sequence contains two
rcu-gp links and one rcu-rscsi link.  (It also implies that
X ->rcu-order T and Z ->rcu-order V.)  On the other hand:

        X ->rcu-rscsi Y ->rcu-link Z ->rcu-rscsi T ->rcu-link U ->rcu-gp V

does not imply X ->rcu-order V, because the sequence contains only
one rcu-gp link but two rcu-rscsi links.

The rcu-order relation is important because the Grace Period Guarantee
means that rcu-order links act kind of like strong fences.  In
particular, E ->rcu-order F implies not only that E begins before F
ends, but also that any write po-before E will propagate to every CPU
before any instruction po-after F can execute.  (However, it does not
imply that E must execute before F; in fact, each synchronize_rcu()
fence event is linked to itself by rcu-order as a degenerate case.)

To prove this in full generality requires some intellectual effort.
We'll consider just a very simple case:

        G ->rcu-gp W ->rcu-link Z ->rcu-rscsi F.

This formula means that G and W are the same event (a grace period),
and there are events X, Y and a read-side critical section C such that:

        1. G = W is po-before or equal to X;

        2. X comes "before" Y in some sense (including rfe, co and fr);

        3. Y is po-before Z;

        4. Z is the rcu_read_unlock() event marking the end of C;

        5. F is the rcu_read_lock() event marking the start of C.

From 1 - 4 we deduce that the grace period G ends before the critical
section C.  Then part (2) of the Grace Period Guarantee says not only
that G starts before C does, but also that any write which executes on
G's CPU before G starts must propagate to every CPU before C starts.
In particular, the write propagates to every CPU before F finishes
executing and hence before any instruction po-after F can execute.
This sort of reasoning can be extended to handle all the situations
covered by rcu-order.

The rcu-fence relation is a simple extension of rcu-order.  While
rcu-order only links certain fence events (calls to synchronize_rcu(),
rcu_read_lock(), or rcu_read_unlock()), rcu-fence links any events
that are separated by an rcu-order link.  This is analogous to the way
the strong-fence relation links events that are separated by an
smp_mb() fence event (as mentioned above, rcu-order links act kind of
like strong fences).  Written symbolically, X ->rcu-fence Y means
there are fence events E and F such that:

        X ->po E ->rcu-order F ->po Y.

From the discussion above, we see this implies not only that X
executes before Y, but also (if X is a store) that X propagates to
every CPU before Y executes.  Thus rcu-fence is sort of a
"super-strong" fence: Unlike the original strong fences (smp_mb() and
synchronize_rcu()), rcu-fence is able to link events on different
CPUs.  (Perhaps this fact should lead us to say that rcu-fence isn't
really a fence at all!)

Finally, the LKMM defines the RCU-before (rb) relation in terms of
rcu-fence.  This is done in essentially the same way as the pb
relation was defined in terms of strong-fence.  We will omit the
details; the end result is that E ->rb F implies E must execute
before F, just as E ->pb F does (and for much the same reasons).

Putting this all together, the LKMM expresses the Grace Period
Guarantee by requiring that the rb relation does not contain a cycle.
Equivalently, this "rcu" axiom requires that there are no events E
and F with E ->rcu-link F ->rcu-order E.  Or to put it a third way,
the axiom requires that there are no cycles consisting of rcu-gp and
rcu-rscsi alternating with rcu-link, where the number of rcu-gp links
is >= the number of rcu-rscsi links.

Justifying the axiom isn't easy, but it is in fact a valid
formalization of the Grace Period Guarantee.  We won't attempt to go
through the detailed argument, but the following analysis gives a
taste of what is involved.  Suppose both parts of the Guarantee are
violated: A critical section starts before a grace period, and some
store propagates to the critical section's CPU before the end of the
critical section but doesn't propagate to some other CPU until after
the end of the grace period.

Putting symbols to these ideas, let L and U be the rcu_read_lock() and
rcu_read_unlock() fence events delimiting the critical section in
question, and let S be the synchronize_rcu() fence event for the grace
period.  Saying that the critical section starts before S means there
are events Q and R where Q is po-after L (which marks the start of the
critical section), Q is "before" R in the sense used by the rcu-link
relation, and R is po-before the grace period S.  Thus we have:

        L ->rcu-link S.

Let W be the store mentioned above, let Y come before the end of the
critical section and witness that W propagates to the critical
section's CPU by reading from W, and let Z on some arbitrary CPU be a
witness that W has not propagated to that CPU, where Z happens after
some event X which is po-after S.  Symbolically, this amounts to:

        S ->po X ->hb* Z ->fr W ->rf Y ->po U.

The fr link from Z to W indicates that W has not propagated to Z's CPU
at the time that Z executes.  From this, it can be shown (see the
discussion of the rcu-link relation earlier) that S and U are related
by rcu-link:

        S ->rcu-link U.

Since S is a grace period we have S ->rcu-gp S, and since L and U are
the start and end of the critical section C we have U ->rcu-rscsi L.
From this we obtain:

        S ->rcu-gp S ->rcu-link U ->rcu-rscsi L ->rcu-link S,

a forbidden cycle.  Thus the "rcu" axiom rules out this violation of
the Grace Period Guarantee.

For something a little more down-to-earth, let's see how the axiom
works out in practice.  Consider the RCU code example from above, this
time with statement labels added:

        int x, y;

        P0()
        {
                L: rcu_read_lock();
                X: WRITE_ONCE(x, 1);
                Y: WRITE_ONCE(y, 1);
                U: rcu_read_unlock();
        }

        P1()
        {
                int r1, r2;

                Z: r1 = READ_ONCE(x);
                S: synchronize_rcu();
                W: r2 = READ_ONCE(y);
        }


If r2 = 0 at the end then P0's store at Y overwrites the value that
P1's load at W reads from, so we have W ->fre Y.  Since S ->po W and
also Y ->po U, we get S ->rcu-link U.  In addition, S ->rcu-gp S
because S is a grace period.

If r1 = 1 at the end then P1's load at Z reads from P0's store at X,
so we have X ->rfe Z.  Together with L ->po X and Z ->po S, this
yields L ->rcu-link S.  And since L and U are the start and end of a
critical section, we have U ->rcu-rscsi L.

Then U ->rcu-rscsi L ->rcu-link S ->rcu-gp S ->rcu-link U is a
forbidden cycle, violating the "rcu" axiom.  Hence the outcome is not
allowed by the LKMM, as we would expect.

For contrast, let's see what can happen in a more complicated example:

        int x, y, z;

        P0()
        {
                int r0;

                L0: rcu_read_lock();
                    r0 = READ_ONCE(x);
                    WRITE_ONCE(y, 1);
                U0: rcu_read_unlock();
        }

        P1()
        {
                int r1;

                    r1 = READ_ONCE(y);
                S1: synchronize_rcu();
                    WRITE_ONCE(z, 1);
        }

        P2()
        {
                int r2;

                L2: rcu_read_lock();
                    r2 = READ_ONCE(z);
                    WRITE_ONCE(x, 1);
                U2: rcu_read_unlock();
        }

If r0 = r1 = r2 = 1 at the end, then similar reasoning to before shows
that U0 ->rcu-rscsi L0 ->rcu-link S1 ->rcu-gp S1 ->rcu-link U2 ->rcu-rscsi
L2 ->rcu-link U0.  However this cycle is not forbidden, because the
sequence of relations contains fewer instances of rcu-gp (one) than of
rcu-rscsi (two).  Consequently the outcome is allowed by the LKMM.
The following instruction timing diagram shows how it might actually
occur:

P0                      P1                      P2
--------------------    --------------------    --------------------
rcu_read_lock()
WRITE_ONCE(y, 1)
                        r1 = READ_ONCE(y)
                        synchronize_rcu() starts
                        .                       rcu_read_lock()
                        .                       WRITE_ONCE(x, 1)
r0 = READ_ONCE(x)       .
rcu_read_unlock()       .
                        synchronize_rcu() ends
                        WRITE_ONCE(z, 1)
                                                r2 = READ_ONCE(z)
                                                rcu_read_unlock()

This requires P0 and P2 to execute their loads and stores out of
program order, but of course they are allowed to do so.  And as you
can see, the Grace Period Guarantee is not violated: The critical
section in P0 both starts before P1's grace period does and ends
before it does, and the critical section in P2 both starts after P1's
grace period does and ends after it does.

The LKMM supports SRCU (Sleepable Read-Copy-Update) in addition to
normal RCU.  The ideas involved are much the same as above, with new
relations srcu-gp and srcu-rscsi added to represent SRCU grace periods
and read-side critical sections.  However, there are some significant
differences between RCU read-side critical sections and their SRCU
counterparts, as described in the next section.


SRCU READ-SIDE CRITICAL SECTIONS
--------------------------------

The LKMM uses the srcu-rscsi relation to model SRCU read-side critical
sections.  They differ from RCU read-side critical sections in the
following respects:

1.      Unlike the analogous RCU primitives, synchronize_srcu(),
        srcu_read_lock(), and srcu_read_unlock() take a pointer to a
        struct srcu_struct as an argument.  This structure is called
        an SRCU domain, and calls linked by srcu-rscsi must have the
        same domain.  Read-side critical sections and grace periods
        associated with different domains are independent of one
        another; the SRCU version of the RCU Guarantee applies only
        to pairs of critical sections and grace periods having the
        same domain.

2.      srcu_read_lock() returns a value, called the index, which must
        be passed to the matching srcu_read_unlock() call.  Unlike
        rcu_read_lock() and rcu_read_unlock(), an srcu_read_lock()
        call does not always have to match the next unpaired
        srcu_read_unlock().  In fact, it is possible for two SRCU
        read-side critical sections to overlap partially, as in the
        following example (where s is an srcu_struct and idx1 and idx2
        are integer variables):

                idx1 = srcu_read_lock(&s);      // Start of first RSCS
                idx2 = srcu_read_lock(&s);      // Start of second RSCS
                srcu_read_unlock(&s, idx1);     // End of first RSCS
                srcu_read_unlock(&s, idx2);     // End of second RSCS

        The matching is determined entirely by the domain pointer and
        index value.  By contrast, if the calls had been
        rcu_read_lock() and rcu_read_unlock() then they would have
        created two nested (fully overlapping) read-side critical
        sections: an inner one and an outer one.

3.      The srcu_down_read() and srcu_up_read() primitives work
        exactly like srcu_read_lock() and srcu_read_unlock(), except
        that matching calls don't have to execute within the same context.
        (The names are meant to be suggestive of operations on
        semaphores.)  Since the matching is determined by the domain
        pointer and index value, these primitives make it possible for
        an SRCU read-side critical section to start on one CPU and end
        on another, so to speak.

In order to account for these properties of SRCU, the LKMM models
srcu_read_lock() as a special type of load event (which is
appropriate, since it takes a memory location as argument and returns
a value, just as a load does) and srcu_read_unlock() as a special type
of store event (again appropriate, since it takes as arguments a
memory location and a value).  These loads and stores are annotated as
belonging to the "srcu-lock" and "srcu-unlock" event classes
respectively.

This approach allows the LKMM to tell whether two events are
associated with the same SRCU domain, simply by checking whether they
access the same memory location (i.e., they are linked by the loc
relation).  It also gives a way to tell which unlock matches a
particular lock, by checking for the presence of a data dependency
from the load (srcu-lock) to the store (srcu-unlock).  For example,
given the situation outlined earlier (with statement labels added):

        A: idx1 = srcu_read_lock(&s);
        B: idx2 = srcu_read_lock(&s);
        C: srcu_read_unlock(&s, idx1);
        D: srcu_read_unlock(&s, idx2);

the LKMM will treat A and B as loads from s yielding values saved in
idx1 and idx2 respectively.  Similarly, it will treat C and D as
though they stored the values from idx1 and idx2 in s.  The end result
is much as if we had written:

        A: idx1 = READ_ONCE(s);
        B: idx2 = READ_ONCE(s);
        C: WRITE_ONCE(s, idx1);
        D: WRITE_ONCE(s, idx2);

except for the presence of the special srcu-lock and srcu-unlock
annotations.  You can see at once that we have A ->data C and
B ->data D.  These dependencies tell the LKMM that C is the
srcu-unlock event matching srcu-lock event A, and D is the
srcu-unlock event matching srcu-lock event B.

This approach is admittedly a hack, and it has the potential to lead
to problems.  For example, in:

        idx1 = srcu_read_lock(&s);
        srcu_read_unlock(&s, idx1);
        idx2 = srcu_read_lock(&s);
        srcu_read_unlock(&s, idx2);

the LKMM will believe that idx2 must have the same value as idx1,
since it reads from the immediately preceding store of idx1 in s.
Fortunately this won't matter, assuming that litmus tests never do
anything with SRCU index values other than pass them to
srcu_read_unlock() or srcu_up_read() calls.

However, sometimes it is necessary to store an index value in a
shared variable temporarily.  In fact, this is the only way for
srcu_down_read() to pass the index it gets to an srcu_up_read() call
on a different CPU.  In more detail, we might have soething like:

        struct srcu_struct s;
        int x;

        P0()
        {
                int r0;

                A: r0 = srcu_down_read(&s);
                B: WRITE_ONCE(x, r0);
        }

        P1()
        {
                int r1;

                C: r1 = READ_ONCE(x);
                D: srcu_up_read(&s, r1);
        }

Assuming that P1 executes after P0 and does read the index value
stored in x, we can write this (using brackets to represent event
annotations) as:

        A[srcu-lock] ->data B[once] ->rf C[once] ->data D[srcu-unlock].

The LKMM defines a carry-srcu-data relation to express this pattern;
it permits an arbitrarily long sequence of

        data ; rf

pairs (that is, a data link followed by an rf link) to occur between
an srcu-lock event and the final data dependency leading to the
matching srcu-unlock event.  carry-srcu-data is complicated by the
need to ensure that none of the intermediate store events in this
sequence are instances of srcu-unlock.  This is necessary because in a
pattern like the one above:

        A: idx1 = srcu_read_lock(&s);
        B: srcu_read_unlock(&s, idx1);
        C: idx2 = srcu_read_lock(&s);
        D: srcu_read_unlock(&s, idx2);

the LKMM treats B as a store to the variable s and C as a load from
that variable, creating an undesirable rf link from B to C:

        A ->data B ->rf C ->data D.

This would cause carry-srcu-data to mistakenly extend a data
dependency from A to D, giving the impression that D was the
srcu-unlock event matching A's srcu-lock.  To avoid such problems,
carry-srcu-data does not accept sequences in which the ends of any of
the intermediate ->data links (B above) is an srcu-unlock event.


LOCKING
-------

The LKMM includes locking.  In fact, there is special code for locking
in the formal model, added in order to make tools run faster.
However, this special code is intended to be more or less equivalent
to concepts we have already covered.  A spinlock_t variable is treated
the same as an int, and spin_lock(&s) is treated almost the same as:

        while (cmpxchg_acquire(&s, 0, 1) != 0)
                cpu_relax();

This waits until s is equal to 0 and then atomically sets it to 1,
and the read part of the cmpxchg operation acts as an acquire fence.
An alternate way to express the same thing would be:

        r = xchg_acquire(&s, 1);

along with a requirement that at the end, r = 0.  Similarly,
spin_trylock(&s) is treated almost the same as:

        return !cmpxchg_acquire(&s, 0, 1);

which atomically sets s to 1 if it is currently equal to 0 and returns
true if it succeeds (the read part of the cmpxchg operation acts as an
acquire fence only if the operation is successful).  spin_unlock(&s)
is treated almost the same as:

        smp_store_release(&s, 0);

The "almost" qualifiers above need some explanation.  In the LKMM, the
store-release in a spin_unlock() and the load-acquire which forms the
first half of the atomic rmw update in a spin_lock() or a successful
spin_trylock() -- we can call these things lock-releases and
lock-acquires -- have two properties beyond those of ordinary releases
and acquires.

First, when a lock-acquire reads from or is po-after a lock-release,
the LKMM requires that every instruction po-before the lock-release
must execute before any instruction po-after the lock-acquire.  This
would naturally hold if the release and acquire operations were on
different CPUs and accessed the same lock variable, but the LKMM says
it also holds when they are on the same CPU, even if they access
different lock variables.  For example:

        int x, y;
        spinlock_t s, t;

        P0()
        {
                int r1, r2;

                spin_lock(&s);
                r1 = READ_ONCE(x);
                spin_unlock(&s);
                spin_lock(&t);
                r2 = READ_ONCE(y);
                spin_unlock(&t);
        }

        P1()
        {
                WRITE_ONCE(y, 1);
                smp_wmb();
                WRITE_ONCE(x, 1);
        }

Here the second spin_lock() is po-after the first spin_unlock(), and
therefore the load of x must execute before the load of y, even though
the two locking operations use different locks.  Thus we cannot have
r1 = 1 and r2 = 0 at the end (this is an instance of the MP pattern).

This requirement does not apply to ordinary release and acquire
fences, only to lock-related operations.  For instance, suppose P0()
in the example had been written as:

        P0()
        {
                int r1, r2, r3;

                r1 = READ_ONCE(x);
                smp_store_release(&s, 1);
                r3 = smp_load_acquire(&s);
                r2 = READ_ONCE(y);
        }

Then the CPU would be allowed to forward the s = 1 value from the
smp_store_release() to the smp_load_acquire(), executing the
instructions in the following order:

                r3 = smp_load_acquire(&s);      // Obtains r3 = 1
                r2 = READ_ONCE(y);
                r1 = READ_ONCE(x);
                smp_store_release(&s, 1);       // Value is forwarded

and thus it could load y before x, obtaining r2 = 0 and r1 = 1.

Second, when a lock-acquire reads from or is po-after a lock-release,
and some other stores W and W' occur po-before the lock-release and
po-after the lock-acquire respectively, the LKMM requires that W must
propagate to each CPU before W' does.  For example, consider:

        int x, y;
        spinlock_t s;

        P0()
        {
                spin_lock(&s);
                WRITE_ONCE(x, 1);
                spin_unlock(&s);
        }

        P1()
        {
                int r1;

                spin_lock(&s);
                r1 = READ_ONCE(x);
                WRITE_ONCE(y, 1);
                spin_unlock(&s);
        }

        P2()
        {
                int r2, r3;

                r2 = READ_ONCE(y);
                smp_rmb();
                r3 = READ_ONCE(x);
        }

If r1 = 1 at the end then the spin_lock() in P1 must have read from
the spin_unlock() in P0.  Hence the store to x must propagate to P2
before the store to y does, so we cannot have r2 = 1 and r3 = 0.  But
if P1 had used a lock variable different from s, the writes could have
propagated in either order.  (On the other hand, if the code in P0 and
P1 had all executed on a single CPU, as in the example before this
one, then the writes would have propagated in order even if the two
critical sections used different lock variables.)

These two special requirements for lock-release and lock-acquire do
not arise from the operational model.  Nevertheless, kernel developers
have come to expect and rely on them because they do hold on all
architectures supported by the Linux kernel, albeit for various
differing reasons.


PLAIN ACCESSES AND DATA RACES
-----------------------------

In the LKMM, memory accesses such as READ_ONCE(x), atomic_inc(&y),
smp_load_acquire(&z), and so on are collectively referred to as
"marked" accesses, because they are all annotated with special
operations of one kind or another.  Ordinary C-language memory
accesses such as x or y = 0 are simply called "plain" accesses.

Early versions of the LKMM had nothing to say about plain accesses.
The C standard allows compilers to assume that the variables affected
by plain accesses are not concurrently read or written by any other
threads or CPUs.  This leaves compilers free to implement all manner
of transformations or optimizations of code containing plain accesses,
making such code very difficult for a memory model to handle.

Here is just one example of a possible pitfall:

        int a = 6;
        int *x = &a;

        P0()
        {
                int *r1;
                int r2 = 0;

                r1 = x;
                if (r1 != NULL)
                        r2 = READ_ONCE(*r1);
        }

        P1()
        {
                WRITE_ONCE(x, NULL);
        }

On the face of it, one would expect that when this code runs, the only
possible final values for r2 are 6 and 0, depending on whether or not
P1's store to x propagates to P0 before P0's load from x executes.
But since P0's load from x is a plain access, the compiler may decide
to carry out the load twice (for the comparison against NULL, then again
for the READ_ONCE()) and eliminate the temporary variable r1.  The
object code generated for P0 could therefore end up looking rather
like this:

        P0()
        {
                int r2 = 0;

                if (x != NULL)
                        r2 = READ_ONCE(*x);
        }

And now it is obvious that this code runs the risk of dereferencing a
NULL pointer, because P1's store to x might propagate to P0 after the
test against NULL has been made but before the READ_ONCE() executes.
If the original code had said "r1 = READ_ONCE(x)" instead of "r1 = x",
the compiler would not have performed this optimization and there
would be no possibility of a NULL-pointer dereference.

Given the possibility of transformations like this one, the LKMM
doesn't try to predict all possible outcomes of code containing plain
accesses.  It is instead content to determine whether the code
violates the compiler's assumptions, which would render the ultimate
outcome undefined.

In technical terms, the compiler is allowed to assume that when the
program executes, there will not be any data races.  A "data race"
occurs when there are two memory accesses such that:

1.      they access the same location,

2.      at least one of them is a store,

3.      at least one of them is plain,

4.      they occur on different CPUs (or in different threads on the
        same CPU), and

5.      they execute concurrently.

In the literature, two accesses are said to "conflict" if they satisfy
1 and 2 above.  We'll go a little farther and say that two accesses
are "race candidates" if they satisfy 1 - 4.  Thus, whether or not two
race candidates actually do race in a given execution depends on
whether they are concurrent.

The LKMM tries to determine whether a program contains race candidates
which may execute concurrently; if it does then the LKMM says there is
a potential data race and makes no predictions about the program's
outcome.

Determining whether two accesses are race candidates is easy; you can
see that all the concepts involved in the definition above are already
part of the memory model.  The hard part is telling whether they may
execute concurrently.  The LKMM takes a conservative attitude,
assuming that accesses may be concurrent unless it can prove they
are not.

If two memory accesses aren't concurrent then one must execute before
the other.  Therefore the LKMM decides two accesses aren't concurrent
if they can be connected by a sequence of hb, pb, and rb links
(together referred to as xb, for "executes before").  However, there
are two complicating factors.

If X is a load and X executes before a store Y, then indeed there is
no danger of X and Y being concurrent.  After all, Y can't have any
effect on the value obtained by X until the memory subsystem has
propagated Y from its own CPU to X's CPU, which won't happen until
some time after Y executes and thus after X executes.  But if X is a
store, then even if X executes before Y it is still possible that X
will propagate to Y's CPU just as Y is executing.  In such a case X
could very well interfere somehow with Y, and we would have to
consider X and Y to be concurrent.

Therefore when X is a store, for X and Y to be non-concurrent the LKMM
requires not only that X must execute before Y but also that X must
propagate to Y's CPU before Y executes.  (Or vice versa, of course, if
Y executes before X -- then Y must propagate to X's CPU before X
executes if Y is a store.)  This is expressed by the visibility
relation (vis), where X ->vis Y is defined to hold if there is an
intermediate event Z such that:

        X is connected to Z by a possibly empty sequence of
        cumul-fence links followed by an optional rfe link (if none of
        these links are present, X and Z are the same event),

and either:

        Z is connected to Y by a strong-fence link followed by a
        possibly empty sequence of xb links,

or:

        Z is on the same CPU as Y and is connected to Y by a possibly
        empty sequence of xb links (again, if the sequence is empty it
        means Z and Y are the same event).

The motivations behind this definition are straightforward:

        cumul-fence memory barriers force stores that are po-before
        the barrier to propagate to other CPUs before stores that are
        po-after the barrier.

        An rfe link from an event W to an event R says that R reads
        from W, which certainly means that W must have propagated to
        R's CPU before R executed.

        strong-fence memory barriers force stores that are po-before
        the barrier, or that propagate to the barrier's CPU before the
        barrier executes, to propagate to all CPUs before any events
        po-after the barrier can execute.

To see how this works out in practice, consider our old friend, the MP
pattern (with fences and statement labels, but without the conditional
test):

        int buf = 0, flag = 0;

        P0()
        {
                X: WRITE_ONCE(buf, 1);
                   smp_wmb();
                W: WRITE_ONCE(flag, 1);
        }

        P1()
        {
                int r1;
                int r2 = 0;

                Z: r1 = READ_ONCE(flag);
                   smp_rmb();
                Y: r2 = READ_ONCE(buf);
        }

The smp_wmb() memory barrier gives a cumul-fence link from X to W, and
assuming r1 = 1 at the end, there is an rfe link from W to Z.  This
means that the store to buf must propagate from P0 to P1 before Z
executes.  Next, Z and Y are on the same CPU and the smp_rmb() fence
provides an xb link from Z to Y (i.e., it forces Z to execute before
Y).  Therefore we have X ->vis Y: X must propagate to Y's CPU before Y
executes.

The second complicating factor mentioned above arises from the fact
that when we are considering data races, some of the memory accesses
are plain.  Now, although we have not said so explicitly, up to this
point most of the relations defined by the LKMM (ppo, hb, prop,
cumul-fence, pb, and so on -- including vis) apply only to marked
accesses.

There are good reasons for this restriction.  The compiler is not
allowed to apply fancy transformations to marked accesses, and
consequently each such access in the source code corresponds more or
less directly to a single machine instruction in the object code.  But
plain accesses are a different story; the compiler may combine them,
split them up, duplicate them, eliminate them, invent new ones, and
who knows what else.  Seeing a plain access in the source code tells
you almost nothing about what machine instructions will end up in the
object code.

Fortunately, the compiler isn't completely free; it is subject to some
limitations.  For one, it is not allowed to introduce a data race into
the object code if the source code does not already contain a data
race (if it could, memory models would be useless and no multithreaded
code would be safe!).  For another, it cannot move a plain access past
a compiler barrier.

A compiler barrier is a kind of fence, but as the name implies, it
only affects the compiler; it does not necessarily have any effect on
how instructions are executed by the CPU.  In Linux kernel source
code, the barrier() function is a compiler barrier.  It doesn't give
rise directly to any machine instructions in the object code; rather,
it affects how the compiler generates the rest of the object code.
Given source code like this:

        ... some memory accesses ...
        barrier();
        ... some other memory accesses ...

the barrier() function ensures that the machine instructions
corresponding to the first group of accesses will all end po-before
any machine instructions corresponding to the second group of accesses
-- even if some of the accesses are plain.  (Of course, the CPU may
then execute some of those accesses out of program order, but we
already know how to deal with such issues.)  Without the barrier()
there would be no such guarantee; the two groups of accesses could be
intermingled or even reversed in the object code.

The LKMM doesn't say much about the barrier() function, but it does
require that all fences are also compiler barriers.  In addition, it
requires that the ordering properties of memory barriers such as
smp_rmb() or smp_store_release() apply to plain accesses as well as to
marked accesses.

This is the key to analyzing data races.  Consider the MP pattern
again, now using plain accesses for buf:

        int buf = 0, flag = 0;

        P0()
        {
                U: buf = 1;
                   smp_wmb();
                X: WRITE_ONCE(flag, 1);
        }

        P1()
        {
                int r1;
                int r2 = 0;

                Y: r1 = READ_ONCE(flag);
                   if (r1) {
                           smp_rmb();
                        V: r2 = buf;
                   }
        }

This program does not contain a data race.  Although the U and V
accesses are race candidates, the LKMM can prove they are not
concurrent as follows:

        The smp_wmb() fence in P0 is both a compiler barrier and a
        cumul-fence.  It guarantees that no matter what hash of
        machine instructions the compiler generates for the plain
        access U, all those instructions will be po-before the fence.
        Consequently U's store to buf, no matter how it is carried out
        at the machine level, must propagate to P1 before X's store to
        flag does.

        X and Y are both marked accesses.  Hence an rfe link from X to
        Y is a valid indicator that X propagated to P1 before Y
        executed, i.e., X ->vis Y.  (And if there is no rfe link then
        r1 will be 0, so V will not be executed and ipso facto won't
        race with U.)

        The smp_rmb() fence in P1 is a compiler barrier as well as a
        fence.  It guarantees that all the machine-level instructions
        corresponding to the access V will be po-after the fence, and
        therefore any loads among those instructions will execute
        after the fence does and hence after Y does.

Thus U's store to buf is forced to propagate to P1 before V's load
executes (assuming V does execute), ruling out the possibility of a
data race between them.

This analysis illustrates how the LKMM deals with plain accesses in
general.  Suppose R is a plain load and we want to show that R
executes before some marked access E.  We can do this by finding a
marked access X such that R and X are ordered by a suitable fence and
X ->xb* E.  If E was also a plain access, we would also look for a
marked access Y such that X ->xb* Y, and Y and E are ordered by a
fence.  We describe this arrangement by saying that R is
"post-bounded" by X and E is "pre-bounded" by Y.

In fact, we go one step further: Since R is a read, we say that R is
"r-post-bounded" by X.  Similarly, E would be "r-pre-bounded" or
"w-pre-bounded" by Y, depending on whether E was a store or a load.
This distinction is needed because some fences affect only loads
(i.e., smp_rmb()) and some affect only stores (smp_wmb()); otherwise
the two types of bounds are the same.  And as a degenerate case, we
say that a marked access pre-bounds and post-bounds itself (e.g., if R
above were a marked load then X could simply be taken to be R itself.)

The need to distinguish between r- and w-bounding raises yet another
issue.  When the source code contains a plain store, the compiler is
allowed to put plain loads of the same location into the object code.
For example, given the source code:

        x = 1;

the compiler is theoretically allowed to generate object code that
looks like:

        if (x != 1)
                x = 1;

thereby adding a load (and possibly replacing the store entirely).
For this reason, whenever the LKMM requires a plain store to be
w-pre-bounded or w-post-bounded by a marked access, it also requires
the store to be r-pre-bounded or r-post-bounded, so as to handle cases
where the compiler adds a load.

(This may be overly cautious.  We don't know of any examples where a
compiler has augmented a store with a load in this fashion, and the
Linux kernel developers would probably fight pretty hard to change a
compiler if it ever did this.  Still, better safe than sorry.)

Incidentally, the other tranformation -- augmenting a plain load by
adding in a store to the same location -- is not allowed.  This is
because the compiler cannot know whether any other CPUs might perform
a concurrent load from that location.  Two concurrent loads don't
constitute a race (they can't interfere with each other), but a store
does race with a concurrent load.  Thus adding a store might create a
data race where one was not already present in the source code,
something the compiler is forbidden to do.  Augmenting a store with a
load, on the other hand, is acceptable because doing so won't create a
data race unless one already existed.

The LKMM includes a second way to pre-bound plain accesses, in
addition to fences: an address dependency from a marked load.  That
is, in the sequence:

        p = READ_ONCE(ptr);
        r = *p;

the LKMM says that the marked load of ptr pre-bounds the plain load of
*p; the marked load must execute before any of the machine
instructions corresponding to the plain load.  This is a reasonable
stipulation, since after all, the CPU can't perform the load of *p
until it knows what value p will hold.  Furthermore, without some
assumption like this one, some usages typical of RCU would count as
data races.  For example:

        int a = 1, b;
        int *ptr = &a;

        P0()
        {
                b = 2;
                rcu_assign_pointer(ptr, &b);
        }

        P1()
        {
                int *p;
                int r;

                rcu_read_lock();
                p = rcu_dereference(ptr);
                r = *p;
                rcu_read_unlock();
        }

(In this example the rcu_read_lock() and rcu_read_unlock() calls don't
really do anything, because there aren't any grace periods.  They are
included merely for the sake of good form; typically P0 would call
synchronize_rcu() somewhere after the rcu_assign_pointer().)

rcu_assign_pointer() performs a store-release, so the plain store to b
is definitely w-post-bounded before the store to ptr, and the two
stores will propagate to P1 in that order.  However, rcu_dereference()
is only equivalent to READ_ONCE().  While it is a marked access, it is
not a fence or compiler barrier.  Hence the only guarantee we have
that the load of ptr in P1 is r-pre-bounded before the load of *p
(thus avoiding a race) is the assumption about address dependencies.

This is a situation where the compiler can undermine the memory model,
and a certain amount of care is required when programming constructs
like this one.  In particular, comparisons between the pointer and
other known addresses can cause trouble.  If you have something like:

        p = rcu_dereference(ptr);
        if (p == &x)
                r = *p;

then the compiler just might generate object code resembling:

        p = rcu_dereference(ptr);
        if (p == &x)
                r = x;

or even:

        rtemp = x;
        p = rcu_dereference(ptr);
        if (p == &x)
                r = rtemp;

which would invalidate the memory model's assumption, since the CPU
could now perform the load of x before the load of ptr (there might be
a control dependency but no address dependency at the machine level).

Finally, it turns out there is a situation in which a plain write does
not need to be w-post-bounded: when it is separated from the other
race-candidate access by a fence.  At first glance this may seem
impossible.  After all, to be race candidates the two accesses must
be on different CPUs, and fences don't link events on different CPUs.
Well, normal fences don't -- but rcu-fence can!  Here's an example:

        int x, y;

        P0()
        {
                WRITE_ONCE(x, 1);
                synchronize_rcu();
                y = 3;
        }

        P1()
        {
                rcu_read_lock();
                if (READ_ONCE(x) == 0)
                        y = 2;
                rcu_read_unlock();
        }

Do the plain stores to y race?  Clearly not if P1 reads a non-zero
value for x, so let's assume the READ_ONCE(x) does obtain 0.  This
means that the read-side critical section in P1 must finish executing
before the grace period in P0 does, because RCU's Grace-Period
Guarantee says that otherwise P0's store to x would have propagated to
P1 before the critical section started and so would have been visible
to the READ_ONCE().  (Another way of putting it is that the fre link
from the READ_ONCE() to the WRITE_ONCE() gives rise to an rcu-link
between those two events.)

This means there is an rcu-fence link from P1's "y = 2" store to P0's
"y = 3" store, and consequently the first must propagate from P1 to P0
before the second can execute.  Therefore the two stores cannot be
concurrent and there is no race, even though P1's plain store to y
isn't w-post-bounded by any marked accesses.

Putting all this material together yields the following picture.  For
race-candidate stores W and W', where W ->co W', the LKMM says the
stores don't race if W can be linked to W' by a

        w-post-bounded ; vis ; w-pre-bounded

sequence.  If W is plain then they also have to be linked by an

        r-post-bounded ; xb* ; w-pre-bounded

sequence, and if W' is plain then they also have to be linked by a

        w-post-bounded ; vis ; r-pre-bounded

sequence.  For race-candidate load R and store W, the LKMM says the
two accesses don't race if R can be linked to W by an

        r-post-bounded ; xb* ; w-pre-bounded

sequence or if W can be linked to R by a

        w-post-bounded ; vis ; r-pre-bounded

sequence.  For the cases involving a vis link, the LKMM also accepts
sequences in which W is linked to W' or R by a

        strong-fence ; xb* ; {w and/or r}-pre-bounded

sequence with no post-bounding, and in every case the LKMM also allows
the link simply to be a fence with no bounding at all.  If no sequence
of the appropriate sort exists, the LKMM says that the accesses race.

There is one more part of the LKMM related to plain accesses (although
not to data races) we should discuss.  Recall that many relations such
as hb are limited to marked accesses only.  As a result, the
happens-before, propagates-before, and rcu axioms (which state that
various relation must not contain a cycle) doesn't apply to plain
accesses.  Nevertheless, we do want to rule out such cycles, because
they don't make sense even for plain accesses.

To this end, the LKMM imposes three extra restrictions, together
called the "plain-coherence" axiom because of their resemblance to the
rules used by the operational model to ensure cache coherence (that
is, the rules governing the memory subsystem's choice of a store to
satisfy a load request and its determination of where a store will
fall in the coherence order):

        If R and W are race candidates and it is possible to link R to
        W by one of the xb* sequences listed above, then W ->rfe R is
        not allowed (i.e., a load cannot read from a store that it
        executes before, even if one or both is plain).

        If W and R are race candidates and it is possible to link W to
        R by one of the vis sequences listed above, then R ->fre W is
        not allowed (i.e., if a store is visible to a load then the
        load must read from that store or one coherence-after it).

        If W and W' are race candidates and it is possible to link W
        to W' by one of the vis sequences listed above, then W' ->co W
        is not allowed (i.e., if one store is visible to a second then
        the second must come after the first in the coherence order).

This is the extent to which the LKMM deals with plain accesses.
Perhaps it could say more (for example, plain accesses might
contribute to the ppo relation), but at the moment it seems that this
minimal, conservative approach is good enough.


ODDS AND ENDS
-------------

This section covers material that didn't quite fit anywhere in the
earlier sections.

The descriptions in this document don't always match the formal
version of the LKMM exactly.  For example, the actual formal
definition of the prop relation makes the initial coe or fre part
optional, and it doesn't require the events linked by the relation to
be on the same CPU.  These differences are very unimportant; indeed,
instances where the coe/fre part of prop is missing are of no interest
because all the other parts (fences and rfe) are already included in
hb anyway, and where the formal model adds prop into hb, it includes
an explicit requirement that the events being linked are on the same
CPU.

Another minor difference has to do with events that are both memory
accesses and fences, such as those corresponding to smp_load_acquire()
calls.  In the formal model, these events aren't actually both reads
and fences; rather, they are read events with an annotation marking
them as acquires.  (Or write events annotated as releases, in the case
smp_store_release().)  The final effect is the same.

Although we didn't mention it above, the instruction execution
ordering provided by the smp_rmb() fence doesn't apply to read events
that are part of a non-value-returning atomic update.  For instance,
given:

        atomic_inc(&x);
        smp_rmb();
        r1 = READ_ONCE(y);

it is not guaranteed that the load from y will execute after the
update to x.  This is because the ARMv8 architecture allows
non-value-returning atomic operations effectively to be executed off
the CPU.  Basically, the CPU tells the memory subsystem to increment
x, and then the increment is carried out by the memory hardware with
no further involvement from the CPU.  Since the CPU doesn't ever read
the value of x, there is nothing for the smp_rmb() fence to act on.

The LKMM defines a few extra synchronization operations in terms of
things we have already covered.  In particular, rcu_dereference() is
treated as READ_ONCE() and rcu_assign_pointer() is treated as
smp_store_release() -- which is basically how the Linux kernel treats
them.

Although we said that plain accesses are not linked by the ppo
relation, they do contribute to it indirectly.  Firstly, when there is
an address dependency from a marked load R to a plain store W,
followed by smp_wmb() and then a marked store W', the LKMM creates a
ppo link from R to W'.  The reasoning behind this is perhaps a little
shaky, but essentially it says there is no way to generate object code
for this source code in which W' could execute before R.  Just as with
pre-bounding by address dependencies, it is possible for the compiler
to undermine this relation if sufficient care is not taken.

Secondly, plain accesses can carry dependencies: If a data dependency
links a marked load R to a store W, and the store is read by a load R'
from the same thread, then the data loaded by R' depends on the data
loaded originally by R. Thus, if R' is linked to any access X by a
dependency, R is also linked to access X by the same dependency, even
if W' or R' (or both!) are plain.

There are a few oddball fences which need special treatment:
smp_mb__before_atomic(), smp_mb__after_atomic(), and
smp_mb__after_spinlock().  The LKMM uses fence events with special
annotations for them; they act as strong fences just like smp_mb()
except for the sets of events that they order.  Instead of ordering
all po-earlier events against all po-later events, as smp_mb() does,
they behave as follows:

        smp_mb__before_atomic() orders all po-earlier events against
        po-later atomic updates and the events following them;

        smp_mb__after_atomic() orders po-earlier atomic updates and
        the events preceding them against all po-later events;

        smp_mb__after_spinlock() orders po-earlier lock acquisition
        events and the events preceding them against all po-later
        events.

Interestingly, RCU and locking each introduce the possibility of
deadlock.  When faced with code sequences such as:

        spin_lock(&s);
        spin_lock(&s);
        spin_unlock(&s);
        spin_unlock(&s);

or:

        rcu_read_lock();
        synchronize_rcu();
        rcu_read_unlock();

what does the LKMM have to say?  Answer: It says there are no allowed
executions at all, which makes sense.  But this can also lead to
misleading results, because if a piece of code has multiple possible
executions, some of which deadlock, the model will report only on the
non-deadlocking executions.  For example:

        int x, y;

        P0()
        {
                int r0;

                WRITE_ONCE(x, 1);
                r0 = READ_ONCE(y);
        }

        P1()
        {
                rcu_read_lock();
                if (READ_ONCE(x) > 0) {
                        WRITE_ONCE(y, 36);
                        synchronize_rcu();
                }
                rcu_read_unlock();
        }

Is it possible to end up with r0 = 36 at the end?  The LKMM will tell
you it is not, but the model won't mention that this is because P1
will self-deadlock in the executions where it stores 36 in y.

Glossary

Peios Kernel / Kernel development / Development tools / lkmm / docs

Literal include of tools/memory-model/Documentation/glossary.txt.


This document contains brief definitions of LKMM-related terms.  Like most
glossaries, it is not intended to be read front to back (except perhaps
as a way of confirming a diagnosis of OCD), but rather to be searched
for specific terms.


Address Dependency:  When the address of a later memory access is computed
        based on the value returned by an earlier load, an "address
        dependency" extends from that load extending to the later access.
        Address dependencies are quite common in RCU read-side critical
        sections:

         1 rcu_read_lock();
         2 p = rcu_dereference(gp);
         3 do_something(p->a);
         4 rcu_read_unlock();

        In this case, because the address of "p->a" on line 3 is computed
        from the value returned by the rcu_dereference() on line 2, the
        address dependency extends from that rcu_dereference() to that
        "p->a".  In rare cases, optimizing compilers can destroy address
        dependencies.   Please see Documentation/RCU/rcu_dereference.rst
        for more information.

        See also "Control Dependency" and "Data Dependency".

Acquire:  With respect to a lock, acquiring that lock, for example,
        using spin_lock().  With respect to a non-lock shared variable,
        a special operation that includes a load and which orders that
        load before later memory references running on that same CPU.
        An example special acquire operation is smp_load_acquire(),
        but atomic_read_acquire() and atomic_xchg_acquire() also include
        acquire loads.

        When an acquire load returns the value stored by a release store
        to that same variable, (in other words, the acquire load "reads
        from" the release store), then all operations preceding that
        store "happen before" any operations following that load acquire.

        See also "Happens-Before", "Reads-From", "Relaxed", and "Release".

Coherence (co):  When one CPU's store to a given variable overwrites
        either the value from another CPU's store or some later value,
        there is said to be a coherence link from the second CPU to
        the first.

        It is also possible to have a coherence link within a CPU, which
        is a "coherence internal" (coi) link.  The term "coherence
        external" (coe) link is used when it is necessary to exclude
        the coi case.

        See also "From-reads" and "Reads-from".

Control Dependency:  When a later store's execution depends on a test
        of a value computed from a value returned by an earlier load,
        a "control dependency" extends from that load to that store.
        For example:

         1 if (READ_ONCE(x))
         2   WRITE_ONCE(y, 1);

        Here, the control dependency extends from the READ_ONCE() on
        line 1 to the WRITE_ONCE() on line 2.   Control dependencies are
        fragile, and can be easily destroyed by optimizing compilers.
        Please see control-dependencies.txt for more information.

        See also "Address Dependency" and "Data Dependency".

Cycle:  Memory-barrier pairing is restricted to a pair of CPUs, as the
        name suggests.  And in a great many cases, a pair of CPUs is all
        that is required.  In other cases, the notion of pairing must be
        extended to additional CPUs, and the result is called a "cycle".
        In a cycle, each CPU's ordering interacts with that of the next:

         CPU 0                CPU 1                CPU 2
         WRITE_ONCE(x, 1);    WRITE_ONCE(y, 1);    WRITE_ONCE(z, 1);
         smp_mb();            smp_mb();            smp_mb();
         r0 = READ_ONCE(y);   r1 = READ_ONCE(z);   r2 = READ_ONCE(x);

        CPU 0's smp_mb() interacts with that of CPU 1, which interacts
        with that of CPU 2, which in turn interacts with that of CPU 0
        to complete the cycle.  Because of the smp_mb() calls between
        each pair of memory accesses, the outcome where r0, r1, and r2
        are all equal to zero is forbidden by LKMM.

        See also "Pairing".

Data Dependency:  When the data written by a later store is computed based
        on the value returned by an earlier load, a "data dependency"
        extends from that load to that later store.  For example:

         1 r1 = READ_ONCE(x);
         2 WRITE_ONCE(y, r1 + 1);

        In this case, the data dependency extends from the READ_ONCE()
        on line 1 to the WRITE_ONCE() on line 2.  Data dependencies are
        fragile and can be easily destroyed by optimizing compilers.
        Because optimizing compilers put a great deal of effort into
        working out what values integer variables might have, this is
        especially true in cases where the dependency is carried through
        an integer.

        See also "Address Dependency" and "Control Dependency".

From-Reads (fr):  When one CPU's store to a given variable happened
        too late to affect the value returned by another CPU's
        load from that same variable, there is said to be a from-reads
        link from the load to the store.

        It is also possible to have a from-reads link within a CPU, which
        is a "from-reads internal" (fri) link.  The term "from-reads
        external" (fre) link is used when it is necessary to exclude
        the fri case.

        See also "Coherence" and "Reads-from".

Fully Ordered:  An operation such as smp_mb() that orders all of
        its CPU's prior accesses with all of that CPU's subsequent
        accesses, or a marked access such as atomic_add_return()
        that orders all of its CPU's prior accesses, itself, and
        all of its CPU's subsequent accesses.

Happens-Before (hb): A relation between two accesses in which LKMM
        guarantees the first access precedes the second.  For more
        detail, please see the "THE HAPPENS-BEFORE RELATION: hb"
        section of explanation.txt.

Marked Access:  An access to a variable that uses an special function or
        macro such as "r1 = READ_ONCE(x)" or "smp_store_release(&a, 1)".

        See also "Unmarked Access".

Pairing: "Memory-barrier pairing" reflects the fact that synchronizing
        data between two CPUs requires that both CPUs their accesses.
        Memory barriers thus tend to come in pairs, one executed by
        one of the CPUs and the other by the other CPU.  Of course,
        pairing also occurs with other types of operations, so that a
        smp_store_release() pairs with an smp_load_acquire() that reads
        the value stored.

        See also "Cycle".

Reads-From (rf):  When one CPU's load returns the value stored by some other
        CPU, there is said to be a reads-from link from the second
        CPU's store to the first CPU's load.  Reads-from links have the
        nice property that time must advance from the store to the load,
        which means that algorithms using reads-from links can use lighter
        weight ordering and synchronization compared to algorithms using
        coherence and from-reads links.

        It is also possible to have a reads-from link within a CPU, which
        is a "reads-from internal" (rfi) link.  The term "reads-from
        external" (rfe) link is used when it is necessary to exclude
        the rfi case.

        See also Coherence" and "From-reads".

Relaxed:  A marked access that does not imply ordering, for example, a
        READ_ONCE(), WRITE_ONCE(), a non-value-returning read-modify-write
        operation, or a value-returning read-modify-write operation whose
        name ends in "_relaxed".

        See also "Acquire" and "Release".

Release:  With respect to a lock, releasing that lock, for example,
        using spin_unlock().  With respect to a non-lock shared variable,
        a special operation that includes a store and which orders that
        store after earlier memory references that ran on that same CPU.
        An example special release store is smp_store_release(), but
        atomic_set_release() and atomic_cmpxchg_release() also include
        release stores.

        See also "Acquire" and "Relaxed".

Unmarked Access:  An access to a variable that uses normal C-language
        syntax, for example, "a = b[2]";

        See also "Marked Access".

herd-representation

Peios Kernel / Kernel development / Development tools / lkmm / docs

Literal include of tools/memory-model/Documentation/herd-representation.txt.


#
# Legend:
#       R,      a Load event
#       W,      a Store event
#       F,      a Fence event
#       LKR,    a Lock-Read event
#       LKW,    a Lock-Write event
#       UL,     an Unlock event
#       LF,     a Lock-Fail event
#       RL,     a Read-Locked event
#       RU,     a Read-Unlocked event
#       R*,     a Load event included in RMW
#       W*,     a Store event included in RMW
#       SRCU,   a Sleepable-Read-Copy-Update event
#
#       po,     a Program-Order link
#       rmw,    a Read-Modify-Write link - every rmw link is a po link
#
# By convention, a blank line in a cell means "same as the preceding line".
#
# Note that the syntactic representation does not always match the sets and
# relations in linux-kernel.cat, due to redefinitions in linux-kernel.bell and
# lock.cat. For example, the po link between LKR and LKW is upgraded to an rmw
# link, and W[ACQUIRE] are not included in the Acquire set.
#
# Disclaimer.  The table includes representations of "add" and "and" operations;
# corresponding/identical representations of "sub", "inc", "dec" and "or", "xor",
# "andnot" operations are omitted.
#
    ------------------------------------------------------------------------------
    |                        C macro | Events                                    |
    ------------------------------------------------------------------------------
    |                    Non-RMW ops |                                           |
    ------------------------------------------------------------------------------
    |                      READ_ONCE | R[ONCE]                                   |
    |                    atomic_read |                                           |
    |                     WRITE_ONCE | W[ONCE]                                   |
    |                     atomic_set |                                           |
    |               smp_load_acquire | R[ACQUIRE]                                |
    |            atomic_read_acquire |                                           |
    |              smp_store_release | W[RELEASE]                                |
    |             atomic_set_release |                                           |
    |                   smp_store_mb | W[ONCE] ->po F[MB]                        |
    |                         smp_mb | F[MB]                                     |
    |                        smp_rmb | F[rmb]                                    |
    |                        smp_wmb | F[wmb]                                    |
    |          smp_mb__before_atomic | F[before-atomic]                          |
    |           smp_mb__after_atomic | F[after-atomic]                           |
    |                    spin_unlock | UL                                        |
    |                 spin_is_locked | On success: RL                            |
    |                                | On failure: RU                            |
    |         smp_mb__after_spinlock | F[after-spinlock]                         |
    |      smp_mb__after_unlock_lock | F[after-unlock-lock]                      |
    |                  rcu_read_lock | F[rcu-lock]                               |
    |                rcu_read_unlock | F[rcu-unlock]                             |
    |                synchronize_rcu | F[sync-rcu]                               |
    |                rcu_dereference | R[ONCE]                                   |
    |             rcu_assign_pointer | W[RELEASE]                                |
    |                 srcu_read_lock | R[srcu-lock]                              |
    |                 srcu_down_read |                                           |
    |               srcu_read_unlock | W[srcu-unlock]                            |
    |                   srcu_up_read |                                           |
    |               synchronize_srcu | SRCU[sync-srcu]                           |
    | smp_mb__after_srcu_read_unlock | F[after-srcu-read-unlock]                 |
    ------------------------------------------------------------------------------
    |       RMW ops w/o return value |                                           |
    ------------------------------------------------------------------------------
    |                     atomic_add | R*[NORETURN] ->rmw W*[NORETURN]           |
    |                     atomic_and |                                           |
    |                      spin_lock | LKR ->po LKW                              |
    ------------------------------------------------------------------------------
    |        RMW ops w/ return value |                                           |
    ------------------------------------------------------------------------------
    |              atomic_add_return | R*[MB] ->rmw W*[MB]                       |
    |               atomic_fetch_add |                                           |
    |               atomic_fetch_and |                                           |
    |                    atomic_xchg |                                           |
    |                           xchg |                                           |
    |            atomic_add_negative |                                           |
    |      atomic_add_return_relaxed | R*[ONCE] ->rmw W*[ONCE]                   |
    |       atomic_fetch_add_relaxed |                                           |
    |       atomic_fetch_and_relaxed |                                           |
    |            atomic_xchg_relaxed |                                           |
    |                   xchg_relaxed |                                           |
    |    atomic_add_negative_relaxed |                                           |
    |      atomic_add_return_acquire | R*[ACQUIRE] ->rmw W*[ACQUIRE]             |
    |       atomic_fetch_add_acquire |                                           |
    |       atomic_fetch_and_acquire |                                           |
    |            atomic_xchg_acquire |                                           |
    |                   xchg_acquire |                                           |
    |    atomic_add_negative_acquire |                                           |
    |      atomic_add_return_release | R*[RELEASE] ->rmw W*[RELEASE]             |
    |       atomic_fetch_add_release |                                           |
    |       atomic_fetch_and_release |                                           |
    |            atomic_xchg_release |                                           |
    |                   xchg_release |                                           |
    |    atomic_add_negative_release |                                           |
    ------------------------------------------------------------------------------
    |            Conditional RMW ops |                                           |
    ------------------------------------------------------------------------------
    |                 atomic_cmpxchg | On success: R*[MB] ->rmw W*[MB]           |
    |                                | On failure: R*[MB]                        |
    |                        cmpxchg |                                           |
    |              atomic_add_unless |                                           |
    |         atomic_cmpxchg_relaxed | On success: R*[ONCE] ->rmw W*[ONCE]       |
    |                                | On failure: R*[ONCE]                      |
    |         atomic_cmpxchg_acquire | On success: R*[ACQUIRE] ->rmw W*[ACQUIRE] |
    |                                | On failure: R*[ACQUIRE]                   |
    |         atomic_cmpxchg_release | On success: R*[RELEASE] ->rmw W*[RELEASE] |
    |                                | On failure: R*[RELEASE]                   |
    |                   spin_trylock | On success: LKR ->po LKW                  |
    |                                | On failure: LF                            |
    ------------------------------------------------------------------------------

Litmus Tests

Peios Kernel / Kernel development / Development tools / lkmm / docs

Literal include of tools/memory-model/Documentation/litmus-tests.txt.


Linux-Kernel Memory Model Litmus Tests
======================================

This file describes the LKMM litmus-test format by example, describes
some tricks and traps, and finally outlines LKMM's limitations.  Earlier
versions of this material appeared in a number of LWN articles, including:

https://lwn.net/Articles/720550/
        A formal kernel memory-ordering model (part 2)
https://lwn.net/Articles/608550/
        Axiomatic validation of memory barriers and atomic instructions
https://lwn.net/Articles/470681/
        Validating Memory Barriers and Atomic Instructions

This document presents information in decreasing order of applicability,
so that, where possible, the information that has proven more commonly
useful is shown near the beginning.

For information on installing LKMM, including the underlying "herd7"
tool, please see tools/memory-model/README.


Copy-Pasta
==========

As with other software, it is often better (if less macho) to adapt an
existing litmus test than it is to create one from scratch.  A number
of litmus tests may be found in the kernel source tree:

        tools/memory-model/litmus-tests/
        Documentation/litmus-tests/

Several thousand more example litmus tests are available on github
and kernel.org:

        https://github.com/paulmckrcu/litmus
        https://git.kernel.org/pub/scm/linux/kernel/git/paulmck/perfbook.git/tree/CodeSamples/formal/herd
        https://git.kernel.org/pub/scm/linux/kernel/git/paulmck/perfbook.git/tree/CodeSamples/formal/litmus

The -l and -L arguments to "git grep" can be quite helpful in identifying
existing litmus tests that are similar to the one you need.  But even if
you start with an existing litmus test, it is still helpful to have a
good understanding of the litmus-test format.


Examples and Format
===================

This section describes the overall format of litmus tests, starting
with a small example of the message-passing pattern and moving on to
more complex examples that illustrate explicit initialization and LKMM's
minimalistic set of flow-control statements.


Message-Passing Example
-----------------------

This section gives an overview of the format of a litmus test using an
example based on the common message-passing use case.  This use case
appears often in the Linux kernel.  For example, a flag (modeled by "y"
below) indicates that a buffer (modeled by "x" below) is now completely
filled in and ready for use.  It would be very bad if the consumer saw the
flag set, but, due to memory misordering, saw old values in the buffer.

This example asks whether smp_store_release() and smp_load_acquire()
suffices to avoid this bad outcome:

 1 C MP+pooncerelease+poacquireonce
 2
 3 {}
 4
 5 P0(int *x, int *y)
 6 {
 7   WRITE_ONCE(*x, 1);
 8   smp_store_release(y, 1);
 9 }
10
11 P1(int *x, int *y)
12 {
13   int r0;
14   int r1;
15
16   r0 = smp_load_acquire(y);
17   r1 = READ_ONCE(*x);
18 }
19
20 exists (1:r0=1 /\ 1:r1=0)

Line 1 starts with "C", which identifies this file as being in the
LKMM C-language format (which, as we will see, is a small fragment
of the full C language).  The remainder of line 1 is the name of
the test, which by convention is the filename with the ".litmus"
suffix stripped.  In this case, the actual test may be found in
tools/memory-model/litmus-tests/MP+pooncerelease+poacquireonce.litmus
in the Linux-kernel source tree.

Mechanically generated litmus tests will often have an optional
double-quoted comment string on the second line.  Such strings are ignored
when running the test.  Yes, you can add your own comments to litmus
tests, but this is a bit involved due to the use of multiple parsers.
For now, you can use C-language comments in the C code, and these comments
may be in either the "/* */" or the "//" style.  A later section will
cover the full litmus-test commenting story.

Line 3 is the initialization section.  Because the default initialization
to zero suffices for this test, the "{}" syntax is used, which mean the
initialization section is empty.  Litmus tests requiring non-default
initialization must have non-empty initialization sections, as in the
example that will be presented later in this document.

Lines 5-9 show the first process and lines 11-18 the second process.  Each
process corresponds to a Linux-kernel task (or kthread, workqueue, thread,
and so on; LKMM discussions often use these terms interchangeably).
The name of the first process is "P0" and that of the second "P1".
You can name your processes anything you like as long as the names consist
of a single "P" followed by a number, and as long as the numbers are
consecutive starting with zero.  This can actually be quite helpful,
for example, a .litmus file matching "^P1(" but not matching "^P2("
must contain a two-process litmus test.

The argument list for each function are pointers to the global variables
used by that function.  Unlike normal C-language function parameters, the
names are significant.  The fact that both P0() and P1() have a formal
parameter named "x" means that these two processes are working with the
same global variable, also named "x".  So the "int *x, int *y" on P0()
and P1() mean that both processes are working with two shared global
variables, "x" and "y".  Global variables are always passed to processes
by reference, hence "P0(int *x, int *y)", but *never* "P0(int x, int y)".

P0() has no local variables, but P1() has two of them named "r0" and "r1".
These names may be freely chosen, but for historical reasons stemming from
other litmus-test formats, it is conventional to use names consisting of
"r" followed by a number as shown here.  A common bug in litmus tests
is forgetting to add a global variable to a process's parameter list.
This will sometimes result in an error message, but can also cause the
intended global to instead be silently treated as an undeclared local
variable.

Each process's code is similar to Linux-kernel C, as can be seen on lines
7-8 and 13-17.  This code may use many of the Linux kernel's atomic
operations, some of its exclusive-lock functions, and some of its RCU
and SRCU functions.  An approximate list of the currently supported
functions may be found in the linux-kernel.def file.

The P0() process does "WRITE_ONCE(*x, 1)" on line 7.  Because "x" is a
pointer in P0()'s parameter list, this does an unordered store to global
variable "x".  Line 8 does "smp_store_release(y, 1)", and because "y"
is also in P0()'s parameter list, this does a release store to global
variable "y".

The P1() process declares two local variables on lines 13 and 14.
Line 16 does "r0 = smp_load_acquire(y)" which does an acquire load
from global variable "y" into local variable "r0".  Line 17 does a
"r1 = READ_ONCE(*x)", which does an unordered load from "*x" into local
variable "r1".  Both "x" and "y" are in P1()'s parameter list, so both
reference the same global variables that are used by P0().

Line 20 is the "exists" assertion expression to evaluate the final state.
This final state is evaluated after the dust has settled: both processes
have completed and all of their memory references and memory barriers
have propagated to all parts of the system.  The references to the local
variables "r0" and "r1" in line 24 must be prefixed with "1:" to specify
which process they are local to.

Note that the assertion expression is written in the litmus-test
language rather than in C.  For example, single "=" is an equality
operator rather than an assignment.  The "/\" character combination means
"and".  Similarly, "\/" stands for "or".  Both of these are ASCII-art
representations of the corresponding mathematical symbols.  Finally,
"~" stands for "logical not", which is "!" in C, and not to be confused
with the C-language "~" operator which instead stands for "bitwise not".
Parentheses may be used to override precedence.

The "exists" assertion on line 20 is satisfied if the consumer sees the
flag ("y") set but the buffer ("x") as not yet filled in, that is, if P1()
loaded a value from "x" that was equal to 1 but loaded a value from "y"
that was still equal to zero.

This example can be checked by running the following command, which
absolutely must be run from the tools/memory-model directory and from
this directory only:

herd7 -conf linux-kernel.cfg litmus-tests/MP+pooncerelease+poacquireonce.litmus

The output is the result of something similar to a full state-space
search, and is as follows:

 1 Test MP+pooncerelease+poacquireonce Allowed
 2 States 3
 3 1:r0=0; 1:r1=0;
 4 1:r0=0; 1:r1=1;
 5 1:r0=1; 1:r1=1;
 6 No
 7 Witnesses
 8 Positive: 0 Negative: 3
 9 Condition exists (1:r0=1 /\ 1:r1=0)
10 Observation MP+pooncerelease+poacquireonce Never 0 3
11 Time MP+pooncerelease+poacquireonce 0.00
12 Hash=579aaa14d8c35a39429b02e698241d09

The most pertinent line is line 10, which contains "Never 0 3", which
indicates that the bad result flagged by the "exists" clause never
happens.  This line might instead say "Sometimes" to indicate that the
bad result happened in some but not all executions, or it might say
"Always" to indicate that the bad result happened in all executions.
(The herd7 tool doesn't judge, so it is only an LKMM convention that the
"exists" clause indicates a bad result.  To see this, invert the "exists"
clause's condition and run the test.)  The numbers ("0 3") at the end
of this line indicate the number of end states satisfying the "exists"
clause (0) and the number not not satisfying that clause (3).

Another important part of this output is shown in lines 2-5, repeated here:

 2 States 3
 3 1:r0=0; 1:r1=0;
 4 1:r0=0; 1:r1=1;
 5 1:r0=1; 1:r1=1;

Line 2 gives the total number of end states, and each of lines 3-5 list
one of these states, with the first ("1:r0=0; 1:r1=0;") indicating that
both of P1()'s loads returned the value "0".  As expected, given the
"Never" on line 10, the state flagged by the "exists" clause is not
listed.  This full list of states can be helpful when debugging a new
litmus test.

The rest of the output is not normally needed, either due to irrelevance
or due to being redundant with the lines discussed above.  However, the
following paragraph lists them for the benefit of readers possessed of
an insatiable curiosity.  Other readers should feel free to skip ahead.

Line 1 echos the test name, along with the "Test" and "Allowed".  Line 6's
"No" says that the "exists" clause was not satisfied by any execution,
and as such it has the same meaning as line 10's "Never".  Line 7 is a
lead-in to line 8's "Positive: 0 Negative: 3", which lists the number
of end states satisfying and not satisfying the "exists" clause, just
like the two numbers at the end of line 10.  Line 9 repeats the "exists"
clause so that you don't have to look it up in the litmus-test file.
The number at the end of line 11 (which begins with "Time") gives the
time in seconds required to analyze the litmus test.  Small tests such
as this one complete in a few milliseconds, so "0.00" is quite common.
Line 12 gives a hash of the contents for the litmus-test file, and is used
by tooling that manages litmus tests and their output.  This tooling is
used by people modifying LKMM itself, and among other things lets such
people know which of the several thousand relevant litmus tests were
affected by a given change to LKMM.


Initialization
--------------

The previous example relied on the default zero initialization for
"x" and "y", but a similar litmus test could instead initialize them
to some other value:

 1 C MP+pooncerelease+poacquireonce
 2
 3 {
 4   x=42;
 5   y=42;
 6 }
 7
 8 P0(int *x, int *y)
 9 {
10   WRITE_ONCE(*x, 1);
11   smp_store_release(y, 1);
12 }
13
14 P1(int *x, int *y)
15 {
16   int r0;
17   int r1;
18
19   r0 = smp_load_acquire(y);
20   r1 = READ_ONCE(*x);
21 }
22
23 exists (1:r0=1 /\ 1:r1=42)

Lines 3-6 now initialize both "x" and "y" to the value 42.  This also
means that the "exists" clause on line 23 must change "1:r1=0" to
"1:r1=42".

Running the test gives the same overall result as before, but with the
value 42 appearing in place of the value zero:

 1 Test MP+pooncerelease+poacquireonce Allowed
 2 States 3
 3 1:r0=1; 1:r1=1;
 4 1:r0=42; 1:r1=1;
 5 1:r0=42; 1:r1=42;
 6 No
 7 Witnesses
 8 Positive: 0 Negative: 3
 9 Condition exists (1:r0=1 /\ 1:r1=42)
10 Observation MP+pooncerelease+poacquireonce Never 0 3
11 Time MP+pooncerelease+poacquireonce 0.02
12 Hash=ab9a9b7940a75a792266be279a980156

It is tempting to avoid the open-coded repetitions of the value "42"
by defining another global variable "initval=42" and replacing all
occurrences of "42" with "initval".  This will not, repeat *not*,
initialize "x" and "y" to 42, but instead to the address of "initval"
(try it!).  See the section below on linked lists to learn more about
why this approach to initialization can be useful.


Control Structures
------------------

LKMM supports the C-language "if" statement, which allows modeling of
conditional branches.  In LKMM, conditional branches can affect ordering,
but only if you are *very* careful (compilers are surprisingly able
to optimize away conditional branches).  The following example shows
the "load buffering" (LB) use case that is used in the Linux kernel to
synchronize between ring-buffer producers and consumers.  In the example
below, P0() is one side checking to see if an operation may proceed and
P1() is the other side completing its update.

 1 C LB+fencembonceonce+ctrlonceonce
 2
 3 {}
 4
 5 P0(int *x, int *y)
 6 {
 7   int r0;
 8
 9   r0 = READ_ONCE(*x);
10   if (r0)
11     WRITE_ONCE(*y, 1);
12 }
13
14 P1(int *x, int *y)
15 {
16   int r0;
17
18   r0 = READ_ONCE(*y);
19   smp_mb();
20   WRITE_ONCE(*x, 1);
21 }
22
23 exists (0:r0=1 /\ 1:r0=1)

P1()'s "if" statement on line 10 works as expected, so that line 11 is
executed only if line 9 loads a non-zero value from "x".  Because P1()'s
write of "1" to "x" happens only after P1()'s read from "y", one would
hope that the "exists" clause cannot be satisfied.  LKMM agrees:

 1 Test LB+fencembonceonce+ctrlonceonce Allowed
 2 States 2
 3 0:r0=0; 1:r0=0;
 4 0:r0=1; 1:r0=0;
 5 No
 6 Witnesses
 7 Positive: 0 Negative: 2
 8 Condition exists (0:r0=1 /\ 1:r0=1)
 9 Observation LB+fencembonceonce+ctrlonceonce Never 0 2
10 Time LB+fencembonceonce+ctrlonceonce 0.00
11 Hash=e5260556f6de495fd39b556d1b831c3b

However, there is no "while" statement due to the fact that full
state-space search has some difficulty with iteration.  However, there
are tricks that may be used to handle some special cases, which are
discussed below.  In addition, loop-unrolling tricks may be applied,
albeit sparingly.


Tricks and Traps
================

This section covers extracting debug output from herd7, emulating
spin loops, handling trivial linked lists, adding comments to litmus tests,
emulating call_rcu(), and finally tricks to improve herd7 performance
in order to better handle large litmus tests.


Debug Output
------------

By default, the herd7 state output includes all variables mentioned
in the "exists" clause.  But sometimes debugging efforts are greatly
aided by the values of other variables.  Consider this litmus test
(tools/memory-order/litmus-tests/SB+rfionceonce-poonceonces.litmus but
slightly modified), which probes an obscure corner of hardware memory
ordering:

 1 C SB+rfionceonce-poonceonces
 2
 3 {}
 4
 5 P0(int *x, int *y)
 6 {
 7   int r1;
 8   int r2;
 9
10   WRITE_ONCE(*x, 1);
11   r1 = READ_ONCE(*x);
12   r2 = READ_ONCE(*y);
13 }
14
15 P1(int *x, int *y)
16 {
17   int r3;
18   int r4;
19
20   WRITE_ONCE(*y, 1);
21   r3 = READ_ONCE(*y);
22   r4 = READ_ONCE(*x);
23 }
24
25 exists (0:r2=0 /\ 1:r4=0)

The herd7 output is as follows:

 1 Test SB+rfionceonce-poonceonces Allowed
 2 States 4
 3 0:r2=0; 1:r4=0;
 4 0:r2=0; 1:r4=1;
 5 0:r2=1; 1:r4=0;
 6 0:r2=1; 1:r4=1;
 7 Ok
 8 Witnesses
 9 Positive: 1 Negative: 3
10 Condition exists (0:r2=0 /\ 1:r4=0)
11 Observation SB+rfionceonce-poonceonces Sometimes 1 3
12 Time SB+rfionceonce-poonceonces 0.01
13 Hash=c7f30fe0faebb7d565405d55b7318ada

(This output indicates that CPUs are permitted to "snoop their own
store buffers", which all of Linux's CPU families other than s390 will
happily do.  Such snooping results in disagreement among CPUs on the
order of stores from different CPUs, which is rarely an issue.)

But the herd7 output shows only the two variables mentioned in the
"exists" clause.  Someone modifying this test might wish to know the
values of "x", "y", "0:r1", and "0:r3" as well.  The "locations"
statement on line 25 shows how to cause herd7 to display additional
variables:

 1 C SB+rfionceonce-poonceonces
 2
 3 {}
 4
 5 P0(int *x, int *y)
 6 {
 7   int r1;
 8   int r2;
 9
10   WRITE_ONCE(*x, 1);
11   r1 = READ_ONCE(*x);
12   r2 = READ_ONCE(*y);
13 }
14
15 P1(int *x, int *y)
16 {
17   int r3;
18   int r4;
19
20   WRITE_ONCE(*y, 1);
21   r3 = READ_ONCE(*y);
22   r4 = READ_ONCE(*x);
23 }
24
25 locations [0:r1; 1:r3; x; y]
26 exists (0:r2=0 /\ 1:r4=0)

The herd7 output then displays the values of all the variables:

 1 Test SB+rfionceonce-poonceonces Allowed
 2 States 4
 3 0:r1=1; 0:r2=0; 1:r3=1; 1:r4=0; x=1; y=1;
 4 0:r1=1; 0:r2=0; 1:r3=1; 1:r4=1; x=1; y=1;
 5 0:r1=1; 0:r2=1; 1:r3=1; 1:r4=0; x=1; y=1;
 6 0:r1=1; 0:r2=1; 1:r3=1; 1:r4=1; x=1; y=1;
 7 Ok
 8 Witnesses
 9 Positive: 1 Negative: 3
10 Condition exists (0:r2=0 /\ 1:r4=0)
11 Observation SB+rfionceonce-poonceonces Sometimes 1 3
12 Time SB+rfionceonce-poonceonces 0.01
13 Hash=40de8418c4b395388f6501cafd1ed38d

What if you would like to know the value of a particular global variable
at some particular point in a given process's execution?  One approach
is to use a READ_ONCE() to load that global variable into a new local
variable, then add that local variable to the "locations" clause.
But be careful:  In some litmus tests, adding a READ_ONCE() will change
the outcome!  For one example, please see the C-READ_ONCE.litmus and
C-READ_ONCE-omitted.litmus tests located here:

        https://github.com/paulmckrcu/litmus/blob/master/manual/kernel/


Spin Loops
----------

The analysis carried out by herd7 explores full state space, which is
at best of exponential time complexity.  Adding processes and increasing
the amount of code in a give process can greatly increase execution time.
Potentially infinite loops, such as those used to wait for locks to
become available, are clearly problematic.

Fortunately, it is possible to avoid state-space explosion by specially
modeling such loops.  For example, the following litmus tests emulates
locking using xchg_acquire(), but instead of enclosing xchg_acquire()
in a spin loop, it instead excludes executions that fail to acquire the
lock using a herd7 "filter" clause.  Note that for exclusive locking, you
are better off using the spin_lock() and spin_unlock() that LKMM directly
models, if for no other reason that these are much faster.  However, the
techniques illustrated in this section can be used for other purposes,
such as emulating reader-writer locking, which LKMM does not yet model.

 1 C C-SB+l-o-o-u+l-o-o-u-X
 2
 3 {
 4 }
 5
 6 P0(int *sl, int *x0, int *x1)
 7 {
 8   int r2;
 9   int r1;
10
11   r2 = xchg_acquire(sl, 1);
12   WRITE_ONCE(*x0, 1);
13   r1 = READ_ONCE(*x1);
14   smp_store_release(sl, 0);
15 }
16
17 P1(int *sl, int *x0, int *x1)
18 {
19   int r2;
20   int r1;
21
22   r2 = xchg_acquire(sl, 1);
23   WRITE_ONCE(*x1, 1);
24   r1 = READ_ONCE(*x0);
25   smp_store_release(sl, 0);
26 }
27
28 filter (0:r2=0 /\ 1:r2=0)
29 exists (0:r1=0 /\ 1:r1=0)

This litmus test may be found here:

https://git.kernel.org/pub/scm/linux/kernel/git/paulmck/perfbook.git/tree/CodeSamples/formal/herd/C-SB+l-o-o-u+l-o-o-u-X.litmus

This test uses two global variables, "x1" and "x2", and also emulates a
single global spinlock named "sl".  This spinlock is held by whichever
process changes the value of "sl" from "0" to "1", and is released when
that process sets "sl" back to "0".  P0()'s lock acquisition is emulated
on line 11 using xchg_acquire(), which unconditionally stores the value
"1" to "sl" and stores either "0" or "1" to "r2", depending on whether
the lock acquisition was successful or unsuccessful (due to "sl" already
having the value "1"), respectively.  P1() operates in a similar manner.

Rather unconventionally, execution appears to proceed to the critical
section on lines 12 and 13 in either case.  Line 14 then uses an
smp_store_release() to store zero to "sl", thus emulating lock release.

The case where xchg_acquire() fails to acquire the lock is handled by
the "filter" clause on line 28, which tells herd7 to keep only those
executions in which both "0:r2" and "1:r2" are zero, that is to pay
attention only to those executions in which both locks are actually
acquired.  Thus, the bogus executions that would execute the critical
sections are discarded and any effects that they might have had are
ignored.  Note well that the "filter" clause keeps those executions
for which its expression is satisfied, that is, for which the expression
evaluates to true.  In other words, the "filter" clause says what to
keep, not what to discard.

The result of running this test is as follows:

 1 Test C-SB+l-o-o-u+l-o-o-u-X Allowed
 2 States 2
 3 0:r1=0; 1:r1=1;
 4 0:r1=1; 1:r1=0;
 5 No
 6 Witnesses
 7 Positive: 0 Negative: 2
 8 Condition exists (0:r1=0 /\ 1:r1=0)
 9 Observation C-SB+l-o-o-u+l-o-o-u-X Never 0 2
10 Time C-SB+l-o-o-u+l-o-o-u-X 0.03

The "Never" on line 9 indicates that this use of xchg_acquire() and
smp_store_release() really does correctly emulate locking.

Why doesn't the litmus test take the simpler approach of using a spin loop
to handle failed spinlock acquisitions, like the kernel does?  The key
insight behind this litmus test is that spin loops have no effect on the
possible "exists"-clause outcomes of program execution in the absence
of deadlock.  In other words, given a high-quality lock-acquisition
primitive in a deadlock-free program running on high-quality hardware,
each lock acquisition will eventually succeed.  Because herd7 already
explores the full state space, the length of time required to actually
acquire the lock does not matter.  After all, herd7 already models all
possible durations of the xchg_acquire() statements.

Why not just add the "filter" clause to the "exists" clause, thus
avoiding the "filter" clause entirely?  This does work, but is slower.
The reason that the "filter" clause is faster is that (in the common case)
herd7 knows to abandon an execution as soon as the "filter" expression
fails to be satisfied.  In contrast, the "exists" clause is evaluated
only at the end of time, thus requiring herd7 to waste time on bogus
executions in which both critical sections proceed concurrently.  In
addition, some LKMM users like the separation of concerns provided by
using the both the "filter" and "exists" clauses.

Readers lacking a pathological interest in odd corner cases should feel
free to skip the remainder of this section.

But what if the litmus test were to temporarily set "0:r2" to a non-zero
value?  Wouldn't that cause herd7 to abandon the execution prematurely
due to an early mismatch of the "filter" clause?

Why not just try it?  Line 4 of the following modified litmus test
introduces a new global variable "x2" that is initialized to "1".  Line 23
of P1() reads that variable into "1:r2" to force an early mismatch with
the "filter" clause.  Line 24 does a known-true "if" condition to avoid
and static analysis that herd7 might do.  Finally the "exists" clause
on line 32 is updated to a condition that is alway satisfied at the end
of the test.

 1 C C-SB+l-o-o-u+l-o-o-u-X
 2
 3 {
 4   x2=1;
 5 }
 6
 7 P0(int *sl, int *x0, int *x1)
 8 {
 9   int r2;
10   int r1;
11
12   r2 = xchg_acquire(sl, 1);
13   WRITE_ONCE(*x0, 1);
14   r1 = READ_ONCE(*x1);
15   smp_store_release(sl, 0);
16 }
17
18 P1(int *sl, int *x0, int *x1, int *x2)
19 {
20   int r2;
21   int r1;
22
23   r2 = READ_ONCE(*x2);
24   if (r2)
25     r2 = xchg_acquire(sl, 1);
26   WRITE_ONCE(*x1, 1);
27   r1 = READ_ONCE(*x0);
28   smp_store_release(sl, 0);
29 }
30
31 filter (0:r2=0 /\ 1:r2=0)
32 exists (x1=1)

If the "filter" clause were to check each variable at each point in the
execution, running this litmus test would display no executions because
all executions would be filtered out at line 23.  However, the output
is instead as follows:

 1 Test C-SB+l-o-o-u+l-o-o-u-X Allowed
 2 States 1
 3 x1=1;
 4 Ok
 5 Witnesses
 6 Positive: 2 Negative: 0
 7 Condition exists (x1=1)
 8 Observation C-SB+l-o-o-u+l-o-o-u-X Always 2 0
 9 Time C-SB+l-o-o-u+l-o-o-u-X 0.04
10 Hash=080bc508da7f291e122c6de76c0088e3

Line 3 shows that there is one execution that did not get filtered out,
so the "filter" clause is evaluated only on the last assignment to
the variables that it checks.  In this case, the "filter" clause is a
disjunction, so it might be evaluated twice, once at the final (and only)
assignment to "0:r2" and once at the final assignment to "1:r2".


Linked Lists
------------

LKMM can handle linked lists, but only linked lists in which each node
contains nothing except a pointer to the next node in the list.  This is
of course quite restrictive, but there is nevertheless quite a bit that
can be done within these confines, as can be seen in the litmus test
at tools/memory-model/litmus-tests/MP+onceassign+derefonce.litmus:

 1 C MP+onceassign+derefonce
 2
 3 {
 4 y=z;
 5 z=0;
 6 }
 7
 8 P0(int *x, int **y)
 9 {
10   WRITE_ONCE(*x, 1);
11   rcu_assign_pointer(*y, x);
12 }
13
14 P1(int *x, int **y)
15 {
16   int *r0;
17   int r1;
18
19   rcu_read_lock();
20   r0 = rcu_dereference(*y);
21   r1 = READ_ONCE(*r0);
22   rcu_read_unlock();
23 }
24
25 exists (1:r0=x /\ 1:r1=0)

Line 4's "y=z" may seem odd, given that "z" has not yet been initialized.
But "y=z" does not set the value of "y" to that of "z", but instead
sets the value of "y" to the *address* of "z".  Lines 4 and 5 therefore
create a simple linked list, with "y" pointing to "z" and "z" having a
NULL pointer.  A much longer linked list could be created if desired,
and circular singly linked lists can also be created and manipulated.

The "exists" clause works the same way, with the "1:r0=x" comparing P1()'s
"r0" not to the value of "x", but again to its address.  This term of the
"exists" clause therefore tests whether line 20's load from "y" saw the
value stored by line 11, which is in fact what is required in this case.

P0()'s line 10 initializes "x" to the value 1 then line 11 links to "x"
from "y", replacing "z".

P1()'s line 20 loads a pointer from "y", and line 21 dereferences that
pointer.  The RCU read-side critical section spanning lines 19-22 is just
for show in this example.  Note that the address used for line 21's load
depends on (in this case, "is exactly the same as") the value loaded by
line 20.  This is an example of what is called an "address dependency".
This particular address dependency extends from the load on line 20 to the
load on line 21.  Address dependencies provide a weak form of ordering.

Running this test results in the following:

 1 Test MP+onceassign+derefonce Allowed
 2 States 2
 3 1:r0=x; 1:r1=1;
 4 1:r0=z; 1:r1=0;
 5 No
 6 Witnesses
 7 Positive: 0 Negative: 2
 8 Condition exists (1:r0=x /\ 1:r1=0)
 9 Observation MP+onceassign+derefonce Never 0 2
10 Time MP+onceassign+derefonce 0.00
11 Hash=49ef7a741563570102448a256a0c8568

The only possible outcomes feature P1() loading a pointer to "z"
(which contains zero) on the one hand and P1() loading a pointer to "x"
(which contains the value one) on the other.  This should be reassuring
because it says that RCU readers cannot see the old preinitialization
values when accessing a newly inserted list node.  This undesirable
scenario is flagged by the "exists" clause, and would occur if P1()
loaded a pointer to "x", but obtained the pre-initialization value of
zero after dereferencing that pointer.


Comments
--------

Different portions of a litmus test are processed by different parsers,
which has the charming effect of requiring different comment syntax in
different portions of the litmus test.  The C-syntax portions use
C-language comments (either "/* */" or "//"), while the other portions
use Ocaml comments "(* *)".

The following litmus test illustrates the comment style corresponding
to each syntactic unit of the test:

 1 C MP+onceassign+derefonce (* A *)
 2
 3 (* B *)
 4
 5 {
 6 y=z; (* C *)
 7 z=0;
 8 } // D
 9
10 // E
11
12 P0(int *x, int **y) // F
13 {
14   WRITE_ONCE(*x, 1);  // G
15   rcu_assign_pointer(*y, x);
16 }
17
18 // H
19
20 P1(int *x, int **y)
21 {
22   int *r0;
23   int r1;
24
25   rcu_read_lock();
26   r0 = rcu_dereference(*y);
27   r1 = READ_ONCE(*r0);
28   rcu_read_unlock();
29 }
30
31 // I
32
33 exists (* J *) (1:r0=x /\ (* K *) 1:r1=0) (* L *)

In short, use C-language comments in the C code and Ocaml comments in
the rest of the litmus test.

On the other hand, if you prefer C-style comments everywhere, the
C preprocessor is your friend.


Asynchronous RCU Grace Periods
------------------------------

The following litmus test is derived from the example show in
Documentation/litmus-tests/rcu/RCU+sync+free.litmus, but converted to
emulate call_rcu():

 1 C RCU+sync+free
 2
 3 {
 4 int x = 1;
 5 int *y = &x;
 6 int z = 1;
 7 }
 8
 9 P0(int *x, int *z, int **y)
10 {
11   int *r0;
12   int r1;
13
14   rcu_read_lock();
15   r0 = rcu_dereference(*y);
16   r1 = READ_ONCE(*r0);
17   rcu_read_unlock();
18 }
19
20 P1(int *z, int **y, int *c)
21 {
22   rcu_assign_pointer(*y, z);
23   smp_store_release(*c, 1); // Emulate call_rcu().
24 }
25
26 P2(int *x, int *z, int **y, int *c)
27 {
28   int r0;
29
30   r0 = smp_load_acquire(*c); // Note call_rcu() request.
31   synchronize_rcu(); // Wait one grace period.
32   WRITE_ONCE(*x, 0); // Emulate the RCU callback.
33 }
34
35 filter (2:r0=1) (* Reject too-early starts. *)
36 exists (0:r0=x /\ 0:r1=0)

Lines 4-6 initialize a linked list headed by "y" that initially contains
"x".  In addition, "z" is pre-initialized to prepare for P1(), which
will replace "x" with "z" in this list.

P0() on lines 9-18 enters an RCU read-side critical section, loads the
list header "y" and dereferences it, leaving the node in "0:r0" and
the node's value in "0:r1".

P1() on lines 20-24 updates the list header to instead reference "z",
then emulates call_rcu() by doing a release store into "c".

P2() on lines 27-33 emulates the behind-the-scenes effect of doing a
call_rcu().  Line 30 first does an acquire load from "c", then line 31
waits for an RCU grace period to elapse, and finally line 32 emulates
the RCU callback, which in turn emulates a call to kfree().

Of course, it is possible for P2() to start too soon, so that the
value of "2:r0" is zero rather than the required value of "1".
The "filter" clause on line 35 handles this possibility, rejecting
all executions in which "2:r0" is not equal to the value "1".


Performance
-----------

LKMM's exploration of the full state-space can be extremely helpful,
but it does not come for free.  The price is exponential computational
complexity in terms of the number of processes, the average number
of statements in each process, and the total number of stores in the
litmus test.

So it is best to start small and then work up.  Where possible, break
your code down into small pieces each representing a core concurrency
requirement.

That said, herd7 is quite fast.  On an unprepossessing x86 laptop, it
was able to analyze the following 10-process RCU litmus test in about
six seconds.

https://github.com/paulmckrcu/litmus/blob/master/auto/C-RW-R+RW-R+RW-G+RW-G+RW-G+RW-G+RW-R+RW-R+RW-R+RW-R.litmus

One way to make herd7 run faster is to use the "-speedcheck true" option.
This option prevents herd7 from generating all possible end states,
instead causing it to focus solely on whether or not the "exists"
clause can be satisfied.  With this option, herd7 evaluates the above
litmus test in about 300 milliseconds, for more than an order of magnitude
improvement in performance.

Larger 16-process litmus tests that would normally consume 15 minutes
of time complete in about 40 seconds with this option.  To be fair,
you do get an extra 65,535 states when you leave off the "-speedcheck
true" option.

https://github.com/paulmckrcu/litmus/blob/master/auto/C-RW-R+RW-R+RW-G+RW-G+RW-G+RW-G+RW-R+RW-R+RW-R+RW-R+RW-G+RW-G+RW-G+RW-G+RW-R+RW-R.litmus

Nevertheless, litmus-test analysis really is of exponential complexity,
whether with or without "-speedcheck true".  Increasing by just three
processes to a 19-process litmus test requires 2 hours and 40 minutes
without, and about 8 minutes with "-speedcheck true".  Each of these
results represent roughly an order of magnitude slowdown compared to the
16-process litmus test.  Again, to be fair, the multi-hour run explores
no fewer than 524,287 additional states compared to the shorter one.

https://github.com/paulmckrcu/litmus/blob/master/auto/C-RW-R+RW-R+RW-G+RW-G+RW-G+RW-G+RW-R+RW-R+RW-R+RW-R+RW-R+RW-R+RW-G+RW-G+RW-G+RW-G+RW-R+RW-R+RW-R.litmus

If you don't like command-line arguments, you can obtain a similar speedup
by adding a "filter" clause with exactly the same expression as your
"exists" clause.

However, please note that seeing the full set of states can be extremely
helpful when developing and debugging litmus tests.


LIMITATIONS
===========

Limitations of the Linux-kernel memory model (LKMM) include:

1.      Compiler optimizations are not accurately modeled.  Of course,
        the use of READ_ONCE() and WRITE_ONCE() limits the compiler's
        ability to optimize, but under some circumstances it is possible
        for the compiler to undermine the memory model.  For more
        information, see Documentation/explanation.txt (in particular,
        the "THE PROGRAM ORDER RELATION: po AND po-loc" and "A WARNING"
        sections).

        Note that this limitation in turn limits LKMM's ability to
        accurately model address, control, and data dependencies.
        For example, if the compiler can deduce the value of some variable
        carrying a dependency, then the compiler can break that dependency
        by substituting a constant of that value.

        Conversely, LKMM will sometimes overestimate the amount of
        reordering compilers and CPUs can carry out, leading it to miss
        some pretty obvious cases of ordering.  A simple example is:

                r1 = READ_ONCE(x);
                if (r1 == 0)
                        smp_mb();
                WRITE_ONCE(y, 1);

        The WRITE_ONCE() does not depend on the READ_ONCE(), and as a
        result, LKMM does not claim ordering.  However, even though no
        dependency is present, the WRITE_ONCE() will not be executed before
        the READ_ONCE().  There are two reasons for this:

                The presence of the smp_mb() in one of the branches
                prevents the compiler from moving the WRITE_ONCE()
                up before the "if" statement, since the compiler has
                to assume that r1 will sometimes be 0 (but see the
                comment below);

                CPUs do not execute stores before po-earlier conditional
                branches, even in cases where the store occurs after the
                two arms of the branch have recombined.

        It is clear that it is not dangerous in the slightest for LKMM to
        make weaker guarantees than architectures.  In fact, it is
        desirable, as it gives compilers room for making optimizations.
        For instance, suppose that a 0 value in r1 would trigger undefined
        behavior elsewhere.  Then a clever compiler might deduce that r1
        can never be 0 in the if condition.  As a result, said clever
        compiler might deem it safe to optimize away the smp_mb(),
        eliminating the branch and any ordering an architecture would
        guarantee otherwise.

2.      Multiple access sizes for a single variable are not supported,
        and neither are misaligned or partially overlapping accesses.

3.      Exceptions and interrupts are not modeled.  In some cases,
        this limitation can be overcome by modeling the interrupt or
        exception with an additional process.

4.      I/O such as MMIO or DMA is not supported.

5.      Self-modifying code (such as that found in the kernel's
        alternatives mechanism, function tracer, Berkeley Packet Filter
        JIT compiler, and module loader) is not supported.

6.      Complete modeling of all variants of atomic read-modify-write
        operations, locking primitives, and RCU is not provided.
        For example, call_rcu() and rcu_barrier() are not supported.
        However, a substantial amount of support is provided for these
        operations, as shown in the linux-kernel.def file.

        Here are specific limitations:

        a.      When rcu_assign_pointer() is passed NULL, the Linux
                kernel provides no ordering, but LKMM models this
                case as a store release.

        b.      The "unless" RMW operations are not currently modeled:
                atomic_long_add_unless(), atomic_inc_unless_negative(),
                and atomic_dec_unless_positive().  These can be emulated
                in litmus tests, for example, by using atomic_cmpxchg().

                One exception of this limitation is atomic_add_unless(),
                which is provided directly by herd7 (so no corresponding
                definition in linux-kernel.def).  atomic_add_unless() is
                modeled by herd7 therefore it can be used in litmus tests.

        c.      The call_rcu() function is not modeled.  As was shown above,
                it can be emulated in litmus tests by adding another
                process that invokes synchronize_rcu() and the body of the
                callback function, with (for example) a release-acquire
                from the site of the emulated call_rcu() to the beginning
                of the additional process.

        d.      The rcu_barrier() function is not modeled.  It can be
                emulated in litmus tests emulating call_rcu() via
                (for example) a release-acquire from the end of each
                additional call_rcu() process to the site of the
                emulated rcu-barrier().

        e.      Reader-writer locking is not modeled.  It can be
                emulated in litmus tests using atomic read-modify-write
                operations.

The fragment of the C language supported by these litmus tests is quite
limited and in some ways non-standard:

1.      There is no automatic C-preprocessor pass.  You can of course
        run it manually, if you choose.

2.      There is no way to create functions other than the Pn() functions
        that model the concurrent processes.

3.      The Pn() functions' formal parameters must be pointers to the
        global shared variables.  Nothing can be passed by value into
        these functions.

4.      The only functions that can be invoked are those built directly
        into herd7 or that are defined in the linux-kernel.def file.

5.      The "switch", "do", "for", "while", and "goto" C statements are
        not supported.  The "switch" statement can be emulated by the
        "if" statement.  The "do", "for", and "while" statements can
        often be emulated by manually unrolling the loop, or perhaps by
        enlisting the aid of the C preprocessor to minimize the resulting
        code duplication.  Some uses of "goto" can be emulated by "if",
        and some others by unrolling.

6.      Although you can use a wide variety of types in litmus-test
        variable declarations, and especially in global-variable
        declarations, the "herd7" tool understands only int and
        pointer types.  There is no support for floating-point types,
        enumerations, characters, strings, arrays, or structures.

7.      Parsing of variable declarations is very loose, with almost no
        type checking.

8.      Initializers differ from their C-language counterparts.
        For example, when an initializer contains the name of a shared
        variable, that name denotes a pointer to that variable, not
        the current value of that variable.  For example, "int x = y"
        is interpreted the way "int x = &y" would be in C.

9.      Dynamic memory allocation is not supported, although this can
        be worked around in some cases by supplying multiple statically
        allocated variables.

Some of these limitations may be overcome in the future, but others are
more likely to be addressed by incorporating the Linux-kernel memory model
into other tools.

Finally, please note that LKMM is subject to change as hardware, use cases,
and compilers evolve.

Locking

Peios Kernel / Kernel development / Development tools / lkmm / docs

Literal include of tools/memory-model/Documentation/locking.txt.


[!] Note:
        This file expands on the "Locking" section of recipes.txt,
        focusing on locklessly accessing shared variables that are
        otherwise protected by a lock.

Locking
=======

Locking is well-known and the common use cases are straightforward: Any
CPU holding a given lock sees any changes previously seen or made by any
CPU before it previously released that same lock.  This last sentence
is the only part of this document that most developers will need to read.

However, developers who would like to also access lock-protected shared
variables outside of their corresponding locks should continue reading.


Locking and Prior Accesses
--------------------------

The basic rule of locking is worth repeating:

        Any CPU holding a given lock sees any changes previously seen
        or made by any CPU before it previously released that same lock.

Note that this statement is a bit stronger than "Any CPU holding a
given lock sees all changes made by any CPU during the time that CPU was
previously holding this same lock".  For example, consider the following
pair of code fragments:

        /* See MP+polocks.litmus. */
        void CPU0(void)
        {
                WRITE_ONCE(x, 1);
                spin_lock(&mylock);
                WRITE_ONCE(y, 1);
                spin_unlock(&mylock);
        }

        void CPU1(void)
        {
                spin_lock(&mylock);
                r0 = READ_ONCE(y);
                spin_unlock(&mylock);
                r1 = READ_ONCE(x);
        }

The basic rule guarantees that if CPU0() acquires mylock before CPU1(),
then both r0 and r1 must be set to the value 1.  This also has the
consequence that if the final value of r0 is equal to 1, then the final
value of r1 must also be equal to 1.  In contrast, the weaker rule would
say nothing about the final value of r1.


Locking and Subsequent Accesses
-------------------------------

The converse to the basic rule also holds:  Any CPU holding a given
lock will not see any changes that will be made by any CPU after it
subsequently acquires this same lock.  This converse statement is
illustrated by the following litmus test:

        /* See MP+porevlocks.litmus. */
        void CPU0(void)
        {
                r0 = READ_ONCE(y);
                spin_lock(&mylock);
                r1 = READ_ONCE(x);
                spin_unlock(&mylock);
        }

        void CPU1(void)
        {
                spin_lock(&mylock);
                WRITE_ONCE(x, 1);
                spin_unlock(&mylock);
                WRITE_ONCE(y, 1);
        }

This converse to the basic rule guarantees that if CPU0() acquires
mylock before CPU1(), then both r0 and r1 must be set to the value 0.
This also has the consequence that if the final value of r1 is equal
to 0, then the final value of r0 must also be equal to 0.  In contrast,
the weaker rule would say nothing about the final value of r0.

These examples show only a single pair of CPUs, but the effects of the
locking basic rule extend across multiple acquisitions of a given lock
across multiple CPUs.


Double-Checked Locking
----------------------

It is well known that more than just a lock is required to make
double-checked locking work correctly,  This litmus test illustrates
one incorrect approach:

        /* See Documentation/litmus-tests/locking/DCL-broken.litmus. */
        void CPU0(void)
        {
                r0 = READ_ONCE(flag);
                if (r0 == 0) {
                        spin_lock(&lck);
                        r1 = READ_ONCE(flag);
                        if (r1 == 0) {
                                WRITE_ONCE(data, 1);
                                WRITE_ONCE(flag, 1);
                        }
                        spin_unlock(&lck);
                }
                r2 = READ_ONCE(data);
        }
        /* CPU1() is the exactly the same as CPU0(). */

There are two problems.  First, there is no ordering between the first
READ_ONCE() of "flag" and the READ_ONCE() of "data".  Second, there is
no ordering between the two WRITE_ONCE() calls.  It should therefore be
no surprise that "r2" can be zero, and a quick herd7 run confirms this.

One way to fix this is to use smp_load_acquire() and smp_store_release()
as shown in this corrected version:

        /* See Documentation/litmus-tests/locking/DCL-fixed.litmus. */
        void CPU0(void)
        {
                r0 = smp_load_acquire(&flag);
                if (r0 == 0) {
                        spin_lock(&lck);
                        r1 = READ_ONCE(flag);
                        if (r1 == 0) {
                                WRITE_ONCE(data, 1);
                                smp_store_release(&flag, 1);
                        }
                        spin_unlock(&lck);
                }
                r2 = READ_ONCE(data);
        }
        /* CPU1() is the exactly the same as CPU0(). */

The smp_load_acquire() guarantees that its load from "flags" will
be ordered before the READ_ONCE() from data, thus solving the first
problem.  The smp_store_release() guarantees that its store will be
ordered after the WRITE_ONCE() to "data", solving the second problem.
The smp_store_release() pairs with the smp_load_acquire(), thus ensuring
that the ordering provided by each actually takes effect.  Again, a
quick herd7 run confirms this.

In short, if you access a lock-protected variable without holding the
corresponding lock, you will need to provide additional ordering, in
this case, via the smp_load_acquire() and the smp_store_release().


Ordering Provided by a Lock to CPUs Not Holding That Lock
---------------------------------------------------------

It is not necessarily the case that accesses ordered by locking will be
seen as ordered by CPUs not holding that lock.  Consider this example:

        /* See Z6.0+pooncelock+pooncelock+pombonce.litmus. */
        void CPU0(void)
        {
                spin_lock(&mylock);
                WRITE_ONCE(x, 1);
                WRITE_ONCE(y, 1);
                spin_unlock(&mylock);
        }

        void CPU1(void)
        {
                spin_lock(&mylock);
                r0 = READ_ONCE(y);
                WRITE_ONCE(z, 1);
                spin_unlock(&mylock);
        }

        void CPU2(void)
        {
                WRITE_ONCE(z, 2);
                smp_mb();
                r1 = READ_ONCE(x);
        }

Counter-intuitive though it might be, it is quite possible to have
the final value of r0 be 1, the final value of z be 2, and the final
value of r1 be 0.  The reason for this surprising outcome is that CPU2()
never acquired the lock, and thus did not fully benefit from the lock's
ordering properties.

Ordering can be extended to CPUs not holding the lock by careful use
of smp_mb__after_spinlock():

        /* See Z6.0+pooncelock+poonceLock+pombonce.litmus. */
        void CPU0(void)
        {
                spin_lock(&mylock);
                WRITE_ONCE(x, 1);
                WRITE_ONCE(y, 1);
                spin_unlock(&mylock);
        }

        void CPU1(void)
        {
                spin_lock(&mylock);
                smp_mb__after_spinlock();
                r0 = READ_ONCE(y);
                WRITE_ONCE(z, 1);
                spin_unlock(&mylock);
        }

        void CPU2(void)
        {
                WRITE_ONCE(z, 2);
                smp_mb();
                r1 = READ_ONCE(x);
        }

This addition of smp_mb__after_spinlock() strengthens the lock
acquisition sufficiently to rule out the counter-intuitive outcome.
In other words, the addition of the smp_mb__after_spinlock() prohibits
the counter-intuitive result where the final value of r0 is 1, the final
value of z is 2, and the final value of r1 is 0.


No Roach-Motel Locking!
-----------------------

This example requires familiarity with the herd7 "filter" clause, so
please read up on that topic in litmus-tests.txt.

It is tempting to allow memory-reference instructions to be pulled
into a critical section, but this cannot be allowed in the general case.
For example, consider a spin loop preceding a lock-based critical section.
Now, herd7 does not model spin loops, but we can emulate one with two
loads, with a "filter" clause to constrain the first to return the
initial value and the second to return the updated value, as shown below:

        /* See Documentation/litmus-tests/locking/RM-fixed.litmus. */
        void CPU0(void)
        {
                spin_lock(&lck);
                r2 = atomic_inc_return(&y);
                WRITE_ONCE(x, 1);
                spin_unlock(&lck);
        }

        void CPU1(void)
        {
                r0 = READ_ONCE(x);
                r1 = READ_ONCE(x);
                spin_lock(&lck);
                r2 = atomic_inc_return(&y);
                spin_unlock(&lck);
        }

        filter (1:r0=0 /\ 1:r1=1)
        exists (1:r2=1)

The variable "x" is the control variable for the emulated spin loop.
CPU0() sets it to "1" while holding the lock, and CPU1() emulates the
spin loop by reading it twice, first into "1:r0" (which should get the
initial value "0") and then into "1:r1" (which should get the updated
value "1").

The "filter" clause takes this into account, constraining "1:r0" to
equal "0" and "1:r1" to equal 1.

Then the "exists" clause checks to see if CPU1() acquired its lock first,
which should not happen given the filter clause because CPU0() updates
"x" while holding the lock.  And herd7 confirms this.

But suppose that the compiler was permitted to reorder the spin loop
into CPU1()'s critical section, like this:

        /* See Documentation/litmus-tests/locking/RM-broken.litmus. */
        void CPU0(void)
        {
                int r2;

                spin_lock(&lck);
                r2 = atomic_inc_return(&y);
                WRITE_ONCE(x, 1);
                spin_unlock(&lck);
        }

        void CPU1(void)
        {
                spin_lock(&lck);
                r0 = READ_ONCE(x);
                r1 = READ_ONCE(x);
                r2 = atomic_inc_return(&y);
                spin_unlock(&lck);
        }

        filter (1:r0=0 /\ 1:r1=1)
        exists (1:r2=1)

If "1:r0" is equal to "0", "1:r1" can never equal "1" because CPU0()
cannot update "x" while CPU1() holds the lock.  And herd7 confirms this,
showing zero executions matching the "filter" criteria.

And this is why Linux-kernel lock and unlock primitives must prevent
code from entering critical sections.  It is not sufficient to only
prevent code from leaving them.

Ordering

Peios Kernel / Kernel development / Development tools / lkmm / docs

Literal include of tools/memory-model/Documentation/ordering.txt.


This document gives an overview of the categories of memory-ordering
operations provided by the Linux-kernel memory model (LKMM).


Categories of Ordering
======================

This section lists LKMM's three top-level categories of memory-ordering
operations in decreasing order of strength:

1.      Barriers (also known as "fences").  A barrier orders some or
        all of the CPU's prior operations against some or all of its
        subsequent operations.

2.      Ordered memory accesses.  These operations order themselves
        against some or all of the CPU's prior accesses or some or all
        of the CPU's subsequent accesses, depending on the subcategory
        of the operation.

3.      Unordered accesses, as the name indicates, have no ordering
        properties except to the extent that they interact with an
        operation in the previous categories.  This being the real world,
        some of these "unordered" operations provide limited ordering
        in some special situations.

Each of the above categories is described in more detail by one of the
following sections.


Barriers
========

Each of the following categories of barriers is described in its own
subsection below:

a.      Full memory barriers.

b.      Read-modify-write (RMW) ordering augmentation barriers.

c.      Write memory barrier.

d.      Read memory barrier.

e.      Compiler barrier.

Note well that many of these primitives generate absolutely no code
in kernels built with CONFIG_SMP=n.  Therefore, if you are writing
a device driver, which must correctly order accesses to a physical
device even in kernels built with CONFIG_SMP=n, please use the
ordering primitives provided for that purpose.  For example, instead of
smp_mb(), use mb().  See the "Linux Kernel Device Drivers" book or the
https://lwn.net/Articles/698014/ article for more information.


Full Memory Barriers
--------------------

The Linux-kernel primitives that provide full ordering include:

o       The smp_mb() full memory barrier.

o       Value-returning RMW atomic operations whose names do not end in
        _acquire, _release, or _relaxed.

o       RCU's grace-period primitives.

First, the smp_mb() full memory barrier orders all of the CPU's prior
accesses against all subsequent accesses from the viewpoint of all CPUs.
In other words, all CPUs will agree that any earlier action taken
by that CPU happened before any later action taken by that same CPU.
For example, consider the following:

        WRITE_ONCE(x, 1);
        smp_mb(); // Order store to x before load from y.
        r1 = READ_ONCE(y);

All CPUs will agree that the store to "x" happened before the load
from "y", as indicated by the comment.  And yes, please comment your
memory-ordering primitives.  It is surprisingly hard to remember their
purpose after even a few months.

Second, some RMW atomic operations provide full ordering.  These
operations include value-returning RMW atomic operations (that is, those
with non-void return types) whose names do not end in _acquire, _release,
or _relaxed.  Examples include atomic_add_return(), atomic_dec_and_test(),
cmpxchg(), and xchg().  Note that conditional RMW atomic operations such
as cmpxchg() are only guaranteed to provide ordering when they succeed.
When RMW atomic operations provide full ordering, they partition the
CPU's accesses into three groups:

1.      All code that executed prior to the RMW atomic operation.

2.      The RMW atomic operation itself.

3.      All code that executed after the RMW atomic operation.

All CPUs will agree that any operation in a given partition happened
before any operation in a higher-numbered partition.

In contrast, non-value-returning RMW atomic operations (that is, those
with void return types) do not guarantee any ordering whatsoever.  Nor do
value-returning RMW atomic operations whose names end in _relaxed.
Examples of the former include atomic_inc() and atomic_dec(),
while examples of the latter include atomic_cmpxchg_relaxed() and
atomic_xchg_relaxed().  Similarly, value-returning non-RMW atomic
operations such as atomic_read() do not guarantee full ordering, and
are covered in the later section on unordered operations.

Value-returning RMW atomic operations whose names end in _acquire or
_release provide limited ordering, and will be described later in this
document.

Finally, RCU's grace-period primitives provide full ordering.  These
primitives include synchronize_rcu(), synchronize_rcu_expedited(),
synchronize_srcu() and so on.  However, these primitives have orders
of magnitude greater overhead than smp_mb(), atomic_xchg(), and so on.
Furthermore, RCU's grace-period primitives can only be invoked in
sleepable contexts.  Therefore, RCU's grace-period primitives are
typically instead used to provide ordering against RCU read-side critical
sections, as documented in their comment headers.  But of course if you
need a synchronize_rcu() to interact with readers, it costs you nothing
to also rely on its additional full-memory-barrier semantics.  Just please
carefully comment this, otherwise your future self will hate you.


RMW Ordering Augmentation Barriers
----------------------------------

As noted in the previous section, non-value-returning RMW operations
such as atomic_inc() and atomic_dec() guarantee no ordering whatsoever.
Nevertheless, a number of popular CPU families, including x86, provide
full ordering for these primitives.  One way to obtain full ordering on
all architectures is to add a call to smp_mb():

        WRITE_ONCE(x, 1);
        atomic_inc(&my_counter);
        smp_mb(); // Inefficient on x86!!!
        r1 = READ_ONCE(y);

This works, but the added smp_mb() adds needless overhead for
x86, on which atomic_inc() provides full ordering all by itself.
The smp_mb__after_atomic() primitive can be used instead:

        WRITE_ONCE(x, 1);
        atomic_inc(&my_counter);
        smp_mb__after_atomic(); // Order store to x before load from y.
        r1 = READ_ONCE(y);

The smp_mb__after_atomic() primitive emits code only on CPUs whose
atomic_inc() implementations do not guarantee full ordering, thus
incurring no unnecessary overhead on x86.  There are a number of
variations on the smp_mb__*() theme:

o       smp_mb__before_atomic(), which provides full ordering prior
        to an unordered RMW atomic operation.

o       smp_mb__after_atomic(), which, as shown above, provides full
        ordering subsequent to an unordered RMW atomic operation.

o       smp_mb__after_spinlock(), which provides full ordering subsequent
        to a successful spinlock acquisition.  Note that spin_lock() is
        always successful but spin_trylock() might not be.

o       smp_mb__after_srcu_read_unlock(), which provides full ordering
        subsequent to an srcu_read_unlock().

It is bad practice to place code between the smp__*() primitive and the
operation whose ordering that it is augmenting.  The reason is that the
ordering of this intervening code will differ from one CPU architecture
to another.


Write Memory Barrier
--------------------

The Linux kernel's write memory barrier is smp_wmb().  If a CPU executes
the following code:

        WRITE_ONCE(x, 1);
        smp_wmb();
        WRITE_ONCE(y, 1);

Then any given CPU will see the write to "x" has having happened before
the write to "y".  However, you are usually better off using a release
store, as described in the "Release Operations" section below.

Note that smp_wmb() might fail to provide ordering for unmarked C-language
stores because profile-driven optimization could determine that the
value being overwritten is almost always equal to the new value.  Such a
compiler might then reasonably decide to transform "x = 1" and "y = 1"
as follows:

        if (x != 1)
                x = 1;
        smp_wmb(); // BUG: does not order the reads!!!
        if (y != 1)
                y = 1;

Therefore, if you need to use smp_wmb() with unmarked C-language writes,
you will need to make sure that none of the compilers used to build
the Linux kernel carry out this sort of transformation, both now and in
the future.


Read Memory Barrier
-------------------

The Linux kernel's read memory barrier is smp_rmb().  If a CPU executes
the following code:

        r0 = READ_ONCE(y);
        smp_rmb();
        r1 = READ_ONCE(x);

Then any given CPU will see the read from "y" as having preceded the read from
"x".  However, you are usually better off using an acquire load, as described
in the "Acquire Operations" section below.

Compiler Barrier
----------------

The Linux kernel's compiler barrier is barrier().  This primitive
prohibits compiler code-motion optimizations that might move memory
references across the point in the code containing the barrier(), but
does not constrain hardware memory ordering.  For example, this can be
used to prevent the compiler from moving code across an infinite loop:

        WRITE_ONCE(x, 1);
        while (dontstop)
                barrier();
        r1 = READ_ONCE(y);

Without the barrier(), the compiler would be within its rights to move the
WRITE_ONCE() to follow the loop.  This code motion could be problematic
in the case where an interrupt handler terminates the loop.  Another way
to handle this is to use READ_ONCE() for the load of "dontstop".

Note that the barriers discussed previously use barrier() or its low-level
equivalent in their implementations.


Ordered Memory Accesses
=======================

The Linux kernel provides a wide variety of ordered memory accesses:

a.      Release operations.

b.      Acquire operations.

c.      RCU read-side ordering.

d.      Control dependencies.

Each of the above categories has its own section below.


Release Operations
------------------

Release operations include smp_store_release(), atomic_set_release(),
rcu_assign_pointer(), and value-returning RMW operations whose names
end in _release.  These operations order their own store against all
of the CPU's prior memory accesses.  Release operations often provide
improved readability and performance compared to explicit barriers.
For example, use of smp_store_release() saves a line compared to the
smp_wmb() example above:

        WRITE_ONCE(x, 1);
        smp_store_release(&y, 1);

More important, smp_store_release() makes it easier to connect up the
different pieces of the concurrent algorithm.  The variable stored to
by the smp_store_release(), in this case "y", will normally be used in
an acquire operation in other parts of the concurrent algorithm.

To see the performance advantages, suppose that the above example reads
from "x" instead of writing to it.  Then an smp_wmb() could not guarantee
ordering, and an smp_mb() would be needed instead:

        r1 = READ_ONCE(x);
        smp_mb();
        WRITE_ONCE(y, 1);

But smp_mb() often incurs much higher overhead than does
smp_store_release(), which still provides the needed ordering of "x"
against "y".  On x86, the version using smp_store_release() might compile
to a simple load instruction followed by a simple store instruction.
In contrast, the smp_mb() compiles to an expensive instruction that
provides the needed ordering.

There is a wide variety of release operations:

o       Store operations, including not only the aforementioned
        smp_store_release(), but also atomic_set_release(), and
        atomic_long_set_release().

o       RCU's rcu_assign_pointer() operation.  This is the same as
        smp_store_release() except that: (1) It takes the pointer to
        be assigned to instead of a pointer to that pointer, (2) It
        is intended to be used in conjunction with rcu_dereference()
        and similar rather than smp_load_acquire(), and (3) It checks
        for an RCU-protected pointer in "sparse" runs.

o       Value-returning RMW operations whose names end in _release,
        such as atomic_fetch_add_release() and cmpxchg_release().
        Note that release ordering is guaranteed only against the
        memory-store portion of the RMW operation, and not against the
        memory-load portion.  Note also that conditional operations such
        as cmpxchg_release() are only guaranteed to provide ordering
        when they succeed.

As mentioned earlier, release operations are often paired with acquire
operations, which are the subject of the next section.


Acquire Operations
------------------

Acquire operations include smp_load_acquire(), atomic_read_acquire(),
and value-returning RMW operations whose names end in _acquire.   These
operations order their own load against all of the CPU's subsequent
memory accesses.  Acquire operations often provide improved performance
and readability compared to explicit barriers.  For example, use of
smp_load_acquire() saves a line compared to the smp_rmb() example above:

        r0 = smp_load_acquire(&y);
        r1 = READ_ONCE(x);

As with smp_store_release(), this also makes it easier to connect
the different pieces of the concurrent algorithm by looking for the
smp_store_release() that stores to "y".  In addition, smp_load_acquire()
improves upon smp_rmb() by ordering against subsequent stores as well
as against subsequent loads.

There are a couple of categories of acquire operations:

o       Load operations, including not only the aforementioned
        smp_load_acquire(), but also atomic_read_acquire(), and
        atomic64_read_acquire().

o       Value-returning RMW operations whose names end in _acquire,
        such as atomic_xchg_acquire() and atomic_cmpxchg_acquire().
        Note that acquire ordering is guaranteed only against the
        memory-load portion of the RMW operation, and not against the
        memory-store portion.  Note also that conditional operations
        such as atomic_cmpxchg_acquire() are only guaranteed to provide
        ordering when they succeed.

Symmetry being what it is, acquire operations are often paired with the
release operations covered earlier.  For example, consider the following
example, where task0() and task1() execute concurrently:

        void task0(void)
        {
                WRITE_ONCE(x, 1);
                smp_store_release(&y, 1);
        }

        void task1(void)
        {
                r0 = smp_load_acquire(&y);
                r1 = READ_ONCE(x);
        }

If "x" and "y" are both initially zero, then either r0's final value
will be zero or r1's final value will be one, thus providing the required
ordering.


RCU Read-Side Ordering
----------------------

This category includes read-side markers such as rcu_read_lock()
and rcu_read_unlock() as well as pointer-traversal primitives such as
rcu_dereference() and srcu_dereference().

Compared to locking primitives and RMW atomic operations, markers
for RCU read-side critical sections incur very low overhead because
they interact only with the corresponding grace-period primitives.
For example, the rcu_read_lock() and rcu_read_unlock() markers interact
with synchronize_rcu(), synchronize_rcu_expedited(), and call_rcu().
The way this works is that if a given call to synchronize_rcu() cannot
prove that it started before a given call to rcu_read_lock(), then
that synchronize_rcu() must block until the matching rcu_read_unlock()
is reached.  For more information, please see the synchronize_rcu()
docbook header comment and the material in Documentation/RCU.

RCU's pointer-traversal primitives, including rcu_dereference() and
srcu_dereference(), order their load (which must be a pointer) against any
of the CPU's subsequent memory accesses whose address has been calculated
from the value loaded.  There is said to be an *address dependency*
from the value returned by the rcu_dereference() or srcu_dereference()
to that subsequent memory access.

A call to rcu_dereference() for a given RCU-protected pointer is
usually paired with a call to rcu_assign_pointer() for that same pointer
in much the same way that a call to smp_load_acquire() is paired with
a call to smp_store_release().  Calls to rcu_dereference() and
rcu_assign_pointer() are often buried in other APIs, for example,
the RCU list API members defined in include/linux/rculist.h.  For more
information, please see the docbook headers in that file, the most
recent LWN article on the RCU API (https://lwn.net/Articles/988638/),
and of course the material in Documentation/RCU.

If the pointer value is manipulated between the rcu_dereference()
that returned it and a later rcu_dereference(), please read
Documentation/RCU/rcu_dereference.rst.  It can also be quite helpful to
review uses in the Linux kernel.


Control Dependencies
--------------------

A control dependency extends from a marked load (READ_ONCE() or stronger)
through an "if" condition to a marked store (WRITE_ONCE() or stronger)
that is executed only by one of the legs of that "if" statement.
Control dependencies are so named because they are mediated by
control-flow instructions such as comparisons and conditional branches.

In short, you can use a control dependency to enforce ordering between
an READ_ONCE() and a WRITE_ONCE() when there is an "if" condition
between them.  The canonical example is as follows:

        q = READ_ONCE(a);
        if (q)
                WRITE_ONCE(b, 1);

In this case, all CPUs would see the read from "a" as happening before
the write to "b".

However, control dependencies are easily destroyed by compiler
optimizations, so any use of control dependencies must take into account
all of the compilers used to build the Linux kernel.  Please see the
"control-dependencies.txt" file for more information.


Unordered Accesses
==================

Each of these two categories of unordered accesses has a section below:

a.      Unordered marked operations.

b.      Unmarked C-language accesses.


Unordered Marked Operations
---------------------------

Unordered operations to different variables are just that, unordered.
However, if a group of CPUs apply these operations to a single variable,
all the CPUs will agree on the operation order.  Of course, the ordering
of unordered marked accesses can also be constrained using the mechanisms
described earlier in this document.

These operations come in three categories:

o       Marked writes, such as WRITE_ONCE() and atomic_set().  These
        primitives require the compiler to emit the corresponding store
        instructions in the expected execution order, thus suppressing
        a number of destructive optimizations.  However, they provide no
        hardware ordering guarantees, and in fact many CPUs will happily
        reorder marked writes with each other or with other unordered
        operations, unless these operations are to the same variable.

o       Marked reads, such as READ_ONCE() and atomic_read().  These
        primitives require the compiler to emit the corresponding load
        instructions in the expected execution order, thus suppressing
        a number of destructive optimizations.  However, they provide no
        hardware ordering guarantees, and in fact many CPUs will happily
        reorder marked reads with each other or with other unordered
        operations, unless these operations are to the same variable.

o       Unordered RMW atomic operations.  These are non-value-returning
        RMW atomic operations whose names do not end in _acquire or
        _release, and also value-returning RMW operations whose names
        end in _relaxed.  Examples include atomic_add(), atomic_or(),
        and atomic64_fetch_xor_relaxed().  These operations do carry
        out the specified RMW operation atomically, for example, five
        concurrent atomic_inc() operations applied to a given variable
        will reliably increase the value of that variable by five.
        However, many CPUs will happily reorder these operations with
        each other or with other unordered operations.

        This category of operations can be efficiently ordered using
        smp_mb__before_atomic() and smp_mb__after_atomic(), as was
        discussed in the "RMW Ordering Augmentation Barriers" section.

In short, these operations can be freely reordered unless they are all
operating on a single variable or unless they are constrained by one of
the operations called out earlier in this document.


Unmarked C-Language Accesses
----------------------------

Unmarked C-language accesses are normal variable accesses to normal
variables, that is, to variables that are not "volatile" and are not
C11 atomic variables.  These operations provide no ordering guarantees,
and further do not guarantee "atomic" access.  For example, the compiler
might (and sometimes does) split a plain C-language store into multiple
smaller stores.  A load from that same variable running on some other
CPU while such a store is executing might see a value that is a mashup
of the old value and the new value.

Unmarked C-language accesses are unordered, and are also subject to
any number of compiler optimizations, many of which can break your
concurrent code.  It is possible to use unmarked C-language accesses for
shared variables that are subject to concurrent access, but great care
is required on an ongoing basis.  The compiler-constraining barrier()
primitive can be helpful, as can the various ordering primitives discussed
in this document.  It nevertheless bears repeating that use of unmarked
C-language accesses requires careful attention to not just your code,
but to all the compilers that might be used to build it.  Such compilers
might replace a series of loads with a single load, and might replace
a series of stores with a single store.  Some compilers will even split
a single store into multiple smaller stores.

But there are some ways of using unmarked C-language accesses for shared
variables without such worries:

o       Guard all accesses to a given variable by a particular lock,
        so that there are never concurrent conflicting accesses to
        that variable.  (There are "conflicting accesses" when
        (1) at least one of the concurrent accesses to a variable is an
        unmarked C-language access and (2) when at least one of those
        accesses is a write, whether marked or not.)

o       As above, but using other synchronization primitives such
        as reader-writer locks or sequence locks.

o       Use locking or other means to ensure that all concurrent accesses
        to a given variable are reads.

o       Restrict use of a given variable to statistics or heuristics
        where the occasional bogus value can be tolerated.

o       Declare the accessed variables as C11 atomics.
        https://lwn.net/Articles/691128/

o       Declare the accessed variables as "volatile".

If you need to live more dangerously, please do take the time to
understand the compilers.  One place to start is these two LWN
articles:

Who's afraid of a big bad optimizing compiler?
        https://lwn.net/Articles/793253
Calibrating your fear of big bad optimizing compilers
        https://lwn.net/Articles/799218

Used properly, unmarked C-language accesses can reduce overhead on
fastpaths.  However, the price is great care and continual attention
to your compiler as new versions come out and as new optimizations
are enabled.

README (for LKMM Documentation)

Peios Kernel / Kernel development / Development tools / lkmm / docs

Literal include of tools/memory-model/Documentation/README.


It has been said that successful communication requires first identifying
what your audience knows and then building a bridge from their current
knowledge to what they need to know.  Unfortunately, the expected
Linux-kernel memory model (LKMM) audience might be anywhere from novice
to expert both in kernel hacking and in understanding LKMM.

This document therefore points out a number of places to start reading,
depending on what you know and what you would like to learn.  Please note
that the documents later in this list assume that the reader understands
the material provided by documents earlier in this list.

If LKMM-specific terms lost you, glossary.txt might help you.

o       You are new to Linux-kernel concurrency: simple.txt

o       You have some background in Linux-kernel concurrency, and would
        like an overview of the types of low-level concurrency primitives
        that the Linux kernel provides:  ordering.txt

        Here, "low level" means atomic operations to single variables.

o       You are familiar with the Linux-kernel concurrency primitives
        that you need, and just want to get started with LKMM litmus
        tests:  litmus-tests.txt

o       You need to locklessly access shared variables that are otherwise
        protected by a lock: locking.txt

        This locking.txt file expands on the "Locking" section in
        recipes.txt, but is self-contained.

o       You are familiar with Linux-kernel concurrency, and would
        like a detailed intuitive understanding of LKMM, including
        situations involving more than two threads:  recipes.txt

o       You would like a detailed understanding of what your compiler can
        and cannot do to control dependencies:  control-dependencies.txt

o       You would like to mark concurrent normal accesses to shared
        variables so that intentional "racy" accesses can be properly
        documented, especially when you are responding to complaints
        from KCSAN:  access-marking.txt

o       You are familiar with Linux-kernel concurrency and the use of
        LKMM, and would like a quick reference:  cheatsheet.txt

o       You are familiar with Linux-kernel concurrency and the use
        of LKMM, and would like to learn about LKMM's requirements,
        rationale, and implementation:  explanation.txt and
        herd-representation.txt

o       You are interested in the publications related to LKMM, including
        hardware manuals, academic literature, standards-committee
        working papers, and LWN articles:  references.txt


====================
DESCRIPTION OF FILES
====================

README
        This file.

access-marking.txt
        Guidelines for marking intentionally concurrent accesses to
        shared memory.

cheatsheet.txt
        Quick-reference guide to the Linux-kernel memory model.

control-dependencies.txt
        Guide to preventing compiler optimizations from destroying
        your control dependencies.

explanation.txt
        Detailed description of the memory model.

glossary.txt
        Brief definitions of LKMM-related terms.

herd-representation.txt
        The (abstract) representation of the Linux-kernel concurrency
        primitives in terms of events.

litmus-tests.txt
        The format, features, capabilities, and limitations of the litmus
        tests that LKMM can evaluate.

locking.txt
        Rules for accessing lock-protected shared variables outside of
        their corresponding critical sections.

ordering.txt
        Overview of the Linux kernel's low-level memory-ordering
        primitives by category.

recipes.txt
        Common memory-ordering patterns.

references.txt
        Background information.

simple.txt
        Starting point for someone new to Linux-kernel concurrency.
        And also a reminder of the simpler approaches to concurrency!

Recipes

Peios Kernel / Kernel development / Development tools / lkmm / docs

Literal include of tools/memory-model/Documentation/recipes.txt.


This document provides "recipes", that is, litmus tests for commonly
occurring situations, as well as a few that illustrate subtly broken but
attractive nuisances.  Many of these recipes include example code from
v5.7 of the Linux kernel.

The first section covers simple special cases, the second section
takes off the training wheels to cover more involved examples,
and the third section provides a few rules of thumb.


Simple special cases
====================

This section presents two simple special cases, the first being where
there is only one CPU or only one memory location is accessed, and the
second being use of that old concurrency workhorse, locking.


Single CPU or single memory location
------------------------------------

If there is only one CPU on the one hand or only one variable
on the other, the code will execute in order.  There are (as
usual) some things to be careful of:

1.      Some aspects of the C language are unordered.  For example,
        in the expression "f(x) + g(y)", the order in which f and g are
        called is not defined; the object code is allowed to use either
        order or even to interleave the computations.

2.      Compilers are permitted to use the "as-if" rule.  That is, a
        compiler can emit whatever code it likes for normal accesses,
        as long as the results of a single-threaded execution appear
        just as if the compiler had followed all the relevant rules.
        To see this, compile with a high level of optimization and run
        the debugger on the resulting binary.

3.      If there is only one variable but multiple CPUs, that variable
        must be properly aligned and all accesses to that variable must
        be full sized.  Variables that straddle cachelines or pages void
        your full-ordering warranty, as do undersized accesses that load
        from or store to only part of the variable.

4.      If there are multiple CPUs, accesses to shared variables should
        use READ_ONCE() and WRITE_ONCE() or stronger to prevent load/store
        tearing, load/store fusing, and invented loads and stores.
        There are exceptions to this rule, including:

        i.      When there is no possibility of a given shared variable
                being updated by some other CPU, for example, while
                holding the update-side lock, reads from that variable
                need not use READ_ONCE().

        ii.     When there is no possibility of a given shared variable
                being either read or updated by other CPUs, for example,
                when running during early boot, reads from that variable
                need not use READ_ONCE() and writes to that variable
                need not use WRITE_ONCE().


Locking
-------

[!] Note:
        locking.txt expands on this section, providing more detail on
        locklessly accessing lock-protected shared variables.

Locking is well-known and straightforward, at least if you don't think
about it too hard.  And the basic rule is indeed quite simple: Any CPU that
has acquired a given lock sees any changes previously seen or made by any
CPU before it released that same lock.  Note that this statement is a bit
stronger than "Any CPU holding a given lock sees all changes made by any
CPU during the time that CPU was holding this same lock".  For example,
consider the following pair of code fragments:

        /* See MP+polocks.litmus. */
        void CPU0(void)
        {
                WRITE_ONCE(x, 1);
                spin_lock(&mylock);
                WRITE_ONCE(y, 1);
                spin_unlock(&mylock);
        }

        void CPU1(void)
        {
                spin_lock(&mylock);
                r0 = READ_ONCE(y);
                spin_unlock(&mylock);
                r1 = READ_ONCE(x);
        }

The basic rule guarantees that if CPU0() acquires mylock before CPU1(),
then both r0 and r1 must be set to the value 1.  This also has the
consequence that if the final value of r0 is equal to 1, then the final
value of r1 must also be equal to 1.  In contrast, the weaker rule would
say nothing about the final value of r1.

The converse to the basic rule also holds, as illustrated by the
following litmus test:

        /* See MP+porevlocks.litmus. */
        void CPU0(void)
        {
                r0 = READ_ONCE(y);
                spin_lock(&mylock);
                r1 = READ_ONCE(x);
                spin_unlock(&mylock);
        }

        void CPU1(void)
        {
                spin_lock(&mylock);
                WRITE_ONCE(x, 1);
                spin_unlock(&mylock);
                WRITE_ONCE(y, 1);
        }

This converse to the basic rule guarantees that if CPU0() acquires
mylock before CPU1(), then both r0 and r1 must be set to the value 0.
This also has the consequence that if the final value of r1 is equal
to 0, then the final value of r0 must also be equal to 0.  In contrast,
the weaker rule would say nothing about the final value of r0.

These examples show only a single pair of CPUs, but the effects of the
locking basic rule extend across multiple acquisitions of a given lock
across multiple CPUs.

However, it is not necessarily the case that accesses ordered by
locking will be seen as ordered by CPUs not holding that lock.
Consider this example:

        /* See Z6.0+pooncelock+pooncelock+pombonce.litmus. */
        void CPU0(void)
        {
                spin_lock(&mylock);
                WRITE_ONCE(x, 1);
                WRITE_ONCE(y, 1);
                spin_unlock(&mylock);
        }

        void CPU1(void)
        {
                spin_lock(&mylock);
                r0 = READ_ONCE(y);
                WRITE_ONCE(z, 1);
                spin_unlock(&mylock);
        }

        void CPU2(void)
        {
                WRITE_ONCE(z, 2);
                smp_mb();
                r1 = READ_ONCE(x);
        }

Counter-intuitive though it might be, it is quite possible to have
the final value of r0 be 1, the final value of z be 2, and the final
value of r1 be 0.  The reason for this surprising outcome is that
CPU2() never acquired the lock, and thus did not benefit from the
lock's ordering properties.

Ordering can be extended to CPUs not holding the lock by careful use
of smp_mb__after_spinlock():

        /* See Z6.0+pooncelock+poonceLock+pombonce.litmus. */
        void CPU0(void)
        {
                spin_lock(&mylock);
                WRITE_ONCE(x, 1);
                WRITE_ONCE(y, 1);
                spin_unlock(&mylock);
        }

        void CPU1(void)
        {
                spin_lock(&mylock);
                smp_mb__after_spinlock();
                r0 = READ_ONCE(y);
                WRITE_ONCE(z, 1);
                spin_unlock(&mylock);
        }

        void CPU2(void)
        {
                WRITE_ONCE(z, 2);
                smp_mb();
                r1 = READ_ONCE(x);
        }

This addition of smp_mb__after_spinlock() strengthens the lock acquisition
sufficiently to rule out the counter-intuitive outcome.


Taking off the training wheels
==============================

This section looks at more complex examples, including message passing,
load buffering, release-acquire chains, store buffering.
Many classes of litmus tests have abbreviated names, which may be found
here: https://www.cl.cam.ac.uk/~pes20/ppc-supplemental/test6.pdf


Message passing (MP)
--------------------

The MP pattern has one CPU execute a pair of stores to a pair of variables
and another CPU execute a pair of loads from this same pair of variables,
but in the opposite order.  The goal is to avoid the counter-intuitive
outcome in which the first load sees the value written by the second store
but the second load does not see the value written by the first store.
In the absence of any ordering, this goal may not be met, as can be seen
in the MP+poonceonces.litmus litmus test.  This section therefore looks at
a number of ways of meeting this goal.


Release and acquire
~~~~~~~~~~~~~~~~~~~

Use of smp_store_release() and smp_load_acquire() is one way to force
the desired MP ordering.  The general approach is shown below:

        /* See MP+pooncerelease+poacquireonce.litmus. */
        void CPU0(void)
        {
                WRITE_ONCE(x, 1);
                smp_store_release(&y, 1);
        }

        void CPU1(void)
        {
                r0 = smp_load_acquire(&y);
                r1 = READ_ONCE(x);
        }

The smp_store_release() macro orders any prior accesses against the
store, while the smp_load_acquire macro orders the load against any
subsequent accesses.  Therefore, if the final value of r0 is the value 1,
the final value of r1 must also be the value 1.

The init_stack_slab() function in lib/stackdepot.c uses release-acquire
in this way to safely initialize of a slab of the stack.  Working out
the mutual-exclusion design is left as an exercise for the reader.


Assign and dereference
~~~~~~~~~~~~~~~~~~~~~~

Use of rcu_assign_pointer() and rcu_dereference() is quite similar to the
use of smp_store_release() and smp_load_acquire(), except that both
rcu_assign_pointer() and rcu_dereference() operate on RCU-protected
pointers.  The general approach is shown below:

        /* See MP+onceassign+derefonce.litmus. */
        int z;
        int *y = &z;
        int x;

        void CPU0(void)
        {
                WRITE_ONCE(x, 1);
                rcu_assign_pointer(y, &x);
        }

        void CPU1(void)
        {
                rcu_read_lock();
                r0 = rcu_dereference(y);
                r1 = READ_ONCE(*r0);
                rcu_read_unlock();
        }

In this example, if the final value of r0 is &x then the final value of
r1 must be 1.

The rcu_assign_pointer() macro has the same ordering properties as does
smp_store_release(), but the rcu_dereference() macro orders the load only
against later accesses that depend on the value loaded.  A dependency
is present if the value loaded determines the address of a later access
(address dependency, as shown above), the value written by a later store
(data dependency), or whether or not a later store is executed in the
first place (control dependency).  Note that the term "data dependency"
is sometimes casually used to cover both address and data dependencies.

In lib/math/prime_numbers.c, the expand_to_next_prime() function invokes
rcu_assign_pointer(), and the next_prime_number() function invokes
rcu_dereference().  This combination mediates access to a bit vector
that is expanded as additional primes are needed.


Write and read memory barriers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

It is usually better to use smp_store_release() instead of smp_wmb()
and to use smp_load_acquire() instead of smp_rmb().  However, the older
smp_wmb() and smp_rmb() APIs are still heavily used, so it is important
to understand their use cases.  The general approach is shown below:

        /* See MP+fencewmbonceonce+fencermbonceonce.litmus. */
        void CPU0(void)
        {
                WRITE_ONCE(x, 1);
                smp_wmb();
                WRITE_ONCE(y, 1);
        }

        void CPU1(void)
        {
                r0 = READ_ONCE(y);
                smp_rmb();
                r1 = READ_ONCE(x);
        }

The smp_wmb() macro orders prior stores against later stores, and the
smp_rmb() macro orders prior loads against later loads.  Therefore, if
the final value of r0 is 1, the final value of r1 must also be 1.

The xlog_state_switch_iclogs() function in fs/xfs/xfs_log.c contains
the following write-side code fragment:

        log->l_curr_block -= log->l_logBBsize;
        ASSERT(log->l_curr_block >= 0);
        smp_wmb();
        log->l_curr_cycle++;

And the xlog_valid_lsn() function in fs/xfs/xfs_log_priv.h contains
the corresponding read-side code fragment:

        cur_cycle = READ_ONCE(log->l_curr_cycle);
        smp_rmb();
        cur_block = READ_ONCE(log->l_curr_block);

Alternatively, consider the following comment in function
perf_output_put_handle() in kernel/events/ring_buffer.c:

         *   kernel                             user
         *
         *   if (LOAD ->data_tail) {            LOAD ->data_head
         *                      (A)             smp_rmb()       (C)
         *      STORE $data                     LOAD $data
         *      smp_wmb()       (B)             smp_mb()        (D)
         *      STORE ->data_head               STORE ->data_tail
         *   }

The B/C pairing is an example of the MP pattern using smp_wmb() on the
write side and smp_rmb() on the read side.

Of course, given that smp_mb() is strictly stronger than either smp_wmb()
or smp_rmb(), any code fragment that would work with smp_rmb() and
smp_wmb() would also work with smp_mb() replacing either or both of the
weaker barriers.


Load buffering (LB)
-------------------

The LB pattern has one CPU load from one variable and then store to a
second, while another CPU loads from the second variable and then stores
to the first.  The goal is to avoid the counter-intuitive situation where
each load reads the value written by the other CPU's store.  In the
absence of any ordering it is quite possible that this may happen, as
can be seen in the LB+poonceonces.litmus litmus test.

One way of avoiding the counter-intuitive outcome is through the use of a
control dependency paired with a full memory barrier:

        /* See LB+fencembonceonce+ctrlonceonce.litmus. */
        void CPU0(void)
        {
                r0 = READ_ONCE(x);
                if (r0)
                        WRITE_ONCE(y, 1);
        }

        void CPU1(void)
        {
                r1 = READ_ONCE(y);
                smp_mb();
                WRITE_ONCE(x, 1);
        }

This pairing of a control dependency in CPU0() with a full memory
barrier in CPU1() prevents r0 and r1 from both ending up equal to 1.

The A/D pairing from the ring-buffer use case shown earlier also
illustrates LB.  Here is a repeat of the comment in
perf_output_put_handle() in kernel/events/ring_buffer.c, showing a
control dependency on the kernel side and a full memory barrier on
the user side:

         *   kernel                             user
         *
         *   if (LOAD ->data_tail) {            LOAD ->data_head
         *                      (A)             smp_rmb()       (C)
         *      STORE $data                     LOAD $data
         *      smp_wmb()       (B)             smp_mb()        (D)
         *      STORE ->data_head               STORE ->data_tail
         *   }
         *
         * Where A pairs with D, and B pairs with C.

The kernel's control dependency between the load from ->data_tail
and the store to data combined with the user's full memory barrier
between the load from data and the store to ->data_tail prevents
the counter-intuitive outcome where the kernel overwrites the data
before the user gets done loading it.


Release-acquire chains
----------------------

Release-acquire chains are a low-overhead, flexible, and easy-to-use
method of maintaining order.  However, they do have some limitations that
need to be fully understood.  Here is an example that maintains order:

        /* See ISA2+pooncerelease+poacquirerelease+poacquireonce.litmus. */
        void CPU0(void)
        {
                WRITE_ONCE(x, 1);
                smp_store_release(&y, 1);
        }

        void CPU1(void)
        {
                r0 = smp_load_acquire(y);
                smp_store_release(&z, 1);
        }

        void CPU2(void)
        {
                r1 = smp_load_acquire(z);
                r2 = READ_ONCE(x);
        }

In this case, if r0 and r1 both have final values of 1, then r2 must
also have a final value of 1.

The ordering in this example is stronger than it needs to be.  For
example, ordering would still be preserved if CPU1()'s smp_load_acquire()
invocation was replaced with READ_ONCE().

It is tempting to assume that CPU0()'s store to x is globally ordered
before CPU1()'s store to z, but this is not the case:

        /* See Z6.0+pooncerelease+poacquirerelease+mbonceonce.litmus. */
        void CPU0(void)
        {
                WRITE_ONCE(x, 1);
                smp_store_release(&y, 1);
        }

        void CPU1(void)
        {
                r0 = smp_load_acquire(y);
                smp_store_release(&z, 1);
        }

        void CPU2(void)
        {
                WRITE_ONCE(z, 2);
                smp_mb();
                r1 = READ_ONCE(x);
        }

One might hope that if the final value of r0 is 1 and the final value
of z is 2, then the final value of r1 must also be 1, but it really is
possible for r1 to have the final value of 0.  The reason, of course,
is that in this version, CPU2() is not part of the release-acquire chain.
This situation is accounted for in the rules of thumb below.

Despite this limitation, release-acquire chains are low-overhead as
well as simple and powerful, at least as memory-ordering mechanisms go.


Store buffering
---------------

Store buffering can be thought of as upside-down load buffering, so
that one CPU first stores to one variable and then loads from a second,
while another CPU stores to the second variable and then loads from the
first.  Preserving order requires nothing less than full barriers:

        /* See SB+fencembonceonces.litmus. */
        void CPU0(void)
        {
                WRITE_ONCE(x, 1);
                smp_mb();
                r0 = READ_ONCE(y);
        }

        void CPU1(void)
        {
                WRITE_ONCE(y, 1);
                smp_mb();
                r1 = READ_ONCE(x);
        }

Omitting either smp_mb() will allow both r0 and r1 to have final
values of 0, but providing both full barriers as shown above prevents
this counter-intuitive outcome.

This pattern most famously appears as part of Dekker's locking
algorithm, but it has a much more practical use within the Linux kernel
of ordering wakeups.  The following comment taken from waitqueue_active()
in include/linux/wait.h shows the canonical pattern:

 *      CPU0 - waker                    CPU1 - waiter
 *
 *                                      for (;;) {
 *      @cond = true;                     prepare_to_wait(&wq_head, &wait, state);
 *      smp_mb();                         // smp_mb() from set_current_state()
 *      if (waitqueue_active(wq_head))         if (@cond)
 *        wake_up(wq_head);                      break;
 *                                        schedule();
 *                                      }
 *                                      finish_wait(&wq_head, &wait);

On CPU0, the store is to @cond and the load is in waitqueue_active().
On CPU1, prepare_to_wait() contains both a store to wq_head and a call
to set_current_state(), which contains an smp_mb() barrier; the load is
"if (@cond)".  The full barriers prevent the undesirable outcome where
CPU1 puts the waiting task to sleep and CPU0 fails to wake it up.

Note that use of locking can greatly simplify this pattern.


Rules of thumb
==============

There might seem to be no pattern governing what ordering primitives are
needed in which situations, but this is not the case.  There is a pattern
based on the relation between the accesses linking successive CPUs in a
given litmus test.  There are three types of linkage:

1.      Write-to-read, where the next CPU reads the value that the
        previous CPU wrote.  The LB litmus-test patterns contain only
        this type of relation.  In formal memory-modeling texts, this
        relation is called "reads-from" and is usually abbreviated "rf".

2.      Read-to-write, where the next CPU overwrites the value that the
        previous CPU read.  The SB litmus test contains only this type
        of relation.  In formal memory-modeling texts, this relation is
        often called "from-reads" and is sometimes abbreviated "fr".

3.      Write-to-write, where the next CPU overwrites the value written
        by the previous CPU.  The Z6.0 litmus test pattern contains a
        write-to-write relation between the last access of CPU1() and
        the first access of CPU2().  In formal memory-modeling texts,
        this relation is often called "coherence order" and is sometimes
        abbreviated "co".  In the C++ standard, it is instead called
        "modification order" and often abbreviated "mo".

The strength of memory ordering required for a given litmus test to
avoid a counter-intuitive outcome depends on the types of relations
linking the memory accesses for the outcome in question:

o       If all links are write-to-read links, then the weakest
        possible ordering within each CPU suffices.  For example, in
        the LB litmus test, a control dependency was enough to do the
        job.

o       If all but one of the links are write-to-read links, then a
        release-acquire chain suffices.  Both the MP and the ISA2
        litmus tests illustrate this case.

o       If more than one of the links are something other than
        write-to-read links, then a full memory barrier is required
        between each successive pair of non-write-to-read links.  This
        case is illustrated by the Z6.0 litmus tests, both in the
        locking and in the release-acquire sections.

However, if you find yourself having to stretch these rules of thumb
to fit your situation, you should consider creating a litmus test and
running it on the model.

References

Peios Kernel / Kernel development / Development tools / lkmm / docs

Literal include of tools/memory-model/Documentation/references.txt.


This document provides background reading for memory models and related
tools.  These documents are aimed at kernel hackers who are interested
in memory models.


Hardware manuals and models
===========================

o       SPARC International Inc. (Ed.). 1994. "The SPARC Architecture
        Reference Manual Version 9". SPARC International Inc.

o       Compaq Computer Corporation (Ed.). 2002. "Alpha Architecture
        Reference Manual".  Compaq Computer Corporation.

o       Intel Corporation (Ed.). 2002. "A Formal Specification of Intel
        Itanium Processor Family Memory Ordering". Intel Corporation.

o       Intel Corporation (Ed.). 2002. "Intel 64 and IA-32 Architectures
        Software Developer’s Manual". Intel Corporation.

o       Peter Sewell, Susmit Sarkar, Scott Owens, Francesco Zappa Nardelli,
        and Magnus O. Myreen. 2010. "x86-TSO: A Rigorous and Usable
        Programmer's Model for x86 Multiprocessors". Commun. ACM 53, 7
        (July, 2010), 89-97. http://doi.acm.org/10.1145/1785414.1785443

o       IBM Corporation (Ed.). 2009. "Power ISA Version 2.06". IBM
        Corporation.

o       ARM Ltd. (Ed.). 2009. "ARM Barrier Litmus Tests and Cookbook".
        ARM Ltd.

o       Susmit Sarkar, Peter Sewell, Jade Alglave, Luc Maranget, and
        Derek Williams.  2011. "Understanding POWER Multiprocessors". In
        Proceedings of the 32Nd ACM SIGPLAN Conference on Programming
        Language Design and Implementation (PLDI ’11). ACM, New York,
        NY, USA, 175–186.

o       Susmit Sarkar, Kayvan Memarian, Scott Owens, Mark Batty,
        Peter Sewell, Luc Maranget, Jade Alglave, and Derek Williams.
        2012. "Synchronising C/C++ and POWER". In Proceedings of the 33rd
        ACM SIGPLAN Conference on Programming Language Design and
        Implementation (PLDI '12). ACM, New York, NY, USA, 311-322.

o       ARM Ltd. (Ed.). 2014. "ARM Architecture Reference Manual (ARMv8,
        for ARMv8-A architecture profile)". ARM Ltd.

o       Imagination Technologies, LTD. 2015. "MIPS(R) Architecture
        For Programmers, Volume II-A: The MIPS64(R) Instruction,
        Set Reference Manual". Imagination Technologies, LTD.

o       Shaked Flur, Kathryn E. Gray, Christopher Pulte, Susmit
        Sarkar, Ali Sezgin, Luc Maranget, Will Deacon, and Peter
        Sewell. 2016. "Modelling the ARMv8 Architecture, Operationally:
        Concurrency and ISA". In Proceedings of the 43rd Annual ACM
        SIGPLAN-SIGACT Symposium on Principles of Programming Languages
        (POPL ’16). ACM, New York, NY, USA, 608–621.

o       Shaked Flur, Susmit Sarkar, Christopher Pulte, Kyndylan Nienhuis,
        Luc Maranget, Kathryn E. Gray, Ali Sezgin, Mark Batty, and Peter
        Sewell. 2017. "Mixed-size Concurrency: ARM, POWER, C/C++11,
        and SC". In Proceedings of the 44th ACM SIGPLAN Symposium on
        Principles of Programming Languages (POPL 2017). ACM, New York,
        NY, USA, 429–442.

o       Christopher Pulte, Shaked Flur, Will Deacon, Jon French,
        Susmit Sarkar, and Peter Sewell. 2018. "Simplifying ARM concurrency:
        multicopy-atomic axiomatic and operational models for ARMv8". In
        Proceedings of the ACM on Programming Languages, Volume 2, Issue
        POPL, Article No. 19. ACM, New York, NY, USA.


Linux-kernel memory model
=========================

o       Jade Alglave, Will Deacon, Boqun Feng, David Howells, Daniel
        Lustig, Luc Maranget, Paul E. McKenney, Andrea Parri, Nicholas
        Piggin, Alan Stern, Akira Yokosawa, and Peter Zijlstra.
        2019. "Calibrating your fear of big bad optimizing compilers"
        Linux Weekly News.  https://lwn.net/Articles/799218/

o       Jade Alglave, Will Deacon, Boqun Feng, David Howells, Daniel
        Lustig, Luc Maranget, Paul E. McKenney, Andrea Parri, Nicholas
        Piggin, Alan Stern, Akira Yokosawa, and Peter Zijlstra.
        2019. "Who's afraid of a big bad optimizing compiler?"
        Linux Weekly News.  https://lwn.net/Articles/793253/

o       Jade Alglave, Luc Maranget, Paul E. McKenney, Andrea Parri, and
        Alan Stern.  2018. "Frightening small children and disconcerting
        grown-ups: Concurrency in the Linux kernel". In Proceedings of
        the 23rd International Conference on Architectural Support for
        Programming Languages and Operating Systems (ASPLOS 2018). ACM,
        New York, NY, USA, 405-418.  Webpage: http://diy.inria.fr/linux/.

o       Jade Alglave, Luc Maranget, Paul E. McKenney, Andrea Parri, and
        Alan Stern.  2017.  "A formal kernel memory-ordering model (part 1)"
        Linux Weekly News.  https://lwn.net/Articles/718628/

o       Jade Alglave, Luc Maranget, Paul E. McKenney, Andrea Parri, and
        Alan Stern.  2017.  "A formal kernel memory-ordering model (part 2)"
        Linux Weekly News.  https://lwn.net/Articles/720550/

o       Jade Alglave, Luc Maranget, Paul E. McKenney, Andrea Parri, and
        Alan Stern.  2017-2019.  "A Formal Model of Linux-Kernel Memory
        Ordering" (backup material for the LWN articles)
        https://mirrors.edge.kernel.org/pub/linux/kernel/people/paulmck/LWNLinuxMM/


Memory-model tooling
====================

o       Daniel Jackson. 2002. "Alloy: A Lightweight Object Modelling
        Notation". ACM Trans. Softw. Eng. Methodol. 11, 2 (April 2002),
        256–290. http://doi.acm.org/10.1145/505145.505149

o       Jade Alglave, Luc Maranget, and Michael Tautschnig. 2014. "Herding
        Cats: Modelling, Simulation, Testing, and Data Mining for Weak
        Memory". ACM Trans. Program. Lang. Syst. 36, 2, Article 7 (July
        2014), 7:1–7:74 pages.

o       Jade Alglave, Patrick Cousot, and Luc Maranget. 2016. "Syntax and
        semantics of the weak consistency model specification language
        cat". CoRR abs/1608.07531 (2016). https://arxiv.org/abs/1608.07531


Memory-model comparisons
========================

o       Paul E. McKenney, Ulrich Weigand, Andrea Parri, and Boqun
        Feng. 2018. "Linux-Kernel Memory Model". (27 September 2018).
        http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0124r6.html.

Simple

Peios Kernel / Kernel development / Development tools / lkmm / docs

Literal include of tools/memory-model/Documentation/simple.txt.


This document provides options for those wishing to keep their
memory-ordering lives simple, as is necessary for those whose domain
is complex.  After all, there are bugs other than memory-ordering bugs,
and the time spent gaining memory-ordering knowledge is not available
for gaining domain knowledge.  Furthermore Linux-kernel memory model
(LKMM) is quite complex, with subtle differences in code often having
dramatic effects on correctness.

The options near the beginning of this list are quite simple.  The idea
is not that kernel hackers don't already know about them, but rather
that they might need the occasional reminder.

Please note that this is a generic guide, and that specific subsystems
will often have special requirements or idioms.  For example, developers
of MMIO-based device drivers will often need to use mb(), rmb(), and
wmb(), and therefore might find smp_mb(), smp_rmb(), and smp_wmb()
to be more natural than smp_load_acquire() and smp_store_release().
On the other hand, those coming in from other environments will likely
be more familiar with these last two.


Single-threaded code
====================

In single-threaded code, there is no reordering, at least assuming
that your toolchain and hardware are working correctly.  In addition,
it is generally a mistake to assume your code will only run in a single
threaded context as the kernel can enter the same code path on multiple
CPUs at the same time.  One important exception is a function that makes
no external data references.

In the general case, you will need to take explicit steps to ensure that
your code really is executed within a single thread that does not access
shared variables.  A simple way to achieve this is to define a global lock
that you acquire at the beginning of your code and release at the end,
taking care to ensure that all references to your code's shared data are
also carried out under that same lock.  Because only one thread can hold
this lock at a given time, your code will be executed single-threaded.
This approach is called "code locking".

Code locking can severely limit both performance and scalability, so it
should be used with caution, and only on code paths that execute rarely.
After all, a huge amount of effort was required to remove the Linux
kernel's old "Big Kernel Lock", so let's please be very careful about
adding new "little kernel locks".

One of the advantages of locking is that, in happy contrast with the
year 1981, almost all kernel developers are very familiar with locking.
The Linux kernel's lockdep (CONFIG_PROVE_LOCKING=y) is very helpful with
the formerly feared deadlock scenarios.

Please use the standard locking primitives provided by the kernel rather
than rolling your own.  For one thing, the standard primitives interact
properly with lockdep.  For another thing, these primitives have been
tuned to deal better with high contention.  And for one final thing, it is
surprisingly hard to correctly code production-quality lock acquisition
and release functions.  After all, even simple non-production-quality
locking functions must carefully prevent both the CPU and the compiler
from moving code in either direction across the locking function.

Despite the scalability limitations of single-threaded code, RCU
takes this approach for much of its grace-period processing and also
for early-boot operation.  The reason RCU is able to scale despite
single-threaded grace-period processing is use of batching, where all
updates that accumulated during one grace period are handled by the
next one.  In other words, slowing down grace-period processing makes
it more efficient.  Nor is RCU unique:  Similar batching optimizations
are used in many I/O operations.


Packaged code
=============

Even if performance and scalability concerns prevent your code from
being completely single-threaded, it is often possible to use library
functions that handle the concurrency nearly or entirely on their own.
This approach delegates any LKMM worries to the library maintainer.

In the kernel, what is the "library"?  Quite a bit.  It includes the
contents of the lib/ directory, much of the include/linux/ directory along
with a lot of other heavily used APIs.  But heavily used examples include
the list macros (for example, include/linux/{,rcu}list.h), workqueues,
smp_call_function(), and the various hash tables and search trees.


Data locking
============

With code locking, we use single-threaded code execution to guarantee
serialized access to the data that the code is accessing.  However,
we can also achieve this by instead associating the lock with specific
instances of the data structures.  This creates a "critical section"
in the code execution that will execute as though it is single threaded.
By placing all the accesses and modifications to a shared data structure
inside a critical section, we ensure that the execution context that
holds the lock has exclusive access to the shared data.

The poster boy for this approach is the hash table, where placing a lock
in each hash bucket allows operations on different buckets to proceed
concurrently.  This works because the buckets do not overlap with each
other, so that an operation on one bucket does not interfere with any
other bucket.

As the number of buckets increases, data locking scales naturally.
In particular, if the amount of data increases with the number of CPUs,
increasing the number of buckets as the number of CPUs increase results
in a naturally scalable data structure.


Per-CPU processing
==================

Partitioning processing and data over CPUs allows each CPU to take
a single-threaded approach while providing excellent performance and
scalability.  Of course, there is no free lunch:  The dark side of this
excellence is substantially increased memory footprint.

In addition, it is sometimes necessary to occasionally update some global
view of this processing and data, in which case something like locking
must be used to protect this global view.  This is the approach taken
by the percpu_counter infrastructure. In many cases, there are already
generic/library variants of commonly used per-cpu constructs available.
Please use them rather than rolling your own.

RCU uses DEFINE_PER_CPU*() declaration to create a number of per-CPU
data sets.  For example, each CPU does private quiescent-state processing
within its instance of the per-CPU rcu_data structure, and then uses data
locking to report quiescent states up the grace-period combining tree.


Packaged primitives: Sequence locking
=====================================

Lockless programming is considered by many to be more difficult than
lock-based programming, but there are a few lockless design patterns that
have been built out into an API.  One of these APIs is sequence locking.
Although this API can be used in extremely complex ways, there are simple
and effective ways of using it that avoid the need to pay attention to
memory ordering.

The basic keep-things-simple rule for sequence locking is "do not write
in read-side code".  Yes, you can do writes from within sequence-locking
readers, but it won't be so simple.  For example, such writes will be
lockless and should be idempotent.

For more sophisticated use cases, LKMM can guide you, including use
cases involving combining sequence locking with other synchronization
primitives.  (LKMM does not yet know about sequence locking, so it is
currently necessary to open-code it in your litmus tests.)

Additional information may be found in include/linux/seqlock.h.

Packaged primitives: RCU
========================

Another lockless design pattern that has been baked into an API
is RCU.  The Linux kernel makes sophisticated use of RCU, but the
keep-things-simple rules for RCU are "do not write in read-side code"
and "do not update anything that is visible to and accessed by readers",
and "protect updates with locking".

These rules are illustrated by the functions foo_update_a() and
foo_get_a() shown in Documentation/RCU/whatisRCU.rst.  Additional
RCU usage patterns maybe found in Documentation/RCU and in the
source code.


Packaged primitives: Atomic operations
======================================

Back in the day, the Linux kernel had three types of atomic operations:

1.      Initialization and read-out, such as atomic_set() and atomic_read().

2.      Operations that did not return a value and provided no ordering,
        such as atomic_inc() and atomic_dec().

3.      Operations that returned a value and provided full ordering, such as
        atomic_add_return() and atomic_dec_and_test().  Note that some
        value-returning operations provide full ordering only conditionally.
        For example, cmpxchg() provides ordering only upon success.

More recent kernels have operations that return a value but do not
provide full ordering.  These are flagged with either a _relaxed()
suffix (providing no ordering), or an _acquire() or _release() suffix
(providing limited ordering).

Additional information may be found in these files:

Documentation/atomic_t.txt
Documentation/atomic_bitops.txt
Documentation/core-api/refcount-vs-atomic.rst

Reading code using these primitives is often also quite helpful.


Lockless, fully ordered
=======================

When using locking, there often comes a time when it is necessary
to access some variable or another without holding the data lock
that serializes access to that variable.

If you want to keep things simple, use the initialization and read-out
operations from the previous section only when there are no racing
accesses.  Otherwise, use only fully ordered operations when accessing
or modifying the variable.  This approach guarantees that code prior
to a given access to that variable will be seen by all CPUs as having
happened before any code following any later access to that same variable.

Please note that per-CPU functions are not atomic operations and
hence they do not provide any ordering guarantees at all.

If the lockless accesses are frequently executed reads that are used
only for heuristics, or if they are frequently executed writes that
are used only for statistics, please see the next section.


Lockless statistics and heuristics
==================================

Unordered primitives such as atomic_read(), atomic_set(), READ_ONCE(), and
WRITE_ONCE() can safely be used in some cases.  These primitives provide
no ordering, but they do prevent the compiler from carrying out a number
of destructive optimizations (for which please see the next section).
One example use for these primitives is statistics, such as per-CPU
counters exemplified by the rt_cache_stat structure's routing-cache
statistics counters.  Another example use case is heuristics, such as
the jiffies_till_first_fqs and jiffies_till_next_fqs kernel parameters
controlling how often RCU scans for idle CPUs.

But be careful.  "Unordered" really does mean "unordered".  It is all
too easy to assume ordering, and this assumption must be avoided when
using these primitives.


Don't let the compiler trip you up
==================================

It can be quite tempting to use plain C-language accesses for lockless
loads from and stores to shared variables.  Although this is both
possible and quite common in the Linux kernel, it does require a
surprising amount of analysis, care, and knowledge about the compiler.
Yes, some decades ago it was not unfair to consider a C compiler to be
an assembler with added syntax and better portability, but the advent of
sophisticated optimizing compilers mean that those days are long gone.
Today's optimizing compilers can profoundly rewrite your code during the
translation process, and have long been ready, willing, and able to do so.

Therefore, if you really need to use C-language assignments instead of
READ_ONCE(), WRITE_ONCE(), and so on, you will need to have a very good
understanding of both the C standard and your compiler.  Here are some
introductory references and some tooling to start you on this noble quest:

Who's afraid of a big bad optimizing compiler?
        https://lwn.net/Articles/793253/
Calibrating your fear of big bad optimizing compilers
        https://lwn.net/Articles/799218/
Concurrency bugs should fear the big bad data-race detector (part 1)
        https://lwn.net/Articles/816850/
Concurrency bugs should fear the big bad data-race detector (part 2)
        https://lwn.net/Articles/816854/


More complex use cases
======================

If the alternatives above do not do what you need, please look at the
recipes.txt file to peel off the next layer of the memory-ordering
onion.

Peios Learn — documentation for Peios software.

Built with Trail.