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

.. _researcher_guidelines:

Researcher Guidelines
+++++++++++++++++++++

The Linux kernel community welcomes transparent research on the Linux
kernel, the activities involved in producing it, and any other byproducts
of its development. Linux benefits greatly from this kind of research, and
most aspects of Linux are driven by research in one form or another.

The community greatly appreciates if researchers can share preliminary
findings before making their results public, especially if such research
involves security. Getting involved early helps both improve the quality
of research and ability for Linux to improve from it. In any case,
sharing open access copies of the published research with the community
is recommended.

This document seeks to clarify what the Linux kernel community considers
acceptable and non-acceptable practices when conducting such research. At
the very least, such research and related activities should follow
standard research ethics rules. For more background on research ethics
generally, ethics in technology, and research of developer communities
in particular, see:

* `History of Research Ethics <https://www.unlv.edu/research/ORI-HSR/history-ethics>`_
* `IEEE Ethics <https://www.ieee.org/about/ethics/index.html>`_
* `Developer and Researcher Views on the Ethics of Experiments on Open-Source Projects <https://arxiv.org/pdf/2112.13217.pdf>`_

The Linux kernel community expects that everyone interacting with the
project is participating in good faith to make Linux better. Research on
any publicly-available artifact (including, but not limited to source
code) produced by the Linux kernel community is welcome, though research
on developers must be distinctly opt-in.

Passive research that is based entirely on publicly available sources,
including posts to public mailing lists and commits to public
repositories, is clearly permissible. Though, as with any research,
standard ethics must still be followed.

Active research on developer behavior, however, must be done with the
explicit agreement of, and full disclosure to, the individual developers
involved. Developers cannot be interacted with/experimented on without
consent; this, too, is standard research ethics.

To help clarify: sending patches to developers *is* interacting
with them, but they have already consented to receiving *good faith
contributions*. Sending intentionally flawed/vulnerable patches or
contributing misleading information to discussions is not consented
to. Such communication can be damaging to the developer (e.g. draining
time, effort, and morale) and damaging to the project by eroding
the entire developer community's trust in the contributor (and the
contributor's organization as a whole), undermining efforts to provide
constructive feedback to contributors, and putting end users at risk of
software flaws.

Participation in the development of Linux itself by researchers, as
with anyone, is welcomed and encouraged. Research into Linux code is
a common practice, especially when it comes to developing or running
analysis tools that produce actionable results.

When engaging with the developer community, sending a patch has
traditionally been the best way to make an impact. Linux already has
plenty of known bugs -- what's much more helpful is having vetted fixes.
Before contributing, carefully read the appropriate documentation:

* Documentation/process/development-process.rst
* Documentation/process/submitting-patches.rst
* Documentation/admin-guide/reporting-issues.rst
* Documentation/admin-guide/security-bugs.rst

Then send a patch (including a commit log with all the details listed
below) and follow up on any feedback from other developers.

When sending patches produced from research, the commit logs should
contain at least the following details, so that developers have
appropriate context for understanding the contribution. Answer:

* What is the specific problem that has been found?
* How could the problem be reached on a running system?
* What effect would encountering the problem have on the system?
* How was the problem found? Specifically include details about any
  testing, static or dynamic analysis programs, and any other tools or
  methods used to perform the work.
* Which version of Linux was the problem found on? Using the most recent
  release or a recent linux-next branch is strongly preferred (see
  Documentation/process/howto.rst).
* What was changed to fix the problem, and why it is believed to be correct?
* How was the change build tested and run-time tested?
* What prior commit does this change fix? This should go in a "Fixes:"
  tag as the documentation describes.
* Who else has reviewed this patch? This should go in appropriate
  "Reviewed-by:" tags; see below.

For example::

  From: Author <author@email>
  Subject: [PATCH] drivers/foo_bar: Add missing kfree()

  The error path in foo_bar driver does not correctly free the allocated
  struct foo_bar_info. This can happen if the attached foo_bar device
  rejects the initialization packets sent during foo_bar_probe(). This
  would result in a 64 byte slab memory leak once per device attach,
  wasting memory resources over time.

  This flaw was found using an experimental static analysis tool we are
  developing, LeakMagic[1], which reported the following warning when
  analyzing the v5.15 kernel release:

   path/to/foo_bar.c:187: missing kfree() call?

  Add the missing kfree() to the error path. No other references to
  this memory exist outside the probe function, so this is the only
  place it can be freed.

  x86_64 and arm64 defconfig builds with CONFIG_FOO_BAR=y using GCC
  11.2 show no new warnings, and LeakMagic no longer warns about this
  code path. As we don't have a FooBar device to test with, no runtime
  testing was able to be performed.

  [1] https://url/to/leakmagic/details

  Reported-by: Researcher <researcher@email>
  Fixes: aaaabbbbccccdddd ("Introduce support for FooBar")
  Signed-off-by: Author <author@email>
  Reviewed-by: Reviewer <reviewer@email>

If you are a first time contributor it is recommended that the patch
itself be vetted by others privately before being posted to public lists.
(This is required if you have been explicitly told your patches need
more careful internal review.) These people are expected to have their
"Reviewed-by" tag included in the resulting patch. Finding another
developer familiar with Linux contribution, especially within your own
organization, and having them help with reviews before sending them to
the public mailing lists tends to significantly improve the quality of the
resulting patches, and there by reduces the burden on other developers.

If no one can be found to internally review patches and you need
help finding such a person, or if you have any other questions
related to this document and the developer community's expectations,
please reach out to the private Technical Advisory Board mailing list:
<tech-board@lists.linux-foundation.org>.


code:
.. _stable_api_nonsense:

The Linux Kernel Driver Interface
==================================

(all of your questions answered and then some)

Greg Kroah-Hartman <greg@kroah.com>

This is being written to try to explain why Linux **does not have a binary
kernel interface, nor does it have a stable kernel interface**.

.. note::

  Please realize that this article describes the **in kernel** interfaces, not
  the kernel to userspace interfaces.

  The kernel to userspace interface is the one that application programs use,
  the syscall interface.  That interface is **very** stable over time, and
  will not break.  I have old programs that were built on a pre 0.9something
  kernel that still work just fine on the latest 2.6 kernel release.
  That interface is the one that users and application programmers can count
  on being stable.

Executive Summary
-----------------
You think you want a stable kernel interface, but you really do not, and
you don't even know it.  What you want is a stable running driver, and
you get that only if your driver is in the main kernel tree.  You also
get lots of other good benefits if your driver is in the main kernel
tree, all of which has made Linux into such a strong, stable, and mature
operating system which is the reason you are using it in the first
place.

Intro
-----

It's only the odd person who wants to write a kernel driver that needs
to worry about the in-kernel interfaces changing.  For the majority of
the world, they neither see this interface, nor do they care about it at
all.

First off, I'm not going to address **any** legal issues about closed
source, hidden source, binary blobs, source wrappers, or any other term
that describes kernel drivers that do not have their source code
released under the GPL.  Please consult a lawyer if you have any legal
questions, I'm a programmer and hence, I'm just going to be describing
the technical issues here (not to make light of the legal issues, they
are real, and you do need to be aware of them at all times.)

So, there are two main topics here, binary kernel interfaces and stable
kernel source interfaces.  They both depend on each other, but we will
discuss the binary stuff first to get it out of the way.

Binary Kernel Interface
-----------------------
Assuming that we had a stable kernel source interface for the kernel, a
binary interface would naturally happen too, right?  Wrong.  Please
consider the following facts about the Linux kernel:

  - Depending on the version of the C compiler you use, different kernel
    data structures will contain different alignment of structures, and
    possibly include different functions in different ways (putting
    functions inline or not.)  The individual function organization
    isn't that important, but the different data structure padding is
    very important.

  - Depending on what kernel build options you select, a wide range of
    different things can be assumed by the kernel:

      - different structures can contain different fields
      - Some functions may not be implemented at all, (i.e. some locks
	compile away to nothing for non-SMP builds.)
      - Memory within the kernel can be aligned in different ways,
	depending on the build options.

  - Linux runs on a wide range of different processor architectures.
    There is no way that binary drivers from one architecture will run
    on another architecture properly.

Now a number of these issues can be addressed by simply compiling your
module for the exact specific kernel configuration, using the same exact
C compiler that the kernel was built with.  This is sufficient if you
want to provide a module for a specific release version of a specific
Linux distribution.  But multiply that single build by the number of
different Linux distributions and the number of different supported
releases of the Linux distribution and you quickly have a nightmare of
different build options on different releases.  Also realize that each
Linux distribution release contains a number of different kernels, all
tuned to different hardware types (different processor types and
different options), so for even a single release you will need to create
multiple versions of your module.

Trust me, you will go insane over time if you try to support this kind
of release, I learned this the hard way a long time ago...

Stable Kernel Source Interfaces
-------------------------------

This is a much more "volatile" topic if you talk to people who try to
keep a Linux kernel driver that is not in the main kernel tree up to
date over time.

Linux kernel development is continuous and at a rapid pace, never
stopping to slow down.  As such, the kernel developers find bugs in
current interfaces, or figure out a better way to do things.  If they do
that, they then fix the current interfaces to work better.  When they do
so, function names may change, structures may grow or shrink, and
function parameters may be reworked.  If this happens, all of the
instances of where this interface is used within the kernel are fixed up
at the same time, ensuring that everything continues to work properly.

As a specific examples of this, the in-kernel USB interfaces have
undergone at least three different reworks over the lifetime of this
subsystem.  These reworks were done to address a number of different
issues:

  - A change from a synchronous model of data streams to an asynchronous
    one.  This reduced the complexity of a number of drivers and
    increased the throughput of all USB drivers such that we are now
    running almost all USB devices at their maximum speed possible.
  - A change was made in the way data packets were allocated from the
    USB core by USB drivers so that all drivers now needed to provide
    more information to the USB core to fix a number of documented
    deadlocks.

This is in stark contrast to a number of closed source operating systems
which have had to maintain their older USB interfaces over time.  This
provides the ability for new developers to accidentally use the old
interfaces and do things in improper ways, causing the stability of the
operating system to suffer.

In both of these instances, all developers agreed that these were
important changes that needed to be made, and they were made, with
relatively little pain.  If Linux had to ensure that it will preserve a
stable source interface, a new interface would have been created, and
the older, broken one would have had to be maintained over time, leading
to extra work for the USB developers.  Since all Linux USB developers do
their work on their own time, asking programmers to do extra work for no
gain, for free, is not a possibility.

Security issues are also very important for Linux.  When a
security issue is found, it is fixed in a very short amount of time.  A
number of times this has caused internal kernel interfaces to be
reworked to prevent the security problem from occurring.  When this
happens, all drivers that use the interfaces were also fixed at the
same time, ensuring that the security problem was fixed and could not
come back at some future time accidentally.  If the internal interfaces
were not allowed to change, fixing this kind of security problem and
insuring that it could not happen again would not be possible.

Kernel interfaces are cleaned up over time.  If there is no one using a
current interface, it is deleted.  This ensures that the kernel remains
as small as possible, and that all potential interfaces are tested as
well as they can be (unused interfaces are pretty much impossible to
test for validity.)

What to do
----------

So, if you have a Linux kernel driver that is not in the main kernel
tree, what are you, a developer, supposed to do?  Releasing a binary
driver for every different kernel version for every distribution is a
nightmare, and trying to keep up with an ever changing kernel interface
is also a rough job.

Simple, get your kernel driver into the main kernel tree (remember we are
talking about drivers released under a GPL-compatible license here, if your
code doesn't fall under this category, good luck, you are on your own here,
you leech).  If your driver is in the tree, and a kernel interface changes,
it will be fixed up by the person who did the kernel change in the first
place.  This ensures that your driver is always buildable, and works over
time, with very little effort on your part.

The very good side effects of having your driver in the main kernel tree
are:

  - The quality of the driver will rise as the maintenance costs (to the
    original developer) will decrease.
  - Other developers will add features to your driver.
  - Other people will find and fix bugs in your driver.
  - Other people will find tuning opportunities in your driver.
  - Other people will update the driver for you when external interface
    changes require it.
  - The driver automatically gets shipped in all Linux distributions
    without having to ask the distros to add it.

As Linux supports a larger number of different devices "out of the box"
than any other operating system, and it supports these devices on more
different processor architectures than any other operating system, this
proven type of development model must be doing something right :)

------

Thanks to Randy Dunlap, Andrew Morton, David Brownell, Hanna Linder,
Robert Love, and Nishanth Aravamudan for their review and comments on
early drafts of this paper.

repo_name: angery/linux


code:
.. _stable_kernel_rules:

Everything you ever wanted to know about Linux -stable releases
===============================================================

Rules on what kind of patches are accepted, and which ones are not, into the
"-stable" tree:

 - It must be obviously correct and tested.
 - It cannot be bigger than 100 lines, with context.
 - It must fix only one thing.
 - It must fix a real bug that bothers people (not a, "This could be a
   problem..." type thing).
 - It must fix a problem that causes a build error (but not for things
   marked CONFIG_BROKEN), an oops, a hang, data corruption, a real
   security issue, or some "oh, that's not good" issue.  In short, something
   critical.
 - Serious issues as reported by a user of a distribution kernel may also
   be considered if they fix a notable performance or interactivity issue.
   As these fixes are not as obvious and have a higher risk of a subtle
   regression they should only be submitted by a distribution kernel
   maintainer and include an addendum linking to a bugzilla entry if it
   exists and additional information on the user-visible impact.
 - New device IDs and quirks are also accepted.
 - No "theoretical race condition" issues, unless an explanation of how the
   race can be exploited is also provided.
 - It cannot contain any "trivial" fixes in it (spelling changes,
   whitespace cleanups, etc).
 - It must follow the
   :ref:`Documentation/process/submitting-patches.rst <submittingpatches>`
   rules.
 - It or an equivalent fix must already exist in Linus' tree (upstream).

Procedure for submitting patches to the -stable tree
----------------------------------------------------

.. note::

   Security patches should not be handled (solely) by the -stable review
   process but should follow the procedures in
   :ref:`Documentation/admin-guide/security-bugs.rst <securitybugs>`.

For all other submissions, choose one of the following procedures
-----------------------------------------------------------------

.. _option_1:

Option 1
********

To have the patch automatically included in the stable tree, add the tag

.. code-block:: none

     Cc: stable@vger.kernel.org

in the sign-off area. Once the patch is merged it will be applied to
the stable tree without anything else needing to be done by the author
or subsystem maintainer.

.. _option_2:

Option 2
********

After the patch has been merged to Linus' tree, send an email to
stable@vger.kernel.org containing the subject of the patch, the commit ID,
why you think it should be applied, and what kernel version you wish it to
be applied to.

.. _option_3:

Option 3
********

Send the patch, after verifying that it follows the above rules, to
stable@vger.kernel.org.  You must note the upstream commit ID in the
changelog of your submission, as well as the kernel version you wish
it to be applied to.

:ref:`option_1` is **strongly** preferred, is the easiest and most common.
:ref:`option_2` and :ref:`option_3` are more useful if the patch isn't deemed
worthy at the time it is applied to a public git tree (for instance, because
it deserves more regression testing first).  :ref:`option_3` is especially
useful if the original upstream patch needs to be backported (for example
the backport needs some special handling due to e.g. API changes).

Note that for :ref:`option_3`, if the patch deviates from the original
upstream patch (for example because it had to be backported) this must be very
clearly documented and justified in the patch description.

The upstream commit ID must be specified with a separate line above the commit
text, like this:

.. code-block:: none

    commit <sha1> upstream.

or alternatively:

.. code-block:: none

    [ Upstream commit <sha1> ]

Additionally, some patches submitted via :ref:`option_1` may have additional
patch prerequisites which can be cherry-picked. This can be specified in the
following format in the sign-off area:

.. code-block:: none

     Cc: <stable@vger.kernel.org> # 3.3.x: a1f84a3: sched: Check for idle
     Cc: <stable@vger.kernel.org> # 3.3.x: 1b9508f: sched: Rate-limit newidle
     Cc: <stable@vger.kernel.org> # 3.3.x: fd21073: sched: Fix affinity logic
     Cc: <stable@vger.kernel.org> # 3.3.x
     Signed-off-by: Ingo Molnar <mingo@elte.hu>

The tag sequence has the meaning of:

.. code-block:: none

     git cherry-pick a1f84a3
     git cherry-pick 1b9508f
     git cherry-pick fd21073
     git cherry-pick <this commit>

Also, some patches may have kernel version prerequisites.  This can be
specified in the following format in the sign-off area:

.. code-block:: none

     Cc: <stable@vger.kernel.org> # 3.3.x

The tag has the meaning of:

.. code-block:: none

     git cherry-pick <this commit>

For each "-stable" tree starting with the specified version.

Following the submission:

 - The sender will receive an ACK when the patch has been accepted into the
   queue, or a NAK if the patch is rejected.  This response might take a few
   days, according to the developer's schedules.
 - If accepted, the patch will be added to the -stable queue, for review by
   other developers and by the relevant subsystem maintainer.

Review cycle
------------

 - When the -stable maintainers decide for a review cycle, the patches will be
   sent to the review committee, and the maintainer of the affected area of
   the patch (unless the submitter is the maintainer of the area) and CC: to
   the linux-kernel mailing list.
 - The review committee has 48 hours in which to ACK or NAK the patch.
 - If the patch is rejected by a member of the committee, or linux-kernel
   members object to the patch, bringing up issues that the maintainers and
   members did not realize, the patch will be dropped from the queue.
 - The ACKed patches will be posted again as part of release candidate (-rc)
   to be tested by developers and testers.
 - Usually only one -rc release is made, however if there are any outstanding
   issues, some patches may be modified or dropped or additional patches may
   be queued. Additional -rc releases are then released and tested until no
   issues are found.
 - Responding to the -rc releases can be done on the mailing list by sending
   a "Tested-by:" email with any testing information desired. The "Tested-by:"
   tags will be collected and added to the release commit.
 - At the end of the review cycle, the new -stable release will be released
   containing all the queued and tested patches.
 - Security patches will be accepted into the -stable tree directly from the
   security kernel team, and not go through the normal review cycle.
   Contact the kernel security team for more details on this procedure.

Trees
-----

 - The queues of patches, for both completed versions and in progress
   versions can be found at:

	https://git.kernel.org/pub/scm/linux/kernel/git/stable/stable-queue.git

 - The finalized and tagged releases of all stable kernels can be found
   in separate branches per version at:

	https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git

 - The release candidate of all stable kernel versions can be found at:

        https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable-rc.git/

   .. warning::
      The -stable-rc tree is a snapshot in time of the stable-queue tree and
      will change frequently, hence will be rebased often. It should only be
      used for testing purposes (e.g. to be consumed by CI systems).

Review committee
----------------

 - This is made up of a number of kernel developers who have volunteered for
   this task, and a few that haven't.


code:
.. _submitchecklist:

Linux Kernel patch submission checklist
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Here are some basic things that developers should do if they want to see their
kernel patch submissions accepted more quickly.

These are all above and beyond the documentation that is provided in
:ref:`Documentation/process/submitting-patches.rst <submittingpatches>`
and elsewhere regarding submitting Linux kernel patches.

1) If you use a facility then #include the file that defines/declares
   that facility.  Don't depend on other header files pulling in ones
   that you use.

2) Builds cleanly:

  a) with applicable or modified ``CONFIG`` options ``=y``, ``=m``, and
     ``=n``.  No ``gcc`` warnings/errors, no linker warnings/errors.

  b) Passes ``allnoconfig``, ``allmodconfig``

  c) Builds successfully when using ``O=builddir``

  d) Any Documentation/ changes build successfully without new warnings/errors.
     Use ``make htmldocs`` or ``make pdfdocs`` to check the build and
     fix any issues.

3) Builds on multiple CPU architectures by using local cross-compile tools
   or some other build farm.

4) ppc64 is a good architecture for cross-compilation checking because it
   tends to use ``unsigned long`` for 64-bit quantities.

5) Check your patch for general style as detailed in
   :ref:`Documentation/process/coding-style.rst <codingstyle>`.
   Check for trivial violations with the patch style checker prior to
   submission (``scripts/checkpatch.pl``).
   You should be able to justify all violations that remain in
   your patch.

6) Any new or modified ``CONFIG`` options do not muck up the config menu and
   default to off unless they meet the exception criteria documented in
   ``Documentation/kbuild/kconfig-language.rst`` Menu attributes: default value.

7) All new ``Kconfig`` options have help text.

8) Has been carefully reviewed with respect to relevant ``Kconfig``
   combinations.  This is very hard to get right with testing -- brainpower
   pays off here.

9) Check cleanly with sparse.

10) Use ``make checkstack`` and fix any problems that it finds.

    .. note::

       ``checkstack`` does not point out problems explicitly,
       but any one function that uses more than 512 bytes on the stack is a
       candidate for change.

11) Include :ref:`kernel-doc <kernel_doc>` to document global  kernel APIs.
    (Not required for static functions, but OK there also.) Use
    ``make htmldocs`` or ``make pdfdocs`` to check the
    :ref:`kernel-doc <kernel_doc>` and fix any issues.

12) Has been tested with ``CONFIG_PREEMPT``, ``CONFIG_DEBUG_PREEMPT``,
    ``CONFIG_DEBUG_SLAB``, ``CONFIG_DEBUG_PAGEALLOC``, ``CONFIG_DEBUG_MUTEXES``,
    ``CONFIG_DEBUG_SPINLOCK``, ``CONFIG_DEBUG_ATOMIC_SLEEP``,
    ``CONFIG_PROVE_RCU`` and ``CONFIG_DEBUG_OBJECTS_RCU_HEAD`` all
    simultaneously enabled.

13) Has been build- and runtime tested with and without ``CONFIG_SMP`` and
    ``CONFIG_PREEMPT.``

14) All codepaths have been exercised with all lockdep features enabled.

15) All new ``/proc`` entries are documented under ``Documentation/``

16) All new kernel boot parameters are documented in
    ``Documentation/admin-guide/kernel-parameters.rst``.

17) All new module parameters are documented with ``MODULE_PARM_DESC()``

18) All new userspace interfaces are documented in ``Documentation/ABI/``.
    See ``Documentation/ABI/README`` for more information.
    Patches that change userspace interfaces should be CCed to
    linux-api@vger.kernel.org.

19) Has been checked with injection of at least slab and page-allocation
    failures.  See ``Documentation/fault-injection/``.

    If the new code is substantial, addition of subsystem-specific fault
    injection might be appropriate.

20) Newly-added code has been compiled with ``gcc -W`` (use
    ``make KCFLAGS=-W``).  This will generate lots of noise, but is good
    for finding bugs like "warning: comparison between signed and unsigned".

21) Tested after it has been merged into the -mm patchset to make sure
    that it still works with all of the other queued patches and various
    changes in the VM, VFS, and other subsystems.

22) All memory barriers {e.g., ``barrier()``, ``rmb()``, ``wmb()``} need a
    comment in the source code that explains the logic of what they are doing
    and why.

23) If any ioctl's are added by the patch, then also update
    ``Documentation/userspace-api/ioctl/ioctl-number.rst``.

24) If your modified source code depends on or uses any of the kernel
    APIs or features that are related to the following ``Kconfig`` symbols,
    then test multiple builds with the related ``Kconfig`` symbols disabled
    and/or ``=m`` (if that option is available) [not all of these at the
    same time, just various/random combinations of them]:

    ``CONFIG_SMP``, ``CONFIG_SYSFS``, ``CONFIG_PROC_FS``, ``CONFIG_INPUT``, ``CONFIG_PCI``, ``CONFIG_BLOCK``, ``CONFIG_PM``, ``CONFIG_MAGIC_SYSRQ``,
    ``CONFIG_NET``, ``CONFIG_INET=n`` (but latter with ``CONFIG_NET=y``).


code:
.. _submittingpatches:

Submitting patches: the essential guide to getting your code into the kernel
============================================================================

For a person or company who wishes to submit a change to the Linux
kernel, the process can sometimes be daunting if you're not familiar
with "the system."  This text is a collection of suggestions which
can greatly increase the chances of your change being accepted.

This document contains a large number of suggestions in a relatively terse
format.  For detailed information on how the kernel development process
works, see Documentation/process/development-process.rst. Also, read
Documentation/process/submit-checklist.rst
for a list of items to check before submitting code.
For device tree binding patches, read
Documentation/devicetree/bindings/submitting-patches.rst.

This documentation assumes that you're using ``git`` to prepare your patches.
If you're unfamiliar with ``git``, you would be well-advised to learn how to
use it, it will make your life as a kernel developer and in general much
easier.

Some subsystems and maintainer trees have additional information about
their workflow and expectations, see
:ref:`Documentation/process/maintainer-handbooks.rst <maintainer_handbooks_main>`.

Obtain a current source tree
----------------------------

If you do not have a repository with the current kernel source handy, use
``git`` to obtain one.  You'll want to start with the mainline repository,
which can be grabbed with::

  git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git

Note, however, that you may not want to develop against the mainline tree
directly.  Most subsystem maintainers run their own trees and want to see
patches prepared against those trees.  See the **T:** entry for the subsystem
in the MAINTAINERS file to find that tree, or simply ask the maintainer if
the tree is not listed there.

.. _describe_changes:

Describe your changes
---------------------

Describe your problem.  Whether your patch is a one-line bug fix or
5000 lines of a new feature, there must be an underlying problem that
motivated you to do this work.  Convince the reviewer that there is a
problem worth fixing and that it makes sense for them to read past the
first paragraph.

Describe user-visible impact.  Straight up crashes and lockups are
pretty convincing, but not all bugs are that blatant.  Even if the
problem was spotted during code review, describe the impact you think
it can have on users.  Keep in mind that the majority of Linux
installations run kernels from secondary stable trees or
vendor/product-specific trees that cherry-pick only specific patches
from upstream, so include anything that could help route your change
downstream: provoking circumstances, excerpts from dmesg, crash
descriptions, performance regressions, latency spikes, lockups, etc.

Quantify optimizations and trade-offs.  If you claim improvements in
performance, memory consumption, stack footprint, or binary size,
include numbers that back them up.  But also describe non-obvious
costs.  Optimizations usually aren't free but trade-offs between CPU,
memory, and readability; or, when it comes to heuristics, between
different workloads.  Describe the expected downsides of your
optimization so that the reviewer can weigh costs against benefits.

Once the problem is established, describe what you are actually doing
about it in technical detail.  It's important to describe the change
in plain English for the reviewer to verify that the code is behaving
as you intend it to.

The maintainer will thank you if you write your patch description in a
form which can be easily pulled into Linux's source code management
system, ``git``, as a "commit log".  See :ref:`the_canonical_patch_format`.

Solve only one problem per patch.  If your description starts to get
long, that's a sign that you probably need to split up your patch.
See :ref:`split_changes`.

When you submit or resubmit a patch or patch series, include the
complete patch description and justification for it.  Don't just
say that this is version N of the patch (series).  Don't expect the
subsystem maintainer to refer back to earlier patch versions or referenced
URLs to find the patch description and put that into the patch.
I.e., the patch (series) and its description should be self-contained.
This benefits both the maintainers and reviewers.  Some reviewers
probably didn't even receive earlier versions of the patch.

Describe your changes in imperative mood, e.g. "make xyzzy do frotz"
instead of "[This patch] makes xyzzy do frotz" or "[I] changed xyzzy
to do frotz", as if you are giving orders to the codebase to change
its behaviour.

If you want to refer to a specific commit, don't just refer to the
SHA-1 ID of the commit. Please also include the oneline summary of
the commit, to make it easier for reviewers to know what it is about.
Example::

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

You should also be sure to use at least the first twelve characters of the
SHA-1 ID.  The kernel repository holds a *lot* of objects, making
collisions with shorter IDs a real possibility.  Bear in mind that, even if
there is no collision with your six-character ID now, that condition may
change five years from now.

If related discussions or any other background information behind the change
can be found on the web, add 'Link:' tags pointing to it. In case your patch
fixes a bug, for example, add a tag with a URL referencing the report in the
mailing list archives or a bug tracker; if the patch is a result of some
earlier mailing list discussion or something documented on the web, point to
it.

When linking to mailing list archives, preferably use the lore.kernel.org
message archiver service. To create the link URL, use the contents of the
``Message-Id`` header of the message without the surrounding angle brackets.
For example::

    Link: https://lore.kernel.org/r/30th.anniversary.repost@klaava.Helsinki.FI/

Please check the link to make sure that it is actually working and points
to the relevant message.

However, try to make your explanation understandable without external
resources. In addition to giving a URL to a mailing list archive or bug,
summarize the relevant points of the discussion that led to the
patch as submitted.

If your patch fixes a bug in a specific commit, e.g. you found an issue using
``git bisect``, please use the 'Fixes:' tag with the first 12 characters of
the SHA-1 ID, and the one line summary.  Do not split the tag across multiple
lines, tags are exempt from the "wrap at 75 columns" rule in order to simplify
parsing scripts.  For example::

	Fixes: 54a4f0239f2e ("KVM: MMU: make kvm_mmu_zap_page() return the number of pages it actually freed")

The following ``git config`` settings can be used to add a pretty format for
outputting the above style in the ``git log`` or ``git show`` commands::

	[core]
		abbrev = 12
	[pretty]
		fixes = Fixes: %h (\"%s\")

An example call::

	$ git log -1 --pretty=fixes 54a4f0239f2e
	Fixes: 54a4f0239f2e ("KVM: MMU: make kvm_mmu_zap_page() return the number of pages it actually freed")

.. _split_changes:

Separate your changes
---------------------

Separate each **logical change** into a separate patch.

For example, if your changes include both bug fixes and performance
enhancements for a single driver, separate those changes into two
or more patches.  If your changes include an API update, and a new
driver which uses that new API, separate those into two patches.

On the other hand, if you make a single change to numerous files,
group those changes into a single patch.  Thus a single logical change
is contained within a single patch.

The point to remember is that each patch should make an easily understood
change that can be verified by reviewers.  Each patch should be justifiable
on its own merits.

If one patch depends on another patch in order for a change to be
complete, that is OK.  Simply note **"this patch depends on patch X"**
in your patch description.

When dividing your change into a series of patches, take special care to
ensure that the kernel builds and runs properly after each patch in the
series.  Developers using ``git bisect`` to track down a problem can end up
splitting your patch series at any point; they will not thank you if you
introduce bugs in the middle.

If you cannot condense your patch set into a smaller set of patches,
then only post say 15 or so at a time and wait for review and integration.

Style-check your changes
------------------------

Check your patch for basic style violations, details of which can be
found in Documentation/process/coding-style.rst.
Failure to do so simply wastes
the reviewers time and will get your patch rejected, probably
without even being read.

One significant exception is when moving code from one file to
another -- in this case you should not modify the moved code at all in
the same patch which moves it.  This clearly delineates the act of
moving the code and your changes.  This greatly aids review of the
actual differences and allows tools to better track the history of
the code itself.

Check your patches with the patch style checker prior to submission
(scripts/checkpatch.pl).  Note, though, that the style checker should be
viewed as a guide, not as a replacement for human judgment.  If your code
looks better with a violation then its probably best left alone.

The checker reports at three levels:
 - ERROR: things that are very likely to be wrong
 - WARNING: things requiring careful review
 - CHECK: things requiring thought

You should be able to justify all violations that remain in your
patch.

Select the recipients for your patch
------------------------------------

You should always copy the appropriate subsystem maintainer(s) on any patch
to code that they maintain; look through the MAINTAINERS file and the
source code revision history to see who those maintainers are.  The
script scripts/get_maintainer.pl can be very useful at this step (pass paths to
your patches as arguments to scripts/get_maintainer.pl).  If you cannot find a
maintainer for the subsystem you are working on, Andrew Morton
(akpm@linux-foundation.org) serves as a maintainer of last resort.

You should also normally choose at least one mailing list to receive a copy
of your patch set.  linux-kernel@vger.kernel.org should be used by default
for all patches, but the volume on that list has caused a number of
developers to tune it out.  Look in the MAINTAINERS file for a
subsystem-specific list; your patch will probably get more attention there.
Please do not spam unrelated lists, though.

Many kernel-related lists are hosted on vger.kernel.org; you can find a
list of them at http://vger.kernel.org/vger-lists.html.  There are
kernel-related lists hosted elsewhere as well, though.

Do not send more than 15 patches at once to the vger mailing lists!!!

Linus Torvalds is the final arbiter of all changes accepted into the
Linux kernel.  His e-mail address is <torvalds@linux-foundation.org>.
He gets a lot of e-mail, and, at this point, very few patches go through
Linus directly, so typically you should do your best to -avoid-
sending him e-mail.

If you have a patch that fixes an exploitable security bug, send that patch
to security@kernel.org.  For severe bugs, a short embargo may be considered
to allow distributors to get the patch out to users; in such cases,
obviously, the patch should not be sent to any public lists. See also
Documentation/admin-guide/security-bugs.rst.

Patches that fix a severe bug in a released kernel should be directed
toward the stable maintainers by putting a line like this::

  Cc: stable@vger.kernel.org

into the sign-off area of your patch (note, NOT an email recipient).  You
should also read Documentation/process/stable-kernel-rules.rst
in addition to this document.

If changes affect userland-kernel interfaces, please send the MAN-PAGES
maintainer (as listed in the MAINTAINERS file) a man-pages patch, or at
least a notification of the change, so that some information makes its way
into the manual pages.  User-space API changes should also be copied to
linux-api@vger.kernel.org.

No MIME, no links, no compression, no attachments.  Just plain text
-------------------------------------------------------------------

Linus and other kernel developers need to be able to read and comment
on the changes you are submitting.  It is important for a kernel
developer to be able to "quote" your changes, using standard e-mail
tools, so that they may comment on specific portions of your code.

For this reason, all patches should be submitted by e-mail "inline". The
easiest way to do this is with ``git send-email``, which is strongly
recommended.  An interactive tutorial for ``git send-email`` is available at
https://git-send-email.io.

If you choose not to use ``git send-email``:

.. warning::

  Be wary of your editor's word-wrap corrupting your patch,
  if you choose to cut-n-paste your patch.

Do not attach the patch as a MIME attachment, compressed or not.
Many popular e-mail applications will not always transmit a MIME
attachment as plain text, making it impossible to comment on your
code.  A MIME attachment also takes Linus a bit more time to process,
decreasing the likelihood of your MIME-attached change being accepted.

Exception:  If your mailer is mangling patches then someone may ask
you to re-send them using MIME.

See Documentation/process/email-clients.rst for hints about configuring
your e-mail client so that it sends your patches untouched.

Respond to review comments
--------------------------

Your patch will almost certainly get comments from reviewers on ways in
which the patch can be improved, in the form of a reply to your email. You must
respond to those comments; ignoring reviewers is a good way to get ignored in
return. You can simply reply to their emails to answer their comments. Review
comments or questions that do not lead to a code change should almost certainly
bring about a comment or changelog entry so that the next reviewer better
understands what is going on.

Be sure to tell the reviewers what changes you are making and to thank them
for their time.  Code review is a tiring and time-consuming process, and
reviewers sometimes get grumpy.  Even in that case, though, respond
politely and address the problems they have pointed out.  When sending a next
version, add a ``patch changelog`` to the cover letter or to individual patches
explaining difference aganst previous submission (see
:ref:`the_canonical_patch_format`).

See Documentation/process/email-clients.rst for recommendations on email
clients and mailing list etiquette.

.. _resend_reminders:

Don't get discouraged - or impatient
------------------------------------

After you have submitted your change, be patient and wait.  Reviewers are
busy people and may not get to your patch right away.

Once upon a time, patches used to disappear into the void without comment,
but the development process works more smoothly than that now.  You should
receive comments within a week or so; if that does not happen, make sure
that you have sent your patches to the right place.  Wait for a minimum of
one week before resubmitting or pinging reviewers - possibly longer during
busy times like merge windows.

It's also ok to resend the patch or the patch series after a couple of
weeks with the word "RESEND" added to the subject line::

   [PATCH Vx RESEND] sub/sys: Condensed patch summary

Don't add "RESEND" when you are submitting a modified version of your
patch or patch series - "RESEND" only applies to resubmission of a
patch or patch series which have not been modified in any way from the
previous submission.

Include PATCH in the subject
-----------------------------

Due to high e-mail traffic to Linus, and to linux-kernel, it is common
convention to prefix your subject line with [PATCH].  This lets Linus
and other kernel developers more easily distinguish patches from other
e-mail discussions.

``git send-email`` will do this for you automatically.

Sign your work - the Developer's Certificate of Origin
------------------------------------------------------

To improve tracking of who did what, especially with patches that can
percolate to their final resting place in the kernel through several
layers of maintainers, we've introduced a "sign-off" procedure on
patches that are being emailed around.

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.  The rules are pretty simple: if you
can certify the below:

Developer's Certificate of Origin 1.1
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

By making a contribution to this project, I certify that:

        (a) The contribution was created in whole or in part by me and I
            have the right to submit it under the open source license
            indicated in the file; or

        (b) The contribution is based upon previous work that, to the best
            of my knowledge, is covered under an appropriate open source
            license and I have the right under that license to submit that
            work with modifications, whether created in whole or in part
            by me, under the same open source license (unless I am
            permitted to submit under a different license), as indicated
            in the file; or

        (c) The contribution was provided directly to me by some other
            person who certified (a), (b) or (c) and I have not modified
            it.

        (d) I understand and agree that this project and the contribution
            are public and that a record of the contribution (including all
            personal information I submit with it, including my sign-off) is
            maintained indefinitely and may be redistributed consistent with
            this project or the open source license(s) involved.

then you just add a line saying::

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

using your real name (sorry, no pseudonyms or anonymous contributions.)
This will be done for you automatically if you use ``git commit -s``.
Reverts should also include "Signed-off-by". ``git revert -s`` does that
for you.

Some people also put extra tags at the end.  They'll just be ignored for
now, but you can do this to mark internal company procedures or just
point out some special detail about the sign-off.

Any further SoBs (Signed-off-by:'s) following the author's SoB are from
people handling and transporting the patch, but were not involved in its
development. SoB chains should reflect the **real** route a patch took
as it was propagated to the maintainers and ultimately to Linus, with
the first SoB entry signalling primary authorship of a single author.

When to use Acked-by:, Cc:, and Co-developed-by:
------------------------------------------------

The Signed-off-by: tag indicates that the signer was involved in the
development of the patch, or that he/she was in the patch's delivery path.

If a person was not directly involved in the preparation or handling of a
patch but wishes to signify and record their approval of it then they can
ask to have an Acked-by: line added to the patch's changelog.

Acked-by: is often used by the maintainer of the affected code when that
maintainer neither contributed to nor forwarded the patch.

Acked-by: is not as formal as Signed-off-by:.  It is a record that the acker
has at least reviewed the patch and has indicated acceptance.  Hence patch
mergers will sometimes manually convert an acker's "yep, looks good to me"
into an Acked-by: (but note that it is usually better to ask for an
explicit ack).

Acked-by: does not necessarily indicate acknowledgement of the entire patch.
For example, if a patch affects multiple subsystems and has an Acked-by: from
one subsystem maintainer then this usually indicates acknowledgement of just
the part which affects that maintainer's code.  Judgement should be used here.
When in doubt people should refer to the original discussion in the mailing
list archives.

If a person has had the opportunity to comment on a patch, but has not
provided such comments, you may optionally add a ``Cc:`` tag to the patch.
This is the only tag which might be added without an explicit action by the
person it names - but it should indicate that this person was copied on the
patch.  This tag documents that potentially interested parties
have been included in the discussion.

Co-developed-by: states that the patch was co-created by multiple developers;
it is used to give attribution to co-authors (in addition to the author
attributed by the From: tag) when several people work on a single patch.  Since
Co-developed-by: denotes authorship, every Co-developed-by: must be immediately
followed by a Signed-off-by: of the associated co-author.  Standard sign-off
procedure applies, i.e. the ordering of Signed-off-by: tags should reflect the
chronological history of the patch insofar as possible, regardless of whether
the author is attributed via From: or Co-developed-by:.  Notably, the last
Signed-off-by: must always be that of the developer submitting the patch.

Note, the From: tag is optional when the From: author is also the person (and
email) listed in the From: line of the email header.

Example of a patch submitted by the From: author::

	<changelog>

	Co-developed-by: First Co-Author <first@coauthor.example.org>
	Signed-off-by: First Co-Author <first@coauthor.example.org>
	Co-developed-by: Second Co-Author <second@coauthor.example.org>
	Signed-off-by: Second Co-Author <second@coauthor.example.org>
	Signed-off-by: From Author <from@author.example.org>

Example of a patch submitted by a Co-developed-by: author::

	From: From Author <from@author.example.org>

	<changelog>

	Co-developed-by: Random Co-Author <random@coauthor.example.org>
	Signed-off-by: Random Co-Author <random@coauthor.example.org>
	Signed-off-by: From Author <from@author.example.org>
	Co-developed-by: Submitting Co-Author <sub@coauthor.example.org>
	Signed-off-by: Submitting Co-Author <sub@coauthor.example.org>

Using Reported-by:, Tested-by:, Reviewed-by:, Suggested-by: and Fixes:
----------------------------------------------------------------------

The Reported-by tag gives credit to people who find bugs and report them and it
hopefully inspires them to help us again in the future.  Please note that if
the bug was reported in private, then ask for permission first before using the
Reported-by tag. The tag is intended for bugs; please do not use it to credit
feature requests.

A Tested-by: tag indicates that the patch has been successfully tested (in
some environment) by the person named.  This tag informs maintainers that
some testing has been performed, provides a means to locate testers for
future patches, and ensures credit for the testers.

Reviewed-by:, instead, indicates that the patch has been reviewed and found
acceptable according to the Reviewer's Statement:

Reviewer's statement of oversight
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

By offering my Reviewed-by: tag, I state that:

	 (a) I have carried out a technical review of this patch to
	     evaluate its appropriateness and readiness for inclusion into
	     the mainline kernel.

	 (b) Any problems, concerns, or questions relating to the patch
	     have been communicated back to the submitter.  I am satisfied
	     with the submitter's response to my comments.

	 (c) While there may be things that could be improved with this
	     submission, I believe that it is, at this time, (1) a
	     worthwhile modification to the kernel, and (2) free of known
	     issues which would argue against its inclusion.

	 (d) While I have reviewed the patch and believe it to be sound, I
	     do not (unless explicitly stated elsewhere) make any
	     warranties or guarantees that it will achieve its stated
	     purpose or function properly in any given situation.

A Reviewed-by tag is a statement of opinion that the patch is an
appropriate modification of the kernel without any remaining serious
technical issues.  Any interested reviewer (who has done the work) can
offer a Reviewed-by tag for a patch.  This tag serves to give credit to
reviewers and to inform maintainers of the degree of review which has been
done on the patch.  Reviewed-by: tags, when supplied by reviewers known to
understand the subject area and to perform thorough reviews, will normally
increase the likelihood of your patch getting into the kernel.

Both Tested-by and Reviewed-by tags, once received on mailing list from tester
or reviewer, should be added by author to the applicable patches when sending
next versions.  However if the patch has changed substantially in following
version, these tags might not be applicable anymore and thus should be removed.
Usually removal of someone's Tested-by or Reviewed-by tags should be mentioned
in the patch changelog (after the '---' separator).

A Suggested-by: tag indicates that the patch idea is suggested by the person
named and ensures credit to the person for the idea. Please note that this
tag should not be added without the reporter's permission, especially if the
idea was not posted in a public forum. That said, if we diligently credit our
idea reporters, they will, hopefully, be inspired to help us again in the
future.

A Fixes: tag indicates that the patch fixes an issue in a previous commit. It
is used to make it easy to determine where a bug originated, which can help
review a bug fix. This tag also assists the stable kernel team in determining
which stable kernel versions should receive your fix. This is the preferred
method for indicating a bug fixed by the patch. See :ref:`describe_changes`
for more details.

Note: Attaching a Fixes: tag does not subvert the stable kernel rules
process nor the requirement to Cc: stable@vger.kernel.org on all stable
patch candidates. For more information, please read
Documentation/process/stable-kernel-rules.rst.

.. _the_canonical_patch_format:

The canonical patch format
--------------------------

This section describes how the patch itself should be formatted.  Note
that, if you have your patches stored in a ``git`` repository, proper patch
formatting can be had with ``git format-patch``.  The tools cannot create
the necessary text, though, so read the instructions below anyway.

The canonical patch subject line is::

    Subject: [PATCH 001/123] subsystem: summary phrase

The canonical patch message body contains the following:

  - A ``from`` line specifying the patch author, followed by an empty
    line (only needed if the person sending the patch is not the author).

  - The body of the explanation, line wrapped at 75 columns, which will
    be copied to the permanent changelog to describe this patch.

  - An empty line.

  - The ``Signed-off-by:`` lines, described above, which will
    also go in the changelog.

  - A marker line containing simply ``---``.

  - Any additional comments not suitable for the changelog.

  - The actual patch (``diff`` output).

The Subject line format makes it very easy to sort the emails
alphabetically by subject line - pretty much any email reader will
support that - since because the sequence number is zero-padded,
the numerical and alphabetic sort is the same.

The ``subsystem`` in the email's Subject should identify which
area or subsystem of the kernel is being patched.

The ``summary phrase`` in the email's Subject should concisely
describe the patch which that email contains.  The ``summary
phrase`` should not be a filename.  Do not use the same ``summary
phrase`` for every patch in a whole patch series (where a ``patch
series`` is an ordered sequence of multiple, related patches).

Bear in mind that the ``summary phrase`` of your email becomes a
globally-unique identifier for that patch.  It propagates all the way
into the ``git`` changelog.  The ``summary phrase`` may later be used in
developer discussions which refer to the patch.  People will want to
google for the ``summary phrase`` to read discussion regarding that
patch.  It will also be the only thing that people may quickly see
when, two or three months later, they are going through perhaps
thousands of patches using tools such as ``gitk`` or ``git log
--oneline``.

For these reasons, the ``summary`` must be no more than 70-75
characters, and it must describe both what the patch changes, as well
as why the patch might be necessary.  It is challenging to be both
succinct and descriptive, but that is what a well-written summary
should do.

The ``summary phrase`` may be prefixed by tags enclosed in square
brackets: "Subject: [PATCH <tag>...] <summary phrase>".  The tags are
not considered part of the summary phrase, but describe how the patch
should be treated.  Common tags might include a version descriptor if
the multiple versions of the patch have been sent out in response to
comments (i.e., "v1, v2, v3"), or "RFC" to indicate a request for
comments.

If there are four patches in a patch series the individual patches may
be numbered like this: 1/4, 2/4, 3/4, 4/4. This assures that developers
understand the order in which the patches should be applied and that
they have reviewed or applied all of the patches in the patch series.

Here are some good example Subjects::

    Subject: [PATCH 2/5] ext2: improve scalability of bitmap searching
    Subject: [PATCH v2 01/27] x86: fix eflags tracking
    Subject: [PATCH v2] sub/sys: Condensed patch summary
    Subject: [PATCH v2 M/N] sub/sys: Condensed patch summary

The ``from`` line must be the very first line in the message body,
and has the form:

        From: Patch Author <author@example.com>

The ``from`` line specifies who will be credited as the author of the
patch in the permanent changelog.  If the ``from`` line is missing,
then the ``From:`` line from the email header will be used to determine
the patch author in the changelog.

The explanation body will be committed to the permanent source
changelog, so should make sense to a competent reader who has long since
forgotten the immediate details of the discussion that might have led to
this patch. Including symptoms of the failure which the patch addresses
(kernel log messages, oops messages, etc.) are especially useful for
people who might be searching the commit logs looking for the applicable
patch. The text should be written in such detail so that when read
weeks, months or even years later, it can give the reader the needed
details to grasp the reasoning for **why** the patch was created.

If a patch fixes a compile failure, it may not be necessary to include
_all_ of the compile failures; just enough that it is likely that
someone searching for the patch can find it. As in the ``summary
phrase``, it is important to be both succinct as well as descriptive.

The ``---`` marker line serves the essential purpose of marking for
patch handling tools where the changelog message ends.

One good use for the additional comments after the ``---`` marker is
for a ``diffstat``, to show what files have changed, and the number of
inserted and deleted lines per file. A ``diffstat`` is especially useful
on bigger patches. If you are going to include a ``diffstat`` after the
``---`` marker, please use ``diffstat`` options ``-p 1 -w 70`` so that
filenames are listed from the top of the kernel source tree and don't
use too much horizontal space (easily fit in 80 columns, maybe with some
indentation). (``git`` generates appropriate diffstats by default.)

Other comments relevant only to the moment or the maintainer, not
suitable for the permanent changelog, should also go here. A good
example of such comments might be ``patch changelogs`` which describe
what has changed between the v1 and v2 version of the patch.

Please put this information **after** the ``---`` line which separates
the changelog from the rest of the patch. The version information is
not part of the changelog which gets committed to the git tree. It is
additional information for the reviewers. If it's placed above the
commit tags, it needs manual interaction to remove it. If it is below
the separator line, it gets automatically stripped off when applying the
patch::

  <commit message>
  ...
  Signed-off-by: Author <author@mail>
  ---
  V2 -> V3: Removed redundant helper function
  V1 -> V2: Cleaned up coding style and addressed review comments

  path/to/file | 5+++--
  ...

See more details on the proper patch format in the following
references.

.. _backtraces:

Backtraces in commit messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Backtraces help document the call chain leading to a problem. However,
not all backtraces are helpful. For example, early boot call chains are
unique and obvious. Copying the full dmesg output verbatim, however,
adds distracting information like timestamps, module lists, register and
stack dumps.

Therefore, the most useful backtraces should distill the relevant
information from the dump, which makes it easier to focus on the real
issue. Here is an example of a well-trimmed backtrace::

  unchecked MSR access error: WRMSR to 0xd51 (tried to write 0x0000000000000064)
  at rIP: 0xffffffffae059994 (native_write_msr+0x4/0x20)
  Call Trace:
  mba_wrmsr
  update_domains
  rdtgroup_mkdir

.. _explicit_in_reply_to:

Explicit In-Reply-To headers
----------------------------

It can be helpful to manually add In-Reply-To: headers to a patch
(e.g., when using ``git send-email``) to associate the patch with
previous relevant discussion, e.g. to link a bug fix to the email with
the bug report.  However, for a multi-patch series, it is generally
best to avoid using In-Reply-To: to link to older versions of the
series.  This way multiple versions of the patch don't become an
unmanageable forest of references in email clients.  If a link is
helpful, you can use the https://lore.kernel.org/ redirector (e.g., in
the cover email text) to link to an earlier version of the patch series.

Providing base tree information
-------------------------------

When other developers receive your patches and start the review process,
it is often useful for them to know where in the tree history they
should place your work. This is particularly useful for automated CI
processes that attempt to run a series of tests in order to establish
the quality of your submission before the maintainer starts the review.

If you are using ``git format-patch`` to generate your patches, you can
automatically include the base tree information in your submission by
using the ``--base`` flag. The easiest and most convenient way to use
this option is with topical branches::

    $ git checkout -t -b my-topical-branch master
    Branch 'my-topical-branch' set up to track local branch 'master'.
    Switched to a new branch 'my-topical-branch'

    [perform your edits and commits]

    $ git format-patch --base=auto --cover-letter -o outgoing/ master
    outgoing/0000-cover-letter.patch
    outgoing/0001-First-Commit.patch
    outgoing/...

When you open ``outgoing/0000-cover-letter.patch`` for editing, you will
notice that it will have the ``base-commit:`` trailer at the very
bottom, which provides the reviewer and the CI tools enough information
to properly perform ``git am`` without worrying about conflicts::

    $ git checkout -b patch-review [base-commit-id]
    Switched to a new branch 'patch-review'
    $ git am patches.mbox
    Applying: First Commit
    Applying: ...

Please see ``man git-format-patch`` for more information about this
option.

.. note::

    The ``--base`` feature was introduced in git version 2.9.0.

If you are not using git to format your patches, you can still include
the same ``base-commit`` trailer to indicate the commit hash of the tree
on which your work is based. You should add it either in the cover
letter or in the first patch of the series and it should be placed
either below the ``---`` line or at the very bottom of all other
content, right before your email signature.

References
----------

Andrew Morton, "The perfect patch" (tpp).
  <https://www.ozlabs.org/~akpm/stuff/tpp.txt>

Jeff Garzik, "Linux kernel patch submission format".
  <https://web.archive.org/web/20180829112450/http://linux.yyz.us/patch-format.html>

Greg Kroah-Hartman, "How to piss off a kernel subsystem maintainer".
  <http://www.kroah.com/log/linux/maintainer.html>

  <http://www.kroah.com/log/linux/maintainer-02.html>

  <http://www.kroah.com/log/linux/maintainer-03.html>

  <http://www.kroah.com/log/linux/maintainer-04.html>

  <http://www.kroah.com/log/linux/maintainer-05.html>

  <http://www.kroah.com/log/linux/maintainer-06.html>

NO!!!! No more huge patch bombs to linux-kernel@vger.kernel.org people!
  <https://lore.kernel.org/r/20050711.125305.08322243.davem@davemloft.net>

Kernel Documentation/process/coding-style.rst

Linus Torvalds's mail on the canonical patch format:
  <https://lore.kernel.org/r/Pine.LNX.4.58.0504071023190.28951@ppc970.osdl.org>

Andi Kleen, "On submitting kernel patches"
  Some strategies to get difficult or controversial changes in.

  http://halobates.de/on-submitting-patches.pdf


code:
.. _volatile_considered_harmful:

Why the "volatile" type class should not be used
------------------------------------------------

C programmers have often taken volatile to mean that the variable could be
changed outside of the current thread of execution; as a result, they are
sometimes tempted to use it in kernel code when shared data structures are
being used.  In other words, they have been known to treat volatile types
as a sort of easy atomic variable, which they are not.  The use of volatile in
kernel code is almost never correct; this document describes why.

The key point to understand with regard to volatile is that its purpose is
to suppress optimization, which is almost never what one really wants to
do.  In the kernel, one must protect shared data structures against
unwanted concurrent access, which is very much a different task.  The
process of protecting against unwanted concurrency will also avoid almost
all optimization-related problems in a more efficient way.

Like volatile, the kernel primitives which make concurrent access to data
safe (spinlocks, mutexes, memory barriers, etc.) are designed to prevent
unwanted optimization.  If they are being used properly, there will be no
need to use volatile as well.  If volatile is still necessary, there is
almost certainly a bug in the code somewhere.  In properly-written kernel
code, volatile can only serve to slow things down.

Consider a typical block of kernel code::

    spin_lock(&the_lock);
    do_something_on(&shared_data);
    do_something_else_with(&shared_data);
    spin_unlock(&the_lock);

If all the code follows the locking rules, the value of shared_data cannot
change unexpectedly while the_lock is held.  Any other code which might
want to play with that data will be waiting on the lock.  The spinlock
primitives act as memory barriers - they are explicitly written to do so -
meaning that data accesses will not be optimized across them.  So the
compiler might think it knows what will be in shared_data, but the
spin_lock() call, since it acts as a memory barrier, will force it to
forget anything it knows.  There will be no optimization problems with
accesses to that data.

If shared_data were declared volatile, the locking would still be
necessary.  But the compiler would also be prevented from optimizing access
to shared_data _within_ the critical section, when we know that nobody else
can be working with it.  While the lock is held, shared_data is not
volatile.  When dealing with shared data, proper locking makes volatile
unnecessary - and potentially harmful.

The volatile storage class was originally meant for memory-mapped I/O
registers.  Within the kernel, register accesses, too, should be protected
by locks, but one also does not want the compiler "optimizing" register
accesses within a critical section.  But, within the kernel, I/O memory
accesses are always done through accessor functions; accessing I/O memory
directly through pointers is frowned upon and does not work on all
architectures.  Those accessors are written to prevent unwanted
optimization, so, once again, volatile is unnecessary.

Another situation where one might be tempted to use volatile is
when the processor is busy-waiting on the value of a variable.  The right
way to perform a busy wait is::

    while (my_variable != what_i_want)
        cpu_relax();

The cpu_relax() call can lower CPU power consumption or yield to a
hyperthreaded twin processor; it also happens to serve as a compiler
barrier, so, once again, volatile is unnecessary.  Of course, busy-
waiting is generally an anti-social act to begin with.

There are still a few rare situations where volatile makes sense in the
kernel:

  - The above-mentioned accessor functions might use volatile on
    architectures where direct I/O memory access does work.  Essentially,
    each accessor call becomes a little critical section on its own and
    ensures that the access happens as expected by the programmer.

  - Inline assembly code which changes memory, but which has no other
    visible side effects, risks being deleted by GCC.  Adding the volatile
    keyword to asm statements will prevent this removal.

  - The jiffies variable is special in that it can have a different value
    every time it is referenced, but it can be read without any special
    locking.  So jiffies can be volatile, but the addition of other
    variables of this type is strongly frowned upon.  Jiffies is considered
    to be a "stupid legacy" issue (Linus's words) in this regard; fixing it
    would be more trouble than it is worth.

  - Pointers to data structures in coherent memory which might be modified
    by I/O devices can, sometimes, legitimately be volatile.  A ring buffer
    used by a network adapter, where that adapter changes pointers to
    indicate which descriptors have been processed, is an example of this
    type of situation.

For most code, none of the above justifications for volatile apply.  As a
result, the use of volatile is likely to be seen as a bug and will bring
additional scrutiny to the code.  Developers who are tempted to use
volatile should take a step back and think about what they are truly trying
to accomplish.

Patches to remove volatile variables are generally welcome - as long as
they come with a justification which shows that the concurrency issues have
been properly thought through.

References
==========

[1] https://lwn.net/Articles/233481/

[2] https://lwn.net/Articles/233482/

Credits
=======

Original impetus and research by Randy Dunlap

Written by Jonathan Corbet

Improvements via comments from Satyam Sharma, Johannes Stezenbach, Jesper
Juhl, Heikki Orsila, H. Peter Anvin, Philipp Hahn, and Stefan
Richter.


code:
=================================
Boot image header in RISC-V Linux
=================================

:Author: Atish Patra <atish.patra@wdc.com>
:Date:   20 May 2019

This document only describes the boot image header details for RISC-V Linux.

TODO:
  Write a complete booting guide.

The following 64-byte header is present in decompressed Linux kernel image::

	u32 code0;		  /* Executable code */
	u32 code1;		  /* Executable code */
	u64 text_offset;	  /* Image load offset, little endian */
	u64 image_size;		  /* Effective Image size, little endian */
	u64 flags;		  /* kernel flags, little endian */
	u32 version;		  /* Version of this header */
	u32 res1 = 0;		  /* Reserved */
	u64 res2 = 0;		  /* Reserved */
	u64 magic = 0x5643534952; /* Magic number, little endian, "RISCV" */
	u32 magic2 = 0x05435352;  /* Magic number 2, little endian, "RSC\x05" */
	u32 res3;		  /* Reserved for PE COFF offset */

This header format is compliant with PE/COFF header and largely inspired from
ARM64 header. Thus, both ARM64 & RISC-V header can be combined into one common
header in future.

Notes
=====

- This header can also be reused to support EFI stub for RISC-V in future. EFI
  specification needs PE/COFF image header in the beginning of the kernel image
  in order to load it as an EFI application. In order to support EFI stub,
  code0 should be replaced with "MZ" magic string and res3(at offset 0x3c) should
  point to the rest of the PE/COFF header.

- version field indicate header version number

	==========  =============
	Bits 0:15   Minor version
	Bits 16:31  Major version
	==========  =============

  This preserves compatibility across newer and older version of the header.
  The current version is defined as 0.2.

- The "magic" field is deprecated as of version 0.2.  In a future
  release, it may be removed.  This originally should have matched up
  with the ARM64 header "magic" field, but unfortunately does not.
  The "magic2" field replaces it, matching up with the ARM64 header.

- In current header, the flags field has only one field.

	=====  ====================================
	Bit 0  Kernel endianness. 1 if BE, 0 if LE.
	=====  ====================================

- Image size is mandatory for boot loader to load kernel image. Booting will
  fail otherwise.


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

.. kernel-feat:: $srctree/Documentation/features riscv


code:
===================
RISC-V architecture
===================

.. toctree::
    :maxdepth: 1

    boot-image-header
    vm-layout
    patch-acceptance
    uabi

    features

.. only::  subproject and html

   Indices
   =======

   * :ref:`genindex`


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

arch/riscv maintenance guidelines for developers
================================================

Overview
--------
The RISC-V instruction set architecture is developed in the open:
in-progress drafts are available for all to review and to experiment
with implementations.  New module or extension drafts can change
during the development process - sometimes in ways that are
incompatible with previous drafts.  This flexibility can present a
challenge for RISC-V Linux maintenance.  Linux maintainers disapprove
of churn, and the Linux development process prefers well-reviewed and
tested code over experimental code.  We wish to extend these same
principles to the RISC-V-related code that will be accepted for
inclusion in the kernel.

Submit Checklist Addendum
-------------------------
We'll only accept patches for new modules or extensions if the
specifications for those modules or extensions are listed as being
unlikely to be incompatibly changed in the future.  For
specifications from the RISC-V foundation this means "Frozen" or
"Ratified", for the UEFI forum specifications this means a published
ECR.  (Developers may, of course, maintain their own Linux kernel trees
that contain code for any draft extensions that they wish.)

Additionally, the RISC-V specification allows implementers to create
their own custom extensions.  These custom extensions aren't required
to go through any review or ratification process by the RISC-V
Foundation.  To avoid the maintenance complexity and potential
performance impact of adding kernel code for implementor-specific
RISC-V extensions, we'll only consider patches for extensions that either:

- Have been officially frozen or ratified by the RISC-V Foundation, or
- Have been implemented in hardware that is widely available, per standard
  Linux practice.

(Implementers, may, of course, maintain their own Linux kernel trees containing
code for any custom extensions that they wish.)


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

RISC-V Linux User ABI
=====================

Misaligned accesses are supported in userspace, but they may perform poorly.


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

Arch Support
============

Currently, the Rust compiler (``rustc``) uses LLVM for code generation,
which limits the supported architectures that can be targeted. In addition,
support for building the kernel with LLVM/Clang varies (please see
Documentation/kbuild/llvm.rst). This support is needed for ``bindgen``
which uses ``libclang``.

Below is a general summary of architectures that currently work. Level of
support corresponds to ``S`` values in the ``MAINTAINERS`` file.

============  ================  ==============================================
Architecture  Level of support  Constraints
============  ================  ==============================================
``x86``       Maintained        ``x86_64`` only.
============  ================  ==============================================


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

Coding Guidelines
=================

This document describes how to write Rust code in the kernel.

Style & formatting
------------------

The code should be formatted using ``rustfmt``. In this way, a person
contributing from time to time to the kernel does not need to learn and
remember one more style guide. More importantly, reviewers and maintainers
do not need to spend time pointing out style issues anymore, and thus
less patch roundtrips may be needed to land a change.

.. note:: Conventions on comments and documentation are not checked by
  ``rustfmt``. Thus those are still needed to be taken care of.

The default settings of ``rustfmt`` are used. This means the idiomatic Rust
style is followed. For instance, 4 spaces are used for indentation rather
than tabs.

It is convenient to instruct editors/IDEs to format while typing,
when saving or at commit time. However, if for some reason reformatting
the entire kernel Rust sources is needed at some point, the following can be
run::

	make LLVM=1 rustfmt

It is also possible to check if everything is formatted (printing a diff
otherwise), for instance for a CI, with::

	make LLVM=1 rustfmtcheck

Like ``clang-format`` for the rest of the kernel, ``rustfmt`` works on
individual files, and does not require a kernel configuration. Sometimes it may
even work with broken code.

Comments
--------

"Normal" comments (i.e. ``//``, rather than code documentation which starts
with ``///`` or ``//!``) are written in Markdown the same way as documentation
comments are, even though they will not be rendered. This improves consistency,
simplifies the rules and allows to move content between the two kinds of
comments more easily. For instance:

.. code-block:: rust

	// `object` is ready to be handled now.
	f(object);

Furthermore, just like documentation, comments are capitalized at the beginning
of a sentence and ended with a period (even if it is a single sentence). This
includes ``// SAFETY:``, ``// TODO:`` and other "tagged" comments, e.g.:

.. code-block:: rust

	// FIXME: The error should be handled properly.

Comments should not be used for documentation purposes: comments are intended
for implementation details, not users. This distinction is useful even if the
reader of the source file is both an implementor and a user of an API. In fact,
sometimes it is useful to use both comments and documentation at the same time.
For instance, for a ``TODO`` list or to comment on the documentation itself.
For the latter case, comments can be inserted in the middle; that is, closer to
the line of documentation to be commented. For any other case, comments are
written after the documentation, e.g.:

.. code-block:: rust

	/// Returns a new [`Foo`].
	///
	/// # Examples
	///
	// TODO: Find a better example.
	/// ```
	/// let foo = f(42);
	/// ```
	// FIXME: Use fallible approach.
	pub fn f(x: i32) -> Foo {
	    // ...
	}

One special kind of comments are the ``// SAFETY:`` comments. These must appear
before every ``unsafe`` block, and they explain why the code inside the block is
correct/sound, i.e. why it cannot trigger undefined behavior in any case, e.g.:

.. code-block:: rust

	// SAFETY: `p` is valid by the safety requirements.
	unsafe { *p = 0; }

``// SAFETY:`` comments are not to be confused with the ``# Safety`` sections
in code documentation. ``# Safety`` sections specify the contract that callers
(for functions) or implementors (for traits) need to abide by. ``// SAFETY:``
comments show why a call (for functions) or implementation (for traits) actually
respects the preconditions stated in a ``# Safety`` section or the language
reference.

Code documentation
------------------

Rust kernel code is not documented like C kernel code (i.e. via kernel-doc).
Instead, the usual system for documenting Rust code is used: the ``rustdoc``
tool, which uses Markdown (a lightweight markup language).

To learn Markdown, there are many guides available out there. For instance,
the one at:

	https://commonmark.org/help/

This is how a well-documented Rust function may look like:

.. code-block:: rust

	/// Returns the contained [`Some`] value, consuming the `self` value,
	/// without checking that the value is not [`None`].
	///
	/// # Safety
	///
	/// Calling this method on [`None`] is *[undefined behavior]*.
	///
	/// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
	///
	/// # Examples
	///
	/// ```
	/// let x = Some("air");
	/// assert_eq!(unsafe { x.unwrap_unchecked() }, "air");
	/// ```
	pub unsafe fn unwrap_unchecked(self) -> T {
	    match self {
	        Some(val) => val,

	        // SAFETY: The safety contract must be upheld by the caller.
	        None => unsafe { hint::unreachable_unchecked() },
	    }
	}

This example showcases a few ``rustdoc`` features and some conventions followed
in the kernel:

  - The first paragraph must be a single sentence briefly describing what
    the documented item does. Further explanations must go in extra paragraphs.

  - Unsafe functions must document their safety preconditions under
    a ``# Safety`` section.

  - While not shown here, if a function may panic, the conditions under which
    that happens must be described under a ``# Panics`` section.

    Please note that panicking should be very rare and used only with a good
    reason. In almost all cases, a fallible approach should be used, typically
    returning a ``Result``.

  - If providing examples of usage would help readers, they must be written in
    a section called ``# Examples``.

  - Rust items (functions, types, constants...) must be linked appropriately
    (``rustdoc`` will create a link automatically).

  - Any ``unsafe`` block must be preceded by a ``// SAFETY:`` comment
    describing why the code inside is sound.

    While sometimes the reason might look trivial and therefore unneeded,
    writing these comments is not just a good way of documenting what has been
    taken into account, but most importantly, it provides a way to know that
    there are no *extra* implicit constraints.

To learn more about how to write documentation for Rust and extra features,
please take a look at the ``rustdoc`` book at:

	https://doc.rust-lang.org/rustdoc/how-to-write-documentation.html

Naming
------

Rust kernel code follows the usual Rust naming conventions:

	https://rust-lang.github.io/api-guidelines/naming.html

When existing C concepts (e.g. macros, functions, objects...) are wrapped into
a Rust abstraction, a name as close as reasonably possible to the C side should
be used in order to avoid confusion and to improve readability when switching
back and forth between the C and Rust sides. For instance, macros such as
``pr_info`` from C are named the same in the Rust side.

Having said that, casing should be adjusted to follow the Rust naming
conventions, and namespacing introduced by modules and types should not be
repeated in the item names. For instance, when wrapping constants like:

.. code-block:: c

	#define GPIO_LINE_DIRECTION_IN	0
	#define GPIO_LINE_DIRECTION_OUT	1

The equivalent in Rust may look like (ignoring documentation):

.. code-block:: rust

	pub mod gpio {
	    pub enum LineDirection {
	        In = bindings::GPIO_LINE_DIRECTION_IN as _,
	        Out = bindings::GPIO_LINE_DIRECTION_OUT as _,
	    }
	}

That is, the equivalent of ``GPIO_LINE_DIRECTION_IN`` would be referred to as
``gpio::LineDirection::In``. In particular, it should not be named
``gpio::gpio_line_direction::GPIO_LINE_DIRECTION_IN``.


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

General Information
===================

This document contains useful information to know when working with
the Rust support in the kernel.

Code documentation
------------------

Rust kernel code is documented using ``rustdoc``, its built-in documentation
generator.

The generated HTML docs include integrated search, linked items (e.g. types,
functions, constants), source code, etc. They may be read at (TODO: link when
in mainline and generated alongside the rest of the documentation):

	http://kernel.org/

The docs can also be easily generated and read locally. This is quite fast
(same order as compiling the code itself) and no special tools or environment
are needed. This has the added advantage that they will be tailored to
the particular kernel configuration used. To generate them, use the ``rustdoc``
target with the same invocation used for compilation, e.g.::

	make LLVM=1 rustdoc

To read the docs locally in your web browser, run e.g.::

	xdg-open rust/doc/kernel/index.html

To learn about how to write the documentation, please see coding-guidelines.rst.

Extra lints
-----------

While ``rustc`` is a very helpful compiler, some extra lints and analyses are
available via ``clippy``, a Rust linter. To enable it, pass ``CLIPPY=1`` to
the same invocation used for compilation, e.g.::

	make LLVM=1 CLIPPY=1

Please note that Clippy may change code generation, thus it should not be
enabled while building a production kernel.

Abstractions vs. bindings
-------------------------

Abstractions are Rust code wrapping kernel functionality from the C side.

In order to use functions and types from the C side, bindings are created.
Bindings are the declarations for Rust of those functions and types from
the C side.

For instance, one may write a ``Mutex`` abstraction in Rust which wraps
a ``struct mutex`` from the C side and calls its functions through the bindings.

Abstractions are not available for all the kernel internal APIs and concepts,
but it is intended that coverage is expanded as time goes on. "Leaf" modules
(e.g. drivers) should not use the C bindings directly. Instead, subsystems
should provide as-safe-as-possible abstractions as needed.

Conditional compilation
-----------------------

Rust code has access to conditional compilation based on the kernel
configuration:

.. code-block:: rust

	#[cfg(CONFIG_X)]       // Enabled               (`y` or `m`)
	#[cfg(CONFIG_X="y")]   // Enabled as a built-in (`y`)
	#[cfg(CONFIG_X="m")]   // Enabled as a module   (`m`)
	#[cfg(not(CONFIG_X))]  // Disabled


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

Rust
====

Documentation related to Rust within the kernel. To start using Rust
in the kernel, please read the quick-start.rst guide.

.. toctree::
    :maxdepth: 1

    quick-start
    general-information
    coding-guidelines
    arch-support

.. only::  subproject and html

   Indices
   =======

   * :ref:`genindex`


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

Quick Start
===========

This document describes how to get started with kernel development in Rust.

Requirements: Building
----------------------

This section explains how to fetch the tools needed for building.

Some of these requirements might be available from Linux distributions
under names like ``rustc``, ``rust-src``, ``rust-bindgen``, etc. However,
at the time of writing, they are likely not to be recent enough unless
the distribution tracks the latest releases.

To easily check whether the requirements are met, the following target
can be used::

	make LLVM=1 rustavailable

This triggers the same logic used by Kconfig to determine whether
``RUST_IS_AVAILABLE`` should be enabled; but it also explains why not
if that is the case.

rustc
*****

A particular version of the Rust compiler is required. Newer versions may or
may not work because, for the moment, the kernel depends on some unstable
Rust features.

If ``rustup`` is being used, enter the checked out source code directory
and run::

	rustup override set $(scripts/min-tool-version.sh rustc)

Otherwise, fetch a standalone installer or install ``rustup`` from:

	https://www.rust-lang.org

Rust standard library source
****************************

The Rust standard library source is required because the build system will
cross-compile ``core`` and ``alloc``.

If ``rustup`` is being used, run::

	rustup component add rust-src

The components are installed per toolchain, thus upgrading the Rust compiler
version later on requires re-adding the component.

Otherwise, if a standalone installer is used, the Rust repository may be cloned
into the installation folder of the toolchain::

	git clone --recurse-submodules \
		--branch $(scripts/min-tool-version.sh rustc) \
		https://github.com/rust-lang/rust \
		$(rustc --print sysroot)/lib/rustlib/src/rust

In this case, upgrading the Rust compiler version later on requires manually
updating this clone.

libclang
********

``libclang`` (part of LLVM) is used by ``bindgen`` to understand the C code
in the kernel, which means LLVM needs to be installed; like when the kernel
is compiled with ``CC=clang`` or ``LLVM=1``.

Linux distributions are likely to have a suitable one available, so it is
best to check that first.

There are also some binaries for several systems and architectures uploaded at:

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

Otherwise, building LLVM takes quite a while, but it is not a complex process:

	https://llvm.org/docs/GettingStarted.html#getting-the-source-code-and-building-llvm

Please see Documentation/kbuild/llvm.rst for more information and further ways
to fetch pre-built releases and distribution packages.

bindgen
*******

The bindings to the C side of the kernel are generated at build time using
the ``bindgen`` tool. A particular version is required.

Install it via (note that this will download and build the tool from source)::

	cargo install --locked --version $(scripts/min-tool-version.sh bindgen) bindgen

Requirements: Developing
------------------------

This section explains how to fetch the tools needed for developing. That is,
they are not needed when just building the kernel.

rustfmt
*******

The ``rustfmt`` tool is used to automatically format all the Rust kernel code,
including the generated C bindings (for details, please see
coding-guidelines.rst).

If ``rustup`` is being used, its ``default`` profile already installs the tool,
thus nothing needs to be done. If another profile is being used, the component
can be installed manually::

	rustup component add rustfmt

The standalone installers also come with ``rustfmt``.

clippy
******

``clippy`` is a Rust linter. Running it provides extra warnings for Rust code.
It can be run by passing ``CLIPPY=1`` to ``make`` (for details, please see
general-information.rst).

If ``rustup`` is being used, its ``default`` profile already installs the tool,
thus nothing needs to be done. If another profile is being used, the component
can be installed manually::

	rustup component add clippy

The standalone installers also come with ``clippy``.

cargo
*****

``cargo`` is the Rust native build system. It is currently required to run
the tests since it is used to build a custom standard library that contains
the facilities provided by the custom ``alloc`` in the kernel. The tests can
be run using the ``rusttest`` Make target.

If ``rustup`` is being used, all the profiles already install the tool,
thus nothing needs to be done.

The standalone installers also come with ``cargo``.

rustdoc
*******

``rustdoc`` is the documentation tool for Rust. It generates pretty HTML
documentation for Rust code (for details, please see
general-information.rst).

``rustdoc`` is also used to test the examples provided in documented Rust code
(called doctests or documentation tests). The ``rusttest`` Make target uses
this feature.

If ``rustup`` is being used, all the profiles already install the tool,
thus nothing needs to be done.

The standalone installers also come with ``rustdoc``.

rust-analyzer
*************

The `rust-analyzer <https://rust-analyzer.github.io/>`_ language server can
be used with many editors to enable syntax highlighting, completion, go to
definition, and other features.

``rust-analyzer`` needs a configuration file, ``rust-project.json``, which
can be generated by the ``rust-analyzer`` Make target.

Configuration
-------------

``Rust support`` (``CONFIG_RUST``) needs to be enabled in the ``General setup``
menu. The option is only shown if a suitable Rust toolchain is found (see
above), as long as the other requirements are met. In turn, this will make
visible the rest of options that depend on Rust.

Afterwards, go to::

	Kernel hacking
	    -> Sample kernel code
	        -> Rust samples

And enable some sample modules either as built-in or as loadable.

Building
--------

Building a kernel with a complete LLVM toolchain is the best supported setup
at the moment. That is::

	make LLVM=1

For architectures that do not support a full LLVM toolchain, use::

	make CC=clang

Using GCC also works for some configurations, but it is very experimental at
the moment.

Hacking
-------

To dive deeper, take a look at the source code of the samples
at ``samples/rust/``, the Rust support code under ``rust/`` and
the ``Rust hacking`` menu under ``Kernel hacking``.

If GDB/Binutils is used and Rust symbols are not getting demangled, the reason
is the toolchain does not support Rust's new v0 mangling scheme yet.
There are a few ways out:

  - Install a newer release (GDB >= 10.2, Binutils >= 2.36).

  - Some versions of GDB (e.g. vanilla GDB 10.1) are able to use
    the pre-demangled names embedded in the debug info (``CONFIG_DEBUG_INFO``).


code:
ChangeLog for the UTS Global 3270-support patch

Sep 2002:	Get bootup colors right on 3270 console
	* In tubttybld.c, substantially revise ESC processing so that
	  ESC sequences (especially coloring ones) and the strings
	  they affect work as right as 3270 can get them.  Also, set
	  screen height to omit the two rows used for input area, in
	  tty3270_open() in tubtty.c.

Sep 2002:	Dynamically get 3270 input buffer
	* Oversize 3270 screen widths may exceed GEOM_MAXINPLEN columns,
	  so get input-area buffer dynamically when sizing the device in
	  tubmakemin() in tuball.c (if it's the console) or tty3270_open()
	  in tubtty.c (if needed).  Change tubp->tty_input to be a
	  pointer rather than an array, in tubio.h.

Sep 2002:	Fix tubfs kmalloc()s
	* Do read and write lengths correctly in fs3270_read()
	  and fs3270_write(), while never asking kmalloc()
	  for more than 0x800 bytes.  Affects tubfs.c and tubio.h.

Sep 2002:	Recognize 3270 control unit type 3174
	* Recognize control-unit type 0x3174 as well as 0x327?.
	  The IBM 2047 device emulates a 3174 control unit.
	  Modularize control-unit recognition in tuball.c by
	  adding and invoking new tub3270_is_ours().

Apr 2002:	Fix 3270 console reboot loop
	* (Belated log entry) Fixed reboot loop if 3270 console,
	  in tubtty.c:ttu3270_bh().

Feb 6, 2001:
	* This changelog is new
	* tub3270 now supports 3270 console:
		Specify y for CONFIG_3270 and y for CONFIG_3270_CONSOLE.
		Support for 3215 will not appear if 3270 console support
		is chosen.
		NOTE:  The default is 3270 console support, NOT 3215.
	* the components are remodularized: added source modules are
	  tubttybld.c and tubttyscl.c, for screen-building code and
	  scroll-timeout code.
	* tub3270 source for this (2.4.0) version is #ifdeffed to
	  build with both 2.4.0 and 2.2.16.2.
	* color support and minimal other ESC-sequence support is added.