Received: by 2002:a05:6a10:413:0:0:0:0 with SMTP id 19csp1611699pxp; Thu, 17 Mar 2022 12:41:29 -0700 (PDT) X-Google-Smtp-Source: ABdhPJwOebyMMtJe+ZrB8Fpu1UdawAo8WY/jEla0G3cAtNQVX9/oUPuH3mgImQY+X4LM7EaXviVj X-Received: by 2002:a17:902:7049:b0:151:e52e:ae42 with SMTP id h9-20020a170902704900b00151e52eae42mr7008516plt.118.1647546089039; Thu, 17 Mar 2022 12:41:29 -0700 (PDT) ARC-Seal: i=1; a=rsa-sha256; t=1647546089; cv=none; d=google.com; s=arc-20160816; b=gHgjI95QzHNNDbjJQWac5sUzYO/Y3vJXlfSnizx8OkjWj7LMImqcpg2WAHzvcLP36o GypzDrAaR7kT8PooiupP7qR2wBPurc6E4EOy3jXh0hd8YCXoN1xlklH1xiJ5O2c5th1X Y0cicxzlAXjcBiFHQ+LFP5fN74flKnHgG3thlbh9SpLYtWKNB9/zkUi98LkNAAr8yPsh DqhFe063dxf0nknASnO8JihKhu1v+6yrSlozvM7EKtX6cYHgPjWxX0RCFTRf9MSpmS4R GfMFiWBuxWqrzawfJxYoKtleN5+7Ck+79LVUluQDDUXuVSgjY+Nhx7MuNvBbAssKwmv6 o+zg== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=5KA6KPf9pzIbrAGQ7OTYwa4WmNOO+NG/X8DFq+/ntEw=; b=Dx+r10hxwsdbCXL9p3mW1K+JIUDx3Qoz/5n/ZWXoh5f/x2WaYYSv6h+EeQMpNFSotg 8bO/pKqcDPbKaKZWTwRdKpT0RW9phxgdOdJCp+0e1fKUZw/PY7BoiXrKcsf/CRLId9Hh xC65VvXWH2PC28KxUXsKBO+D0p08CvjDMqaMdXMcyl9KpdjASuWOWbIyZJgiGBi46nlX 1I+FHq8BZ1zcKS1aqkFlzv7NcxMbjcKYOz16eJ04XHSiQFfZT9qyGS3qGBGmZ6pkEroP zREZgOsJEJDs6M7eUvy7dVbaSacK1DKlGYjyvMwAzBSF42/n/y0scCTKRmDPhYqtc2gQ xbWg== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=iLY8T7ma; spf=softfail (google.com: domain of transitioning linux-kernel-owner@vger.kernel.org does not designate 23.128.96.19 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Return-Path: Received: from lindbergh.monkeyblade.net (lindbergh.monkeyblade.net. [23.128.96.19]) by mx.google.com with ESMTPS id e7-20020a635447000000b003816043efcdsi3023893pgm.450.2022.03.17.12.41.28 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 17 Mar 2022 12:41:29 -0700 (PDT) Received-SPF: softfail (google.com: domain of transitioning linux-kernel-owner@vger.kernel.org does not designate 23.128.96.19 as permitted sender) client-ip=23.128.96.19; Authentication-Results: mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=iLY8T7ma; spf=softfail (google.com: domain of transitioning linux-kernel-owner@vger.kernel.org does not designate 23.128.96.19 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by lindbergh.monkeyblade.net (Postfix) with ESMTP id 1953022F3C9; Thu, 17 Mar 2022 12:41:18 -0700 (PDT) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S237345AbiCQSOm (ORCPT + 99 others); Thu, 17 Mar 2022 14:14:42 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:34444 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S237336AbiCQSOG (ORCPT ); Thu, 17 Mar 2022 14:14:06 -0400 Received: from dfw.source.kernel.org (dfw.source.kernel.org [IPv6:2604:1380:4641:c500::1]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 085BD221BAF; Thu, 17 Mar 2022 11:12:28 -0700 (PDT) Received: from smtp.kernel.org (relay.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by dfw.source.kernel.org (Postfix) with ESMTPS id 6A70261671; Thu, 17 Mar 2022 18:12:27 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id B3FD7C340E9; Thu, 17 Mar 2022 18:12:20 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1647540746; bh=SitlRaV0KtXhyXe6RFz7Aw0RDpiWGyj8dk2YClR8zz0=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=iLY8T7maVzTyELIBg9UlU9aZDJ7Ww5vTWgfSoq4zy7QqH6WsM823DFjq+wDaH+SxM YtcPdjoMnVs5lGg0KZg5dWYJfuJR2V+bAEHDoT1JgCrMIpyQ8GVDySoxA0PmxGcNmj sF3xJarI8lqCYx3lr/ziS5jfxVORmt6jfSQZrndtxJv2blAsTFs5nSowOGzzNUi0pw faigSLCZTkAVdZolUlw1AsJ37KA7BILQV8BAWtVLQQOVAgUCKrpKt2PIguhd7h4A2P kSEzom4NRQeq8XtlOsRlJzuh5sB1z7Nqkq9DzPZ9G+GEtI6v26OzNIN2gB93lvK9AO GWXBNA+9lCMvw== From: Miguel Ojeda To: Linus Torvalds , Greg Kroah-Hartman Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Miguel Ojeda , Alex Gaynor , Finn Behrens , Adam Bratschi-Kaye , Wedson Almeida Filho , Michael Ellerman , Sven Van Asbroeck , Wu XiangCheng , Gary Guo , Boris-Chengbiao Zhou , Yuki Okushi , Wei Liu , Daniel Xu , Julian Merkle , Jonathan Corbet , Masahiro Yamada , Michal Marek , Nick Desaulniers , linux-doc@vger.kernel.org, linux-kbuild@vger.kernel.org Subject: [PATCH v5 15/20] docs: add Rust documentation Date: Thu, 17 Mar 2022 19:10:03 +0100 Message-Id: <20220317181032.15436-16-ojeda@kernel.org> In-Reply-To: <20220317181032.15436-1-ojeda@kernel.org> References: <20220317181032.15436-1-ojeda@kernel.org> MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-Spam-Status: No, score=-3.8 required=5.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,MAILING_LIST_MULTI, RDNS_NONE,SPF_HELO_NONE,T_SCC_BODY_TEXT_LINE autolearn=unavailable autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org Most of the documentation for Rust is written within the source code itself, as it is idiomatic for Rust projects. This applies to both the shared infrastructure at `rust/` as well as any other Rust module (e.g. drivers) written across the kernel. However, these documents contain general information that does not fit particularly well in the source code, like the Quick Start guide. It also contains an asset (SVG logo) used for the `rustdoc` target and a few other small changes elsewhere in the documentation folder. Co-developed-by: Alex Gaynor Signed-off-by: Alex Gaynor Co-developed-by: Finn Behrens Signed-off-by: Finn Behrens Co-developed-by: Adam Bratschi-Kaye Signed-off-by: Adam Bratschi-Kaye Co-developed-by: Wedson Almeida Filho Signed-off-by: Wedson Almeida Filho Co-developed-by: Michael Ellerman Signed-off-by: Michael Ellerman Co-developed-by: Sven Van Asbroeck Signed-off-by: Sven Van Asbroeck Co-developed-by: Wu XiangCheng Signed-off-by: Wu XiangCheng Co-developed-by: Gary Guo Signed-off-by: Gary Guo Co-developed-by: Boris-Chengbiao Zhou Signed-off-by: Boris-Chengbiao Zhou Co-developed-by: Yuki Okushi Signed-off-by: Yuki Okushi Co-developed-by: Wei Liu Signed-off-by: Wei Liu Co-developed-by: Daniel Xu Signed-off-by: Daniel Xu Co-developed-by: Julian Merkle Signed-off-by: Julian Merkle Signed-off-by: Miguel Ojeda --- Documentation/doc-guide/kernel-doc.rst | 3 + Documentation/index.rst | 1 + Documentation/kbuild/kbuild.rst | 17 + Documentation/kbuild/makefiles.rst | 50 ++- Documentation/process/changes.rst | 41 +++ Documentation/rust/arch-support.rst | 34 ++ Documentation/rust/coding-guidelines.rst | 214 ++++++++++++ Documentation/rust/general-information.rst | 77 +++++ Documentation/rust/index.rst | 20 ++ Documentation/rust/logo.svg | 357 +++++++++++++++++++++ Documentation/rust/quick-start.rst | 230 +++++++++++++ 11 files changed, 1040 insertions(+), 4 deletions(-) create mode 100644 Documentation/rust/arch-support.rst create mode 100644 Documentation/rust/coding-guidelines.rst create mode 100644 Documentation/rust/general-information.rst create mode 100644 Documentation/rust/index.rst create mode 100644 Documentation/rust/logo.svg create mode 100644 Documentation/rust/quick-start.rst diff --git a/Documentation/doc-guide/kernel-doc.rst b/Documentation/doc-gui= de/kernel-doc.rst index 79aaa55d6bcf..724e2ffddff1 100644 --- a/Documentation/doc-guide/kernel-doc.rst +++ b/Documentation/doc-guide/kernel-doc.rst @@ -11,6 +11,9 @@ when it is embedded in source files. reasons. The kernel source contains tens of thousands of kernel-doc comments. Please stick to the style described here. =20 +.. note:: kernel-doc does not cover Rust code: please see + Documentation/rust/docs.rst instead. + The kernel-doc structure is extracted from the comments, and proper `Sphinx C Domain`_ function and type descriptions with anchors are generated from them. The descriptions are filtered for special kernel-doc diff --git a/Documentation/index.rst b/Documentation/index.rst index b58692d687f6..ca9ff1adbe0b 100644 --- a/Documentation/index.rst +++ b/Documentation/index.rst @@ -82,6 +82,7 @@ merged much easier. maintainer/index fault-injection/index livepatch/index + rust/index =20 =20 Kernel API documentation diff --git a/Documentation/kbuild/kbuild.rst b/Documentation/kbuild/kbuild.= rst index 2d1fc03d346e..11c8a55c91ff 100644 --- a/Documentation/kbuild/kbuild.rst +++ b/Documentation/kbuild/kbuild.rst @@ -48,6 +48,10 @@ KCFLAGS ------- Additional options to the C compiler (for built-in and modules). =20 +KRUSTFLAGS +---------- +Additional options to the Rust compiler (for built-in and modules). + CFLAGS_KERNEL ------------- Additional options for $(CC) when used to compile @@ -57,6 +61,15 @@ CFLAGS_MODULE ------------- Additional module specific options to use for $(CC). =20 +RUSTFLAGS_KERNEL +---------------- +Additional options for $(RUSTC) when used to compile +code that is compiled as built-in. + +RUSTFLAGS_MODULE +---------------- +Additional module specific options to use for $(RUSTC). + LDFLAGS_MODULE -------------- Additional options used for $(LD) when linking modules. @@ -69,6 +82,10 @@ HOSTCXXFLAGS ------------ Additional flags to be passed to $(HOSTCXX) when building host programs. =20 +HOSTRUSTFLAGS +------------- +Additional flags to be passed to $(HOSTRUSTC) when building host programs. + HOSTLDFLAGS ----------- Additional flags to be passed when linking host programs. diff --git a/Documentation/kbuild/makefiles.rst b/Documentation/kbuild/make= files.rst index b008b90b92c9..1cd9b8ac90ee 100644 --- a/Documentation/kbuild/makefiles.rst +++ b/Documentation/kbuild/makefiles.rst @@ -29,8 +29,9 @@ This document describes the Linux kernel Makefiles. --- 4.1 Simple Host Program --- 4.2 Composite Host Programs --- 4.3 Using C++ for host programs - --- 4.4 Controlling compiler options for host programs - --- 4.5 When host programs are actually built + --- 4.4 Using Rust for host programs + --- 4.5 Controlling compiler options for host programs + --- 4.6 When host programs are actually built =20 =3D=3D=3D 5 Userspace Program support --- 5.1 Simple Userspace Program @@ -835,7 +836,24 @@ Both possibilities are described in the following. qconf-cxxobjs :=3D qconf.o qconf-objs :=3D check.o =20 -4.4 Controlling compiler options for host programs +4.4 Using Rust for host programs +-------------------------------- + + Kbuild offers support for host programs written in Rust. However, + since a Rust toolchain is not mandatory for kernel compilation, + it may only be used in scenarios where Rust is required to be + available (e.g. when ``CONFIG_RUST`` is enabled). + + Example:: + + hostprogs :=3D target + target-rust :=3D y + + Kbuild will compile ``target`` using ``target.rs`` as the crate root, + located in the same directory as the ``Makefile``. The crate may + consist of several source files (see ``samples/rust/hostprogs``). + +4.5 Controlling compiler options for host programs -------------------------------------------------- =20 When compiling host programs, it is possible to set specific flags. @@ -867,7 +885,7 @@ Both possibilities are described in the following. When linking qconf, it will be passed the extra option "-L$(QTDIR)/lib". =20 -4.5 When host programs are actually built +4.6 When host programs are actually built ----------------------------------------- =20 Kbuild will only build host-programs when they are referenced @@ -1179,6 +1197,17 @@ When kbuild executes, the following steps are follow= ed (roughly): The first example utilises the trick that a config option expands to 'y' when selected. =20 + KBUILD_RUSTFLAGS + $(RUSTC) compiler flags + + Default value - see top level Makefile + Append or modify as required per architecture. + + Often, the KBUILD_RUSTFLAGS variable depends on the configuration. + + Note that target specification file generation (for ``--target``) + is handled in ``scripts/generate_rust_target.rs``. + KBUILD_AFLAGS_KERNEL Assembler options specific for built-in =20 @@ -1206,6 +1235,19 @@ When kbuild executes, the following steps are follow= ed (roughly): are used for $(CC). From commandline CFLAGS_MODULE shall be used (see kbuild.rst). =20 + KBUILD_RUSTFLAGS_KERNEL + $(RUSTC) options specific for built-in + + $(KBUILD_RUSTFLAGS_KERNEL) contains extra Rust compiler flags used to + compile resident kernel code. + + KBUILD_RUSTFLAGS_MODULE + Options for $(RUSTC) when building modules + + $(KBUILD_RUSTFLAGS_MODULE) is used to add arch-specific options that + are used for $(RUSTC). + From commandline RUSTFLAGS_MODULE shall be used (see kbuild.rst). + KBUILD_LDFLAGS_MODULE Options for $(LD) when linking modules =20 diff --git a/Documentation/process/changes.rst b/Documentation/process/chan= ges.rst index a337e8eabfe1..ee22bd1da334 100644 --- a/Documentation/process/changes.rst +++ b/Documentation/process/changes.rst @@ -31,6 +31,8 @@ you probably needn't concern yourself with pcmciautils. =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D =3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D GNU C 5.1 gcc --version Clang/LLVM (optional) 11.0.0 clang --version +Rust (optional) 1.59.0 rustc --version +bindgen (optional) 0.56.0 bindgen --version GNU make 3.81 make --version binutils 2.23 ld -v flex 2.5.35 flex --version @@ -78,6 +80,29 @@ kernels. Older releases aren't guaranteed to work, and w= e may drop workarounds from the kernel that were used to support older versions. Please see addit= ional docs on :ref:`Building Linux with Clang/LLVM `. =20 +Rust (optional) +--------------- + +A particular version of the Rust toolchain is required. Newer versions may= or +may not work because the kernel depends on some unstable Rust features, for +the moment. + +Each Rust toolchain comes with several "components", some of which are req= uired +(like ``rustc``) and some that are optional. The ``rust-src`` component (w= hich +is optional) needs to be installed to build the kernel. Other components a= re +useful for developing. + +Please see Documentation/rust/quick-start.rst for instructions on how to +satisfy the build requirements of Rust support. In particular, the ``Makef= ile`` +target ``rustavailable`` is useful to check why the Rust toolchain may not +be detected. + +bindgen (optional) +------------------ + +``bindgen`` is used to generate the Rust bindings to the C side of the ker= nel. +It depends on ``libclang``. + Make ---- =20 @@ -340,6 +365,12 @@ Sphinx Please see :ref:`sphinx_install` in :ref:`Documentation/doc-guide/sphinx.r= st ` for details about Sphinx requirements. =20 +rustdoc +------- + +``rustdoc`` is used to generate the documentation for Rust code. Please see +Documentation/rust/general-information.rst for more information. + Getting updated software =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D =20 @@ -356,6 +387,16 @@ Clang/LLVM =20 - :ref:`Getting LLVM `. =20 +Rust +---- + +- Documentation/rust/quick-start.rst. + +bindgen +------- + +- Documentation/rust/quick-start.rst. + Make ---- =20 diff --git a/Documentation/rust/arch-support.rst b/Documentation/rust/arch-= support.rst new file mode 100644 index 000000000000..482757a1f3d0 --- /dev/null +++ b/Documentation/rust/arch-support.rst @@ -0,0 +1,34 @@ +Arch Support +=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D + +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. + +.. list-table:: + :widths: 10 10 10 + :header-rows: 1 + + * - Architecture + - Level of support + - Constraints + * - ``arm`` + - Maintained + - ``armv6`` and compatible only, ``RUST_OPT_LEVEL >=3D 2`` + * - ``arm64`` + - Maintained + - None + * - ``powerpc`` + - Maintained + - ``ppc64le`` only, ``RUST_OPT_LEVEL < 2`` requires ``CONFIG_THREAD_S= HIFT=3D15`` + * - ``riscv`` + - Maintained + - ``riscv64`` only + * - ``x86`` + - Maintained + - ``x86_64`` only diff --git a/Documentation/rust/coding-guidelines.rst b/Documentation/rust/= coding-guidelines.rst new file mode 100644 index 000000000000..2a71fd68a06d --- /dev/null +++ b/Documentation/rust/coding-guidelines.rst @@ -0,0 +1,214 @@ +Coding Guidelines +=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D + +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=3D1 rustfmt + +It is also possible to check if everything is formatted (printing a diff +otherwise), for instance for a CI, with:: + + make LLVM=3D1 rustfmtcheck + +Like ``clang-format`` for the rest of the kernel, ``rustfmt`` works on +individual files, and does not require a kernel configuration. Sometimes i= t 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 documenta= tion +comments are, even though they will not be rendered. This improves consist= ency, +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 begi= nning +of a sentence and ended with a period (even if it is a single sentence). T= his +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 inten= ded +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 itsel= f. +For the latter case, comments can be inserted in the middle; that is, clos= er 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 =3D f(42); + /// ``` + // FIXME: Use fallible approach. + pub fn f(x: i32) -> Foo { + // ... + } + +One special kind of comments are the ``// SAFETY:`` comments. These must a= ppear +before every ``unsafe`` block, and they explain why the code inside the bl= ock 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 =3D 0; } + +``// SAFETY:`` comments are not to be confused with the ``# Safety`` secti= ons +in code documentation. ``# Safety`` sections specify the contract that cal= lers +(for functions) or implementors (for traits) need to abide by. ``// SAFETY= :`` +comments show why a call (for functions) or implementation (for traits) ac= tually +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-co= nsidered-undefined.html + /// + /// # Examples + /// + /// ``` + /// let x =3D Some("air"); + /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air"); + /// ``` + pub unsafe fn unwrap_unchecked(self) -> T { + match self { + Some(val) =3D> val, + + // SAFETY: The safety contract must be upheld by the caller. + None =3D> unsafe { hint::unreachable_unchecked() }, + } + } + +This example showcases a few ``rustdoc`` features and some conventions fol= lowed +in the kernel: + + - The first paragraph must be a single sentence briefly describing what + the documented item does. Further explanations must go in extra paragr= aphs. + + - Unsafe functions must document their safety preconditions under + a ``# Safety`` section. + + - While not shown here, if a function may panic, the conditions under wh= ich + that happens must be described under a ``# Panics`` section. + + Please note that panicking should be very rare and used only with a go= od + reason. In almost all cases, a fallible approach should be used, typic= ally + returning a ``Result``. + + - If providing examples of usage would help readers, they must be writte= n in + a section called ``# Examples``. + + - Rust items (functions, types, constants...) must be linked appropriate= ly + (``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 th= at + 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 s= hould +be used in order to avoid confusion and to improve readability when switch= ing +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 =3D bindings::GPIO_LINE_DIRECTION_IN as _, + Out =3D 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``. diff --git a/Documentation/rust/general-information.rst b/Documentation/rus= t/general-information.rst new file mode 100644 index 000000000000..e2713f145a17 --- /dev/null +++ b/Documentation/rust/general-information.rst @@ -0,0 +1,77 @@ +General Information +=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D + +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 documentati= on +generator. + +The generated HTML docs include integrated search, linked items (e.g. type= s, +functions, constants), source code, etc. They may be read at (TODO: link w= hen +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 environm= ent +are needed. This has the added advantage that they will be tailored to +the particular kernel configuration used. To generate them, use the ``rust= doc`` +target with the same invocation used for compilation, e.g.:: + + make LLVM=3D1 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-guideline= s.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=3D1``= to +the same invocation used for compilation, e.g.:: + + make LLVM=3D1 CLIPPY=3D1 + +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 bin= dings. + +Abstractions are not available for all the kernel internal APIs and concep= ts, +but it is intended that coverage is expanded as time goes on. "Leaf" modul= es +(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=3D"y")] // Enabled as a built-in (`y`) + #[cfg(CONFIG_X=3D"m")] // Enabled as a module (`m`) + #[cfg(not(CONFIG_X))] // Disabled diff --git a/Documentation/rust/index.rst b/Documentation/rust/index.rst new file mode 100644 index 000000000000..d28e816513aa --- /dev/null +++ b/Documentation/rust/index.rst @@ -0,0 +1,20 @@ +Rust +=3D=3D=3D=3D + +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 + =3D=3D=3D=3D=3D=3D=3D + + * :ref:`genindex` diff --git a/Documentation/rust/logo.svg b/Documentation/rust/logo.svg new file mode 100644 index 000000000000..65be792a5abe --- /dev/null +++ b/Documentation/rust/logo.svg @@ -0,0 +1,357 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Documentation/rust/quick-start.rst b/Documentation/rust/quick-= start.rst new file mode 100644 index 000000000000..d23ee31d4716 --- /dev/null +++ b/Documentation/rust/quick-start.rst @@ -0,0 +1,230 @@ +Quick Start +=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D + +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=3D1 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 compil= er +version later on requires re-adding the component. + +Otherwise, if a standalone installer is used, the Rust repository may be c= loned +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 manual= ly +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=3Dclang`` or ``LLVM=3D1``. + +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 uploade= d at: + + https://releases.llvm.org/download.html + +Otherwise, building LLVM takes quite a while, but it is not a complex proc= ess: + + https://llvm.org/docs/GettingStarted.html#getting-the-source-code-and-bui= lding-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 sourc= e):: + + cargo install --locked --version $(scripts/min-tool-version.sh bindgen) b= indgen + + +Requirements: Developing +------------------------ + +This section explains how to fetch the tools needed for developing. That i= s, +they are not needed when just building the kernel. + + +rustfmt +******* + +The ``rustfmt`` tool is used to automatically format all the Rust kernel c= ode, +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 compo= nent +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 c= ode. +It can be run by passing ``CLIPPY=3D1`` to ``make`` (for details, please s= ee +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 compo= nent +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 c= an +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 `_ 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 se= tup`` +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 set= up +at the moment. That is:: + + make LLVM=3D1 + +For architectures that do not support a full LLVM toolchain, use:: + + make CC=3Dclang + +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 re= ason +is the toolchain does not support Rust's new v0 mangling scheme yet. +There are a few ways out: + + - Install a newer release (GDB >=3D 10.2, Binutils >=3D 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_INF= O``). --=20 2.35.1