code:
Developing Cipher Algorithms
============================

Registering And Unregistering Transformation
--------------------------------------------

There are three distinct types of registration functions in the Crypto
API. One is used to register a generic cryptographic transformation,
while the other two are specific to HASH transformations and
COMPRESSion. We will discuss the latter two in a separate chapter, here
we will only look at the generic ones.

Before discussing the register functions, the data structure to be
filled with each, struct crypto_alg, must be considered -- see below
for a description of this data structure.

The generic registration functions can be found in
include/linux/crypto.h and their definition can be seen below. The
former function registers a single transformation, while the latter
works on an array of transformation descriptions. The latter is useful
when registering transformations in bulk, for example when a driver
implements multiple transformations.

::

       int crypto_register_alg(struct crypto_alg *alg);
       int crypto_register_algs(struct crypto_alg *algs, int count);

The counterparts to those functions are listed below.

::

       void crypto_unregister_alg(struct crypto_alg *alg);
       void crypto_unregister_algs(struct crypto_alg *algs, int count);

The registration functions return 0 on success, or a negative errno
value on failure.  crypto_register_algs() succeeds only if it
successfully registered all the given algorithms; if it fails partway
through, then any changes are rolled back.

The unregistration functions always succeed, so they don't have a
return value.  Don't try to unregister algorithms that aren't
currently registered.

Single-Block Symmetric Ciphers [CIPHER]
---------------------------------------

Example of transformations: aes, serpent, ...

This section describes the simplest of all transformation
implementations, that being the CIPHER type used for symmetric ciphers.
The CIPHER type is used for transformations which operate on exactly one
block at a time and there are no dependencies between blocks at all.

Registration specifics
~~~~~~~~~~~~~~~~~~~~~~

The registration of [CIPHER] algorithm is specific in that struct
crypto_alg field .cra_type is empty. The .cra_u.cipher has to be
filled in with proper callbacks to implement this transformation.

See struct cipher_alg below.

Cipher Definition With struct cipher_alg
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Struct cipher_alg defines a single block cipher.

Here are schematics of how these functions are called when operated from
other part of the kernel. Note that the .cia_setkey() call might happen
before or after any of these schematics happen, but must not happen
during any of these are in-flight.

::

             KEY ---.    PLAINTEXT ---.
                    v                 v
              .cia_setkey() -> .cia_encrypt()
                                      |
                                      '-----> CIPHERTEXT

Please note that a pattern where .cia_setkey() is called multiple times
is also valid:

::

      KEY1 --.    PLAINTEXT1 --.         KEY2 --.    PLAINTEXT2 --.
             v                 v                v                 v
       .cia_setkey() -> .cia_encrypt() -> .cia_setkey() -> .cia_encrypt()
                               |                                  |
                               '---> CIPHERTEXT1                  '---> CIPHERTEXT2

Multi-Block Ciphers
-------------------

Example of transformations: cbc(aes), chacha20, ...

This section describes the multi-block cipher transformation
implementations. The multi-block ciphers are used for transformations
which operate on scatterlists of data supplied to the transformation
functions. They output the result into a scatterlist of data as well.

Registration Specifics
~~~~~~~~~~~~~~~~~~~~~~

The registration of multi-block cipher algorithms is one of the most
standard procedures throughout the crypto API.

Note, if a cipher implementation requires a proper alignment of data,
the caller should use the functions of crypto_skcipher_alignmask() to
identify a memory alignment mask. The kernel crypto API is able to
process requests that are unaligned. This implies, however, additional
overhead as the kernel crypto API needs to perform the realignment of
the data which may imply moving of data.

Cipher Definition With struct skcipher_alg
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Struct skcipher_alg defines a multi-block cipher, or more generally, a
length-preserving symmetric cipher algorithm.

Scatterlist handling
~~~~~~~~~~~~~~~~~~~~

Some drivers will want to use the Generic ScatterWalk in case the
hardware needs to be fed separate chunks of the scatterlist which
contains the plaintext and will contain the ciphertext. Please refer
to the ScatterWalk interface offered by the Linux kernel scatter /
gather list implementation.

Hashing [HASH]
--------------

Example of transformations: crc32, md5, sha1, sha256,...

Registering And Unregistering The Transformation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

There are multiple ways to register a HASH transformation, depending on
whether the transformation is synchronous [SHASH] or asynchronous
[AHASH] and the amount of HASH transformations we are registering. You
can find the prototypes defined in include/crypto/internal/hash.h:

::

       int crypto_register_ahash(struct ahash_alg *alg);

       int crypto_register_shash(struct shash_alg *alg);
       int crypto_register_shashes(struct shash_alg *algs, int count);

The respective counterparts for unregistering the HASH transformation
are as follows:

::

       void crypto_unregister_ahash(struct ahash_alg *alg);

       void crypto_unregister_shash(struct shash_alg *alg);
       void crypto_unregister_shashes(struct shash_alg *algs, int count);

Cipher Definition With struct shash_alg and ahash_alg
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Here are schematics of how these functions are called when operated from
other part of the kernel. Note that the .setkey() call might happen
before or after any of these schematics happen, but must not happen
during any of these are in-flight. Please note that calling .init()
followed immediately by .final() is also a perfectly valid
transformation.

::

       I)   DATA -----------.
                            v
             .init() -> .update() -> .final()      ! .update() might not be called
                         ^    |         |            at all in this scenario.
                         '----'         '---> HASH

       II)  DATA -----------.-----------.
                            v           v
             .init() -> .update() -> .finup()      ! .update() may not be called
                         ^    |         |            at all in this scenario.
                         '----'         '---> HASH

       III) DATA -----------.
                            v
                        .digest()                  ! The entire process is handled
                            |                        by the .digest() call.
                            '---------------> HASH

Here is a schematic of how the .export()/.import() functions are called
when used from another part of the kernel.

::

       KEY--.                 DATA--.
            v                       v                  ! .update() may not be called
        .setkey() -> .init() -> .update() -> .export()   at all in this scenario.
                                 ^     |         |
                                 '-----'         '--> PARTIAL_HASH

       ----------- other transformations happen here -----------

       PARTIAL_HASH--.   DATA1--.
                     v          v
                 .import -> .update() -> .final()     ! .update() may not be called
                             ^    |         |           at all in this scenario.
                             '----'         '--> HASH1

       PARTIAL_HASH--.   DATA2-.
                     v         v
                 .import -> .finup()
                               |
                               '---------------> HASH2

Note that it is perfectly legal to "abandon" a request object:
- call .init() and then (as many times) .update()
- _not_ call any of .final(), .finup() or .export() at any point in future

In other words implementations should mind the resource allocation and clean-up.
No resources related to request objects should remain allocated after a call
to .init() or .update(), since there might be no chance to free them.

Specifics Of Asynchronous HASH Transformation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Some of the drivers will want to use the Generic ScatterWalk in case the
implementation needs to be fed separate chunks of the scatterlist which
contains the input data. The buffer containing the resulting hash will
always be properly aligned to .cra_alignmask so there is no need to
worry about this.


code:
=======================
Linux Kernel Crypto API
=======================

:Author: Stephan Mueller
:Author: Marek Vasut

This documentation outlines the Linux kernel crypto API with its
concepts, details about developing cipher implementations, employment of the API
for cryptographic use cases, as well as programming examples.

.. class:: toc-title

	   Table of contents

.. toctree::
   :maxdepth: 2

   intro
   api-intro
   architecture

   async-tx-api
   asymmetric-keys
   devel-algos
   userspace-if
   crypto_engine
   api
   api-samples
   descore-readme

repo_name: angery/linux


code:
Kernel Crypto API Interface Specification
=========================================

Introduction
------------

The kernel crypto API offers a rich set of cryptographic ciphers as well
as other data transformation mechanisms and methods to invoke these.
This document contains a description of the API and provides example
code.

To understand and properly use the kernel crypto API a brief explanation
of its structure is given. Based on the architecture, the API can be
separated into different components. Following the architecture
specification, hints to developers of ciphers are provided. Pointers to
the API function call documentation are given at the end.

The kernel crypto API refers to all algorithms as "transformations".
Therefore, a cipher handle variable usually has the name "tfm". Besides
cryptographic operations, the kernel crypto API also knows compression
transformations and handles them the same way as ciphers.

The kernel crypto API serves the following entity types:

-  consumers requesting cryptographic services

-  data transformation implementations (typically ciphers) that can be
   called by consumers using the kernel crypto API

This specification is intended for consumers of the kernel crypto API as
well as for developers implementing ciphers. This API specification,
however, does not discuss all API calls available to data transformation
implementations (i.e. implementations of ciphers and other
transformations (such as CRC or even compression algorithms) that can
register with the kernel crypto API).

Note: The terms "transformation" and cipher algorithm are used
interchangeably.

Terminology
-----------

The transformation implementation is an actual code or interface to
hardware which implements a certain transformation with precisely
defined behavior.

The transformation object (TFM) is an instance of a transformation
implementation. There can be multiple transformation objects associated
with a single transformation implementation. Each of those
transformation objects is held by a crypto API consumer or another
transformation. Transformation object is allocated when a crypto API
consumer requests a transformation implementation. The consumer is then
provided with a structure, which contains a transformation object (TFM).

The structure that contains transformation objects may also be referred
to as a "cipher handle". Such a cipher handle is always subject to the
following phases that are reflected in the API calls applicable to such
a cipher handle:

1. Initialization of a cipher handle.

2. Execution of all intended cipher operations applicable for the handle
   where the cipher handle must be furnished to every API call.

3. Destruction of a cipher handle.

When using the initialization API calls, a cipher handle is created and
returned to the consumer. Therefore, please refer to all initialization
API calls that refer to the data structure type a consumer is expected
to receive and subsequently to use. The initialization API calls have
all the same naming conventions of crypto_alloc\*.

The transformation context is private data associated with the
transformation object.


code:
User Space Interface
====================

Introduction
------------

The concepts of the kernel crypto API visible to kernel space is fully
applicable to the user space interface as well. Therefore, the kernel
crypto API high level discussion for the in-kernel use cases applies
here as well.

The major difference, however, is that user space can only act as a
consumer and never as a provider of a transformation or cipher
algorithm.

The following covers the user space interface exported by the kernel
crypto API. A working example of this description is libkcapi that can
be obtained from [1]. That library can be used by user space
applications that require cryptographic services from the kernel.

Some details of the in-kernel kernel crypto API aspects do not apply to
user space, however. This includes the difference between synchronous
and asynchronous invocations. The user space API call is fully
synchronous.

[1] https://www.chronox.de/libkcapi.html

User Space API General Remarks
------------------------------

The kernel crypto API is accessible from user space. Currently, the
following ciphers are accessible:

-  Message digest including keyed message digest (HMAC, CMAC)

-  Symmetric ciphers

-  AEAD ciphers

-  Random Number Generators

The interface is provided via socket type using the type AF_ALG. In
addition, the setsockopt option type is SOL_ALG. In case the user space
header files do not export these flags yet, use the following macros:

::

    #ifndef AF_ALG
    #define AF_ALG 38
    #endif
    #ifndef SOL_ALG
    #define SOL_ALG 279
    #endif

A cipher is accessed with the same name as done for the in-kernel API
calls. This includes the generic vs. unique naming schema for ciphers as
well as the enforcement of priorities for generic names.

To interact with the kernel crypto API, a socket must be created by the
user space application. User space invokes the cipher operation with the
send()/write() system call family. The result of the cipher operation is
obtained with the read()/recv() system call family.

The following API calls assume that the socket descriptor is already
opened by the user space application and discusses only the kernel
crypto API specific invocations.

To initialize the socket interface, the following sequence has to be
performed by the consumer:

1. Create a socket of type AF_ALG with the struct sockaddr_alg
   parameter specified below for the different cipher types.

2. Invoke bind with the socket descriptor

3. Invoke accept with the socket descriptor. The accept system call
   returns a new file descriptor that is to be used to interact with the
   particular cipher instance. When invoking send/write or recv/read
   system calls to send data to the kernel or obtain data from the
   kernel, the file descriptor returned by accept must be used.

In-place Cipher operation
-------------------------

Just like the in-kernel operation of the kernel crypto API, the user
space interface allows the cipher operation in-place. That means that
the input buffer used for the send/write system call and the output
buffer used by the read/recv system call may be one and the same. This
is of particular interest for symmetric cipher operations where a
copying of the output data to its final destination can be avoided.

If a consumer on the other hand wants to maintain the plaintext and the
ciphertext in different memory locations, all a consumer needs to do is
to provide different memory pointers for the encryption and decryption
operation.

Message Digest API
------------------

The message digest type to be used for the cipher operation is selected
when invoking the bind syscall. bind requires the caller to provide a
filled struct sockaddr data structure. This data structure must be
filled as follows:

::

    struct sockaddr_alg sa = {
        .salg_family = AF_ALG,
        .salg_type = "hash", /* this selects the hash logic in the kernel */
        .salg_name = "sha1" /* this is the cipher name */
    };

The salg_type value "hash" applies to message digests and keyed message
digests. Though, a keyed message digest is referenced by the appropriate
salg_name. Please see below for the setsockopt interface that explains
how the key can be set for a keyed message digest.

Using the send() system call, the application provides the data that
should be processed with the message digest. The send system call allows
the following flags to be specified:

-  MSG_MORE: If this flag is set, the send system call acts like a
   message digest update function where the final hash is not yet
   calculated. If the flag is not set, the send system call calculates
   the final message digest immediately.

With the recv() system call, the application can read the message digest
from the kernel crypto API. If the buffer is too small for the message
digest, the flag MSG_TRUNC is set by the kernel.

In order to set a message digest key, the calling application must use
the setsockopt() option of ALG_SET_KEY or ALG_SET_KEY_BY_KEY_SERIAL. If the
key is not set the HMAC operation is performed without the initial HMAC state
change caused by the key.

Symmetric Cipher API
--------------------

The operation is very similar to the message digest discussion. During
initialization, the struct sockaddr data structure must be filled as
follows:

::

    struct sockaddr_alg sa = {
        .salg_family = AF_ALG,
        .salg_type = "skcipher", /* this selects the symmetric cipher */
        .salg_name = "cbc(aes)" /* this is the cipher name */
    };

Before data can be sent to the kernel using the write/send system call
family, the consumer must set the key. The key setting is described with
the setsockopt invocation below.

Using the sendmsg() system call, the application provides the data that
should be processed for encryption or decryption. In addition, the IV is
specified with the data structure provided by the sendmsg() system call.

The sendmsg system call parameter of struct msghdr is embedded into the
struct cmsghdr data structure. See recv(2) and cmsg(3) for more
information on how the cmsghdr data structure is used together with the
send/recv system call family. That cmsghdr data structure holds the
following information specified with a separate header instances:

-  specification of the cipher operation type with one of these flags:

   -  ALG_OP_ENCRYPT - encryption of data

   -  ALG_OP_DECRYPT - decryption of data

-  specification of the IV information marked with the flag ALG_SET_IV

The send system call family allows the following flag to be specified:

-  MSG_MORE: If this flag is set, the send system call acts like a
   cipher update function where more input data is expected with a
   subsequent invocation of the send system call.

Note: The kernel reports -EINVAL for any unexpected data. The caller
must make sure that all data matches the constraints given in
/proc/crypto for the selected cipher.

With the recv() system call, the application can read the result of the
cipher operation from the kernel crypto API. The output buffer must be
at least as large as to hold all blocks of the encrypted or decrypted
data. If the output data size is smaller, only as many blocks are
returned that fit into that output buffer size.

AEAD Cipher API
---------------

The operation is very similar to the symmetric cipher discussion. During
initialization, the struct sockaddr data structure must be filled as
follows:

::

    struct sockaddr_alg sa = {
        .salg_family = AF_ALG,
        .salg_type = "aead", /* this selects the symmetric cipher */
        .salg_name = "gcm(aes)" /* this is the cipher name */
    };

Before data can be sent to the kernel using the write/send system call
family, the consumer must set the key. The key setting is described with
the setsockopt invocation below.

In addition, before data can be sent to the kernel using the write/send
system call family, the consumer must set the authentication tag size.
To set the authentication tag size, the caller must use the setsockopt
invocation described below.

Using the sendmsg() system call, the application provides the data that
should be processed for encryption or decryption. In addition, the IV is
specified with the data structure provided by the sendmsg() system call.

The sendmsg system call parameter of struct msghdr is embedded into the
struct cmsghdr data structure. See recv(2) and cmsg(3) for more
information on how the cmsghdr data structure is used together with the
send/recv system call family. That cmsghdr data structure holds the
following information specified with a separate header instances:

-  specification of the cipher operation type with one of these flags:

   -  ALG_OP_ENCRYPT - encryption of data

   -  ALG_OP_DECRYPT - decryption of data

-  specification of the IV information marked with the flag ALG_SET_IV

-  specification of the associated authentication data (AAD) with the
   flag ALG_SET_AEAD_ASSOCLEN. The AAD is sent to the kernel together
   with the plaintext / ciphertext. See below for the memory structure.

The send system call family allows the following flag to be specified:

-  MSG_MORE: If this flag is set, the send system call acts like a
   cipher update function where more input data is expected with a
   subsequent invocation of the send system call.

Note: The kernel reports -EINVAL for any unexpected data. The caller
must make sure that all data matches the constraints given in
/proc/crypto for the selected cipher.

With the recv() system call, the application can read the result of the
cipher operation from the kernel crypto API. The output buffer must be
at least as large as defined with the memory structure below. If the
output data size is smaller, the cipher operation is not performed.

The authenticated decryption operation may indicate an integrity error.
Such breach in integrity is marked with the -EBADMSG error code.

AEAD Memory Structure
~~~~~~~~~~~~~~~~~~~~~

The AEAD cipher operates with the following information that is
communicated between user and kernel space as one data stream:

-  plaintext or ciphertext

-  associated authentication data (AAD)

-  authentication tag

The sizes of the AAD and the authentication tag are provided with the
sendmsg and setsockopt calls (see there). As the kernel knows the size
of the entire data stream, the kernel is now able to calculate the right
offsets of the data components in the data stream.

The user space caller must arrange the aforementioned information in the
following order:

-  AEAD encryption input: AAD \|\| plaintext

-  AEAD decryption input: AAD \|\| ciphertext \|\| authentication tag

The output buffer the user space caller provides must be at least as
large to hold the following data:

-  AEAD encryption output: ciphertext \|\| authentication tag

-  AEAD decryption output: plaintext

Random Number Generator API
---------------------------

Again, the operation is very similar to the other APIs. During
initialization, the struct sockaddr data structure must be filled as
follows:

::

    struct sockaddr_alg sa = {
        .salg_family = AF_ALG,
        .salg_type = "rng", /* this selects the random number generator */
        .salg_name = "drbg_nopr_sha256" /* this is the RNG name */
    };

Depending on the RNG type, the RNG must be seeded. The seed is provided
using the setsockopt interface to set the key. For example, the
ansi_cprng requires a seed. The DRBGs do not require a seed, but may be
seeded. The seed is also known as a *Personalization String* in NIST SP 800-90A
standard.

Using the read()/recvmsg() system calls, random numbers can be obtained.
The kernel generates at most 128 bytes in one call. If user space
requires more data, multiple calls to read()/recvmsg() must be made.

WARNING: The user space caller may invoke the initially mentioned accept
system call multiple times. In this case, the returned file descriptors
have the same state.

Following CAVP testing interfaces are enabled when kernel is built with
CRYPTO_USER_API_RNG_CAVP option:

-  the concatenation of *Entropy* and *Nonce* can be provided to the RNG via
   ALG_SET_DRBG_ENTROPY setsockopt interface. Setting the entropy requires
   CAP_SYS_ADMIN permission.

-  *Additional Data* can be provided using the send()/sendmsg() system calls,
   but only after the entropy has been set.

Zero-Copy Interface
-------------------

In addition to the send/write/read/recv system call family, the AF_ALG
interface can be accessed with the zero-copy interface of
splice/vmsplice. As the name indicates, the kernel tries to avoid a copy
operation into kernel space.

The zero-copy operation requires data to be aligned at the page
boundary. Non-aligned data can be used as well, but may require more
operations of the kernel which would defeat the speed gains obtained
from the zero-copy interface.

The system-inherent limit for the size of one zero-copy operation is 16
pages. If more data is to be sent to AF_ALG, user space must slice the
input into segments with a maximum size of 16 pages.

Zero-copy can be used with the following code example (a complete
working example is provided with libkcapi):

::

    int pipes[2];

    pipe(pipes);
    /* input data in iov */
    vmsplice(pipes[1], iov, iovlen, SPLICE_F_GIFT);
    /* opfd is the file descriptor returned from accept() system call */
    splice(pipes[0], NULL, opfd, NULL, ret, 0);
    read(opfd, out, outlen);

Setsockopt Interface
--------------------

In addition to the read/recv and send/write system call handling to send
and retrieve data subject to the cipher operation, a consumer also needs
to set the additional information for the cipher operation. This
additional information is set using the setsockopt system call that must
be invoked with the file descriptor of the open cipher (i.e. the file
descriptor returned by the accept system call).

Each setsockopt invocation must use the level SOL_ALG.

The setsockopt interface allows setting the following data using the
mentioned optname:

-  ALG_SET_KEY -- Setting the key. Key setting is applicable to:

   -  the skcipher cipher type (symmetric ciphers)

   -  the hash cipher type (keyed message digests)

   -  the AEAD cipher type

   -  the RNG cipher type to provide the seed

- ALG_SET_KEY_BY_KEY_SERIAL -- Setting the key via keyring key_serial_t.
   This operation behaves the same as ALG_SET_KEY. The decrypted
   data is copied from a keyring key, and uses that data as the
   key for symmetric encryption.

   The passed in key_serial_t must have the KEY_(POS|USR|GRP|OTH)_SEARCH
   permission set, otherwise -EPERM is returned. Supports key types: user,
   logon, encrypted, and trusted.

-  ALG_SET_AEAD_AUTHSIZE -- Setting the authentication tag size for
   AEAD ciphers. For a encryption operation, the authentication tag of
   the given size will be generated. For a decryption operation, the
   provided ciphertext is assumed to contain an authentication tag of
   the given size (see section about AEAD memory layout below).

-  ALG_SET_DRBG_ENTROPY -- Setting the entropy of the random number generator.
   This option is applicable to RNG cipher type only.

User space API example
----------------------

Please see [1] for libkcapi which provides an easy-to-use wrapper around
the aforementioned Netlink kernel interface. [1] also contains a test
application that invokes all libkcapi API calls.

[1] https://www.chronox.de/libkcapi.html


code:
.. SPDX-License-Identifier: GPL-2.0-only

==========
Checkpatch
==========

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 exists, 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 maybe 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.

.. Types in this section are also parsed by checkpatch.
.. The types are grouped into subsections based on use.

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

  **DEPRECATED_VARIABLE**
    EXTRA_{A,C,CPP,LD}FLAGS are deprecated and should be replaced by the new
    flags added via commit f77bf01425b1 ("kbuild: introduce ccflags-y,
    asflags-y and ldflags-y").

    The following conversion scheme maybe used::

      EXTRA_AFLAGS    ->  asflags-y
      EXTRA_CFLAGS    ->  ccflags-y
      EXTRA_CPPFLAGS  ->  cppflags-y
      EXTRA_LDFLAGS   ->  ldflags-y

    See:

      1. https://lore.kernel.org/lkml/20070930191054.GA15876@uranus.ravnborg.org/
      2. https://lore.kernel.org/lkml/1313384834-24433-12-git-send-email-lacombar@gmail.com/
      3. https://www.kernel.org/doc/html/latest/kbuild/makefiles.html#compilation-flags

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

    See: https://www.kernel.org/doc/html/latest/timers/timers-howto.html#delays-information-on-the-various-kernel-delay-sleep-mechanisms

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

    The networking comment style is a bit different, with the first line
    not empty like the former::

      /* This is the preferred comment style
      * for files in net/ and drivers/net/
      */

    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/

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

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

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

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();

      2. Comparisons in if::

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

        could be::

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

      3. 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.

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


code:
.. Copyright 2010 Nicolas Palix <npalix@diku.dk>
.. Copyright 2010 Julia Lawall <julia@diku.dk>
.. Copyright 2010 Gilles Muller <Gilles.Muller@lip6.fr>

.. highlight:: none

.. _devtools_coccinelle:

Coccinelle
==========

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

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.

Alternatively you can debug running Coccinelle against SmPL patches
by asking for stderr to be redirected to stderr. 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

Since coccicheck runs through make, it naturally runs from the kernel
proper dir; as such the second rule above would be implied for picking up a
.cocciconfig when using ``make coccicheck``.

``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::

    if [ "$KBUILD_EXTMOD" = "" ] ; then
        OPTIONS="--dir $srctree $COCCIINCLUDE"
    else
        OPTIONS="--dir $KBUILD_EXTMOD $COCCIINCLUDE"
    fi

KBUILD_EXTMOD is set when an explicit target with M= is used. For both cases
the spatch --dir argument is used, as such third rule applies when whether M=
is used or not, and when M= is used the target directory can have its own
.cocciconfig file. When M= is not passed as an argument to coccicheck the
target directory is the same as the directory from where spatch was called.

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]]


code:
Using gcov with the Linux kernel
================================

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?)

.. _gcov: https://gcc.gnu.org/onlinedocs/gcc/Gcov.html
.. _lcov: http://ltp.sourceforge.net/coverage/lcov.php

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.

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:

.. _gcov-test:

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

.. _gcov-build:

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.

.. _gcov: https://gcc.gnu.org/onlinedocs/gcc/Gcov.html
.. _llvm-cov: https://llvm.org/docs/CommandGuide/llvm-cov.html

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 :ref:`Separated build and test machines a. <gcov-test>`):

.. code-block:: sh

    #!/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 :ref:`Separated build and test machines b. <gcov-build>`):

.. code-block:: sh

    #!/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"