From nobody Wed Sep 10 06:07:56 2025 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id F01E8C64ED8 for ; Fri, 24 Feb 2023 08:50:46 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S229866AbjBXIuo (ORCPT ); Fri, 24 Feb 2023 03:50:44 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:34328 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S229758AbjBXIuj (ORCPT ); Fri, 24 Feb 2023 03:50:39 -0500 Received: from mail.marcansoft.com (marcansoft.com [212.63.210.85]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id AE38526AA; Fri, 24 Feb 2023 00:50:38 -0800 (PST) Received: from [127.0.0.1] (localhost [127.0.0.1]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits) server-digest SHA256) (No client certificate requested) (Authenticated sender: linasend@asahilina.net) by mail.marcansoft.com (Postfix) with ESMTPSA id 31A103FB17; Fri, 24 Feb 2023 08:50:33 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=asahilina.net; s=default; t=1677228637; bh=M10zbadndwKZhD79Kr8HJcwiw4rH1LF/7cTiGWMgTk8=; h=From:Date:Subject:References:In-Reply-To:To:Cc; b=rxZyMibjaZ6LZEVtlYDJAKnfIA8G8nCJ6WBhvtUFKt+oa44YUYkNytz/nRl7PIjK3 KsovDYXQ7NxK4j0FoX30fybbD/sTebMJBDIoqR9KSzLGyc8Lp+IO16y+OFsXKltDzy BobDpVsTTYVYOONz883rwyRgu1dv5Xlv+EEDpbCbfJtiTGRoTrf4l7KtudA93X4BTk Uf6hMIV46bR6OCV8WYI7OtjxwKTdWlAUUdfdYBzvRUfpssj719iFfVcqpQcdCasLRe Uq7EB3xIgb9z2DGg/xJgsHcQFIt/bd7Vkm/5htImkA6ybhaCY1hxgEvrC086rTLWo2 Q6uig72WcEk6g== From: Asahi Lina Date: Fri, 24 Feb 2023 17:50:19 +0900 Subject: [PATCH 1/5] rust: error: Add Error::to_ptr() MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20230224-rust-error-v1-1-f8f9a9a87303@asahilina.net> References: <20230224-rust-error-v1-0-f8f9a9a87303@asahilina.net> In-Reply-To: <20230224-rust-error-v1-0-f8f9a9a87303@asahilina.net> To: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Sven Van Asbroeck Cc: Fox Chen , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, asahi@lists.linux.dev, Asahi Lina X-Mailer: b4 0.12.0 X-Developer-Signature: v=1; a=ed25519-sha256; t=1677228630; l=1624; i=lina@asahilina.net; s=20230221; h=from:subject:message-id; bh=M10zbadndwKZhD79Kr8HJcwiw4rH1LF/7cTiGWMgTk8=; b=z9aZrN4fCmRuP/ostz6C6/F/Fyl5yn8Ylw5KNL2xDbGwWpW4TGwxSiMXo66tBPTFXeAM/J8XP hFMbaVVmizHA2/pLsbqC/BVXiYzZ79/viIlk3yIwIoQl2id9f+fFNdr X-Developer-Key: i=lina@asahilina.net; a=ed25519; pk=Qn8jZuOtR1m5GaiDfTrAoQ4NE1XoYVZ/wmt5YtXWFC4= Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org This is the Rust equivalent to ERR_PTR(), for use in C callbacks. Marked as #[allow(dead_code)] for now, since it does not have any consumers yet. Signed-off-by: Asahi Lina --- rust/helpers.c | 7 +++++++ rust/kernel/error.rs | 7 +++++++ 2 files changed, 14 insertions(+) diff --git a/rust/helpers.c b/rust/helpers.c index 09a4d93f9d62..89f4cd1e0df3 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -20,6 +20,7 @@ =20 #include #include +#include #include =20 __noreturn void rust_helper_BUG(void) @@ -46,6 +47,12 @@ bool rust_helper_refcount_dec_and_test(refcount_t *r) } EXPORT_SYMBOL_GPL(rust_helper_refcount_dec_and_test); =20 +__force void *rust_helper_ERR_PTR(long err) +{ + return ERR_PTR(err); +} +EXPORT_SYMBOL_GPL(rust_helper_ERR_PTR); + /* * We use `bindgen`'s `--size_t-is-usize` option to bind the C `size_t` ty= pe * as the Rust `usize` type, so we can use it in contexts where Rust diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index 5b9751d7ff1d..8611758e27f4 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -76,6 +76,13 @@ impl Error { pub fn to_kernel_errno(self) -> core::ffi::c_int { self.0 } + + /// Returns the error encoded as a pointer. + #[allow(dead_code)] + pub(crate) fn to_ptr(self) -> *mut T { + // SAFETY: Valid as long as self.0 is a valid error + unsafe { bindings::ERR_PTR(self.0.into()) as *mut _ } + } } =20 impl From for Error { --=20 2.35.1 From nobody Wed Sep 10 06:07:56 2025 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id 9A393C64ED8 for ; Fri, 24 Feb 2023 08:50:50 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S229872AbjBXIus (ORCPT ); Fri, 24 Feb 2023 03:50:48 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:34418 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S229844AbjBXIun (ORCPT ); Fri, 24 Feb 2023 03:50:43 -0500 Received: from mail.marcansoft.com (marcansoft.com [212.63.210.85]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 3CF2B61EFE; Fri, 24 Feb 2023 00:50:42 -0800 (PST) Received: from [127.0.0.1] (localhost [127.0.0.1]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits) server-digest SHA256) (No client certificate requested) (Authenticated sender: linasend@asahilina.net) by mail.marcansoft.com (Postfix) with ESMTPSA id C372241A42; Fri, 24 Feb 2023 08:50:37 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=asahilina.net; s=default; t=1677228640; bh=N+RXIF/i8BSXwu8BAV5Rq51ZpnCtf/pwSt4pl5MqBLw=; h=From:Date:Subject:References:In-Reply-To:To:Cc; b=sgSwQWt9xGTwGFMB2TdWEr9w5/65uiCuNhnF6EePNANn7kTxyc9j1ki7VZHILynIi nzOz0/JtbOP1KoEPaFyAgKJ/Oti/bNVV7yy/3gsSB1Juy22ZiulYaNXAsEs19tH3tE 1rIWsiSaH+gVFW93LS3A8XsKCp8WHR4tcimOujS/dZLB5SexFouEXMSpVPtANwGvtn LwriYEWDJ0Y9IGgHNeefy4M1xfJwxDYE0k1ZBxRz3/bt9/n2cl22vXFZEMa6zsWQlv LExpOrEzvitw/6oOyy3B3yTADIwl6i5gD6jr9Bo3y4yW5ty2MasfneY+vFxkA2oDmB 2CZLOUUe/4BEA== From: Asahi Lina Date: Fri, 24 Feb 2023 17:50:20 +0900 Subject: [PATCH 2/5] rust: error: Add Error::from_kernel_errno() MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20230224-rust-error-v1-2-f8f9a9a87303@asahilina.net> References: <20230224-rust-error-v1-0-f8f9a9a87303@asahilina.net> In-Reply-To: <20230224-rust-error-v1-0-f8f9a9a87303@asahilina.net> To: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Sven Van Asbroeck Cc: Fox Chen , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, asahi@lists.linux.dev, Asahi Lina X-Mailer: b4 0.12.0 X-Developer-Signature: v=1; a=ed25519-sha256; t=1677228630; l=1835; i=lina@asahilina.net; s=20230221; h=from:subject:message-id; bh=x7nP5Dl+jwwx+80LB5PaFXLvxugGvPP/700imGU1Bp0=; b=CdN4zbiFV2Fkiy8QTvCq6VBwUqTn1obt6jCAuKp+JyoSL0YG47zwHJBiiSUrkvLnt3nZjNt+7 Fj9UV4SjXZ6ApdWLpqILoNme+RbeL+trkrVNJpsxdlZma9ofB4O79/+ X-Developer-Key: i=lina@asahilina.net; a=ed25519; pk=Qn8jZuOtR1m5GaiDfTrAoQ4NE1XoYVZ/wmt5YtXWFC4= Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org From: Miguel Ojeda Add a function to create `Error` values out of a kernel error return, which safely upholds the invariant that the error code is well-formed (negative and greater than -MAX_ERRNO). If a malformed code is passed in, it will be converted to EINVAL. Lina: Imported from rust-for-linux/rust as authored by Miguel and Fox with refactoring from Wedson. Co-developed-by: Fox Chen Signed-off-by: Fox Chen Co-developed-by: Wedson Almeida Filho Signed-off-by: Wedson Almeida Filho Signed-off-by: Miguel Ojeda Signed-off-by: Asahi Lina Reviewed-by: Andreas Hindborg --- rust/kernel/error.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index 8611758e27f4..3b439fdb405c 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -72,6 +72,25 @@ pub mod code { pub struct Error(core::ffi::c_int); =20 impl Error { + /// Creates an [`Error`] from a kernel error code. + /// + /// It is a bug to pass an out-of-range `errno`. `EINVAL` would + /// be returned in such a case. + pub(crate) fn from_kernel_errno(errno: core::ffi::c_int) -> Error { + if errno < -(bindings::MAX_ERRNO as i32) || errno >=3D 0 { + // TODO: Make it a `WARN_ONCE` once available. + crate::pr_warn!( + "attempted to create `Error` with out of range `errno`: {}= ", + errno + ); + return code::EINVAL; + } + + // INVARIANT: The check above ensures the type invariant + // will hold. + Error(errno) + } + /// Returns the kernel error code. pub fn to_kernel_errno(self) -> core::ffi::c_int { self.0 --=20 2.35.1 From nobody Wed Sep 10 06:07:56 2025 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id 4F637C64ED8 for ; Fri, 24 Feb 2023 08:51:00 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S229863AbjBXIu6 (ORCPT ); Fri, 24 Feb 2023 03:50:58 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:34786 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S229874AbjBXIut (ORCPT ); Fri, 24 Feb 2023 03:50:49 -0500 Received: from mail.marcansoft.com (marcansoft.com [212.63.210.85]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 5877165CDC; Fri, 24 Feb 2023 00:50:45 -0800 (PST) Received: from [127.0.0.1] (localhost [127.0.0.1]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits) server-digest SHA256) (No client certificate requested) (Authenticated sender: linasend@asahilina.net) by mail.marcansoft.com (Postfix) with ESMTPSA id 615E73FA55; Fri, 24 Feb 2023 08:50:41 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=asahilina.net; s=default; t=1677228644; bh=kJHc+snPjIgQ0x5b0wG6oWK+hDCWiSQ0+kJLlveg4g4=; h=From:Date:Subject:References:In-Reply-To:To:Cc; b=eADOkSXnOnrG+bRm9Lumm0rkE0iFgIIYcbPQEVc6tAjTSY7inqONtJOJBFpISJfvU 514K3eerbniJ1CtxpN7Hkb3h0e8Z5BF/DqUq4gzG3bNkfzPCDqO6Jr0Q/LPt7watiM rvdT+A+mCY9kkpLVHYnRBlhTNl/SYg2jzo8cKL615LzPHdQiWhRFF8k6BWbDsvkmV1 +u221r3xiv/Vk2G4Zoxi5COvkD69p8nXqnTGtREa+qDl0gPCQ+Zhh/OWTPS0AH9Yk1 cr0/3fZWwsTsBbxPpwnJAaEbCzbai54MGUNTedh4M6NfIfmbL2/Fp7ZDI9yjSKcyHW t+Q1Yii2HzaTw== From: Asahi Lina Date: Fri, 24 Feb 2023 17:50:21 +0900 Subject: [PATCH 3/5] rust: error: Add to_result() helper MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20230224-rust-error-v1-3-f8f9a9a87303@asahilina.net> References: <20230224-rust-error-v1-0-f8f9a9a87303@asahilina.net> In-Reply-To: <20230224-rust-error-v1-0-f8f9a9a87303@asahilina.net> To: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Sven Van Asbroeck Cc: Fox Chen , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, asahi@lists.linux.dev, Asahi Lina X-Mailer: b4 0.12.0 X-Developer-Signature: v=1; a=ed25519-sha256; t=1677228630; l=1204; i=lina@asahilina.net; s=20230221; h=from:subject:message-id; bh=NH9SKYYkrqlm+FkWH/ZnDX0pl4F1HcPQKt111GaT3sI=; b=KCT/Vytm/SqVGGDB3HJRNnWM8vV7m/eg//dyk/XUccOo+pJEshAuoTMhBGxReTX91zNPMWhlm Lcfou1e9YyICK6k6MRMrXWr6EYJv1btKFyGKZxWjqu1Xom8w/AQwjpF X-Developer-Key: i=lina@asahilina.net; a=ed25519; pk=Qn8jZuOtR1m5GaiDfTrAoQ4NE1XoYVZ/wmt5YtXWFC4= Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org From: Wedson Almeida Filho Add a to_result() helper to convert kernel C return values to a Rust Result, mapping >=3D0 values to Ok(()) and negative values to Err(...), with Error::from_kernel_errno() ensuring that the errno is within range. Lina: Imported from rust-for-linux/rust, originally developed by Wedson as part of the AMBA device driver support. Signed-off-by: Wedson Almeida Filho Signed-off-by: Asahi Lina Reviewed-by: Andreas Hindborg --- rust/kernel/error.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index 3b439fdb405c..1e8371f28746 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -167,3 +167,13 @@ impl From for Error { /// it should still be modeled as returning a `Result` rather than /// just an [`Error`]. pub type Result =3D core::result::Result; + +/// Converts an integer as returned by a C kernel function to an error if = it's negative, and +/// `Ok(())` otherwise. +pub fn to_result(err: core::ffi::c_int) -> Result { + if err < 0 { + Err(Error::from_kernel_errno(err)) + } else { + Ok(()) + } +} --=20 2.35.1 From nobody Wed Sep 10 06:07:56 2025 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id 5A3E4C678DB for ; Fri, 24 Feb 2023 08:51:13 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S229932AbjBXIvM (ORCPT ); Fri, 24 Feb 2023 03:51:12 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:35158 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S229550AbjBXIu6 (ORCPT ); Fri, 24 Feb 2023 03:50:58 -0500 Received: from mail.marcansoft.com (marcansoft.com [212.63.210.85]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 70F8B63570; Fri, 24 Feb 2023 00:50:49 -0800 (PST) Received: from [127.0.0.1] (localhost [127.0.0.1]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits) server-digest SHA256) (No client certificate requested) (Authenticated sender: linasend@asahilina.net) by mail.marcansoft.com (Postfix) with ESMTPSA id F31923FB17; Fri, 24 Feb 2023 08:50:44 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=asahilina.net; s=default; t=1677228648; bh=wVJAQXcyraQ0BfnXVpkBZ9YtELT3PqirBDuZ+Zuy55o=; h=From:Date:Subject:References:In-Reply-To:To:Cc; b=HxJYgu4n3tTBc25V8jiw1H0eIyUfSgpNQlKnyQGzcg0Wsm7bkxPAQIH0x+mvUT5a5 fBFICspOG2q43aR9I8XFkfvffo7dsmJMRJLD0lidZnkyBJJpW9JgKwSQpXomMNwnF5 Nm06Mt0ky44TS5Bs3S3T2OtrQ13Hgy2XfzmH3MIdnPm9u/PCi7Gwew9jekhxtF1AOD b6M1kbyyDQlGYPvJhWeeSr+kZjjGowz947r1RYPWSPZOSwdq+22wjiiU50mQvv2CZc by4gxtsNM/h5T63aKMrBA+k1rCjOJRBmnNH7Z8eTQxyjBdNbsKLcZ8Y4AcUPRhSfeC gXv/6BmmmmAug== From: Asahi Lina Date: Fri, 24 Feb 2023 17:50:22 +0900 Subject: [PATCH 4/5] rust: error: Add a helper to convert a C ERR_PTR to a `Result` MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20230224-rust-error-v1-4-f8f9a9a87303@asahilina.net> References: <20230224-rust-error-v1-0-f8f9a9a87303@asahilina.net> In-Reply-To: <20230224-rust-error-v1-0-f8f9a9a87303@asahilina.net> To: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Sven Van Asbroeck Cc: Fox Chen , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, asahi@lists.linux.dev, Asahi Lina X-Mailer: b4 0.12.0 X-Developer-Signature: v=1; a=ed25519-sha256; t=1677228630; l=4205; i=lina@asahilina.net; s=20230221; h=from:subject:message-id; bh=BznKYHV/l7mf3LcMbv3Ntc8N6CmBcSea0BDBchPZBuw=; b=qzb7B+mHGS+D6NarBS16ESgo6Zx+rEfmqOWkoKfUXQdB365dlGdx3Dd1Vz2YrosL9xrTUz3Kz EWUbzM45L/3AvmIG0XUcRjR3mXU/P2tCad+LNAHbgxIR6LKGgxnjVD1 X-Developer-Key: i=lina@asahilina.net; a=ed25519; pk=Qn8jZuOtR1m5GaiDfTrAoQ4NE1XoYVZ/wmt5YtXWFC4= Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org From: Sven Van Asbroeck Some kernel C API functions return a pointer which embeds an optional `errno`. Callers are supposed to check the returned pointer with `IS_ERR()` and if this returns `true`, retrieve the `errno` using `PTR_ERR()`. Create a Rust helper function to implement the Rust equivalent: transform a `*mut T` to `Result<*mut T>`. Lina: Imported from rust-for-linux/linux, with subsequent refactoring and contributions squashed in and attributed below. Replaced usage of from_kernel_errno_unchecked() with an open-coded constructor, since this is the only user anyway. Co-developed-by: Boqun Feng Signed-off-by: Boqun Feng Co-developed-by: Miguel Ojeda Signed-off-by: Miguel Ojeda Co-developed-by: Fox Chen Signed-off-by: Fox Chen Co-developed-by: Gary Guo Signed-off-by: Gary Guo Signed-off-by: Sven Van Asbroeck Signed-off-by: Asahi Lina --- rust/helpers.c | 12 ++++++++++++ rust/kernel/error.rs | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/rust/helpers.c b/rust/helpers.c index 89f4cd1e0df3..04b9be46e887 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -53,6 +53,18 @@ __force void *rust_helper_ERR_PTR(long err) } EXPORT_SYMBOL_GPL(rust_helper_ERR_PTR); =20 +bool rust_helper_IS_ERR(__force const void *ptr) +{ + return IS_ERR(ptr); +} +EXPORT_SYMBOL_GPL(rust_helper_IS_ERR); + +long rust_helper_PTR_ERR(__force const void *ptr) +{ + return PTR_ERR(ptr); +} +EXPORT_SYMBOL_GPL(rust_helper_PTR_ERR); + /* * We use `bindgen`'s `--size_t-is-usize` option to bind the C `size_t` ty= pe * as the Rust `usize` type, so we can use it in contexts where Rust diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index 1e8371f28746..cf3d089477d2 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -177,3 +177,52 @@ pub fn to_result(err: core::ffi::c_int) -> Result { Ok(()) } } + +/// Transform a kernel "error pointer" to a normal pointer. +/// +/// Some kernel C API functions return an "error pointer" which optionally +/// embeds an `errno`. Callers are supposed to check the returned pointer +/// for errors. This function performs the check and converts the "error p= ointer" +/// to a normal pointer in an idiomatic fashion. +/// +/// # Examples +/// +/// ```ignore +/// # use kernel::from_kernel_err_ptr; +/// # use kernel::bindings; +/// fn devm_platform_ioremap_resource( +/// pdev: &mut PlatformDevice, +/// index: u32, +/// ) -> Result<*mut core::ffi::c_void> { +/// // SAFETY: FFI call. +/// unsafe { +/// from_kernel_err_ptr(bindings::devm_platform_ioremap_resource( +/// pdev.to_ptr(), +/// index, +/// )) +/// } +/// } +/// ``` +// TODO: Remove `dead_code` marker once an in-kernel client is available. +#[allow(dead_code)] +pub(crate) fn from_kernel_err_ptr(ptr: *mut T) -> Result<*mut T> { + // CAST: Casting a pointer to `*const core::ffi::c_void` is always val= id. + let const_ptr: *const core::ffi::c_void =3D ptr.cast(); + // SAFETY: The FFI function does not deref the pointer. + if unsafe { bindings::IS_ERR(const_ptr) } { + // SAFETY: The FFI function does not deref the pointer. + let err =3D unsafe { bindings::PTR_ERR(const_ptr) }; + // CAST: If `IS_ERR()` returns `true`, + // then `PTR_ERR()` is guaranteed to return a + // negative value greater-or-equal to `-bindings::MAX_ERRNO`, + // which always fits in an `i16`, as per the invariant above. + // And an `i16` always fits in an `i32`. So casting `err` to + // an `i32` can never overflow, and is always valid. + // + // SAFETY: `IS_ERR()` ensures `err` is a + // negative value greater-or-equal to `-bindings::MAX_ERRNO`. + #[cfg_attr(CONFIG_ARM, allow(clippy::unnecessary_cast))] + return Err(Error(err as i32)); + } + Ok(ptr) +} --=20 2.35.1 From nobody Wed Sep 10 06:07:56 2025 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id E96CFC677F1 for ; Fri, 24 Feb 2023 08:51:26 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S229959AbjBXIvZ (ORCPT ); Fri, 24 Feb 2023 03:51:25 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:35526 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S229892AbjBXIvI (ORCPT ); Fri, 24 Feb 2023 03:51:08 -0500 Received: from mail.marcansoft.com (marcansoft.com [212.63.210.85]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 3D30B63DC2; Fri, 24 Feb 2023 00:50:53 -0800 (PST) Received: from [127.0.0.1] (localhost [127.0.0.1]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits) server-digest SHA256) (No client certificate requested) (Authenticated sender: linasend@asahilina.net) by mail.marcansoft.com (Postfix) with ESMTPSA id 9133941A42; Fri, 24 Feb 2023 08:50:48 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=asahilina.net; s=default; t=1677228651; bh=xB/uTkNdcRyAJ9MSmz0Zm2ytGsD1PaLAfUTJ4lXE38o=; h=From:Date:Subject:References:In-Reply-To:To:Cc; b=jluUxTT4MsfWow1fquKnY6BSANJ/SOd4Jesz7Uh8zivRONgIVXOwXArRMjNQS/0D5 45iD20o5RBLpaAQRA+5duNKq/skh3y8obwKVEE7ktZXZBSn0ZsGY/XJDI9uXMiQGN7 D3SCiWUJ+1JaXLBWBJDkwb13SIU3jBpAlu20+E2p/fbmdd6B/t7gKj9NYD9sBUa7x5 uCrakUy9Kj/cdP2CiOm7iTR9MJLGYnyIaX5T87NMrrBiDHUyr6ZL6nXlQpo2YPNnEE slCjNYRl9kyhKBiIhqlsNLhkhGpT7ztUT/2gucAYgFJxtJx+whXqpK2BpsKpMKS4tE bQpHo8xTgTtXg== From: Asahi Lina Date: Fri, 24 Feb 2023 17:50:23 +0900 Subject: [PATCH 5/5] rust: error: Add from_kernel_result!() macro MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20230224-rust-error-v1-5-f8f9a9a87303@asahilina.net> References: <20230224-rust-error-v1-0-f8f9a9a87303@asahilina.net> In-Reply-To: <20230224-rust-error-v1-0-f8f9a9a87303@asahilina.net> To: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Sven Van Asbroeck Cc: Fox Chen , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, asahi@lists.linux.dev, Asahi Lina X-Mailer: b4 0.12.0 X-Developer-Signature: v=1; a=ed25519-sha256; t=1677228630; l=2780; i=lina@asahilina.net; s=20230221; h=from:subject:message-id; bh=vBDhcwnH5ynZ3xRDLShDFkYEv5ArQWgEwhEf43533EA=; b=boG/WaS3XMs/3FWEPp+1XQvxkXa8H/c6k5q+2b+v2KaY055zgjtJnRQ53iv5jS+h2FpjzuPR1 fI81HlcBJISB+Tr+N/6qsC2xNEW3hQyZxQhKw+ky6RopnnFk1ZYcITp X-Developer-Key: i=lina@asahilina.net; a=ed25519; pk=Qn8jZuOtR1m5GaiDfTrAoQ4NE1XoYVZ/wmt5YtXWFC4= Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org From: Wedson Almeida Filho Add a helper macro to easily return C result codes from a Rust function that calls functions which return a Result. Lina: Imported from rust-for-linux/rust, originally developed by Wedson as part of file_operations.rs. Added the allow() flags since there is no user in the kernel crate yet and fixed a typo in a comment. Co-developed-by: Fox Chen Signed-off-by: Fox Chen Co-developed-by: Miguel Ojeda Signed-off-by: Miguel Ojeda Signed-off-by: Wedson Almeida Filho Signed-off-by: Asahi Lina --- rust/kernel/error.rs | 52 ++++++++++++++++++++++++++++++++++++++++++++++++= ++++ 1 file changed, 52 insertions(+) diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index cf3d089477d2..8a9222595cd1 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -226,3 +226,55 @@ pub(crate) fn from_kernel_err_ptr(ptr: *mut T) -> R= esult<*mut T> { } Ok(ptr) } + +// TODO: Remove `dead_code` marker once an in-kernel client is available. +#[allow(dead_code)] +pub(crate) fn from_kernel_result_helper(r: Result) -> T +where + T: From, +{ + match r { + Ok(v) =3D> v, + // NO-OVERFLOW: negative `errno`s are no smaller than `-bindings::= MAX_ERRNO`, + // `-bindings::MAX_ERRNO` fits in an `i16` as per invariant above, + // therefore a negative `errno` always fits in an `i16` and will n= ot overflow. + Err(e) =3D> T::from(e.to_kernel_errno() as i16), + } +} + +/// Transforms a [`crate::error::Result`] to a kernel C integer result. +/// +/// This is useful when calling Rust functions that return [`crate::error:= :Result`] +/// from inside `extern "C"` functions that need to return an integer +/// error result. +/// +/// `T` should be convertible from an `i16` via `From`. +/// +/// # Examples +/// +/// ```ignore +/// # use kernel::from_kernel_result; +/// # use kernel::bindings; +/// unsafe extern "C" fn probe_callback( +/// pdev: *mut bindings::platform_device, +/// ) -> core::ffi::c_int { +/// from_kernel_result! { +/// let ptr =3D devm_alloc(pdev)?; +/// bindings::platform_set_drvdata(pdev, ptr); +/// Ok(0) +/// } +/// } +/// ``` +// TODO: Remove `unused_macros` marker once an in-kernel client is availab= le. +#[allow(unused_macros)] +macro_rules! from_kernel_result { + ($($tt:tt)*) =3D> {{ + $crate::error::from_kernel_result_helper((|| { + $($tt)* + })()) + }}; +} + +// TODO: Remove `unused_imports` marker once an in-kernel client is availa= ble. +#[allow(unused_imports)] +pub(crate) use from_kernel_result; --=20 2.35.1