From patchwork Tue Feb 11 15:57:35 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Andreas Hindborg X-Patchwork-Id: 13970177 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 2253F25744C; Tue, 11 Feb 2025 15:59:17 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1739289558; cv=none; b=C3uqsBItli3dcuNgeG8AG+oeEt0TgIh53WOaNmvGegCrVQ4HcZYECJZ5xUq8Ejghyvs716DCDGGVFk6lZgD+AKiUXsCoXp++1BW2g2rB9VgNiXIilm1ubh3Kk0Ospwfni9gvD3dsdbJI5uj9LdZCP+0unAyahX5X9OiZhmsUjJs= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1739289558; c=relaxed/simple; bh=lS6k9hPNj5ZHeaqOmPt5Xc0PPaJv+8aNNMGM3N8QSTo=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=I3zOm2Tmoi8ecCJ3LVGorqEEeDySSCnATV1wH19k2d19ItLsBG//dax/UVP0qUpMIGW1edcBdesTaliJr75PJxOeTI4aB5tH0CrYgeKTWCDe0Z3r1+ThYNeRzZL0vXuHaXmudQLCvhixa/mYVcWzfiCZ2v9mEa7TNvnZ54s2Sm0= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=KNcOrv+t; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="KNcOrv+t" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 780D0C4CEE7; Tue, 11 Feb 2025 15:59:12 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1739289557; bh=lS6k9hPNj5ZHeaqOmPt5Xc0PPaJv+8aNNMGM3N8QSTo=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=KNcOrv+t6uuIaD/2Twk9XMX21QMfyf3fQMETL+fuBn/uDQCteiYPxigJGilXDQ/41 +r1+sKQ4utNXBauhcRBu7O/6jJbmxNEubafSOKE3JWjrIgsPB8lru6hOZwqHNaIh3y hfj0+D56drj7a8jumnkemX7R8+a68M0OgXNK4S12PWE5CDcFpgNT80H9ekmu8FCHHj Go3OX2AIco6RPXdOHAA8MEdCzXfBx0M0g1JWQNkhwfEjbKE1CIIaPxwjzppe0i0KCS 4SJ7rRkkSayBXSSdzq8E5gufZ4LOkfYN4cVgnvdbw6APo+VxN4yn5Jb0V27X1Q4EEO I8LQwg7wDFqzw== From: Andreas Hindborg Date: Tue, 11 Feb 2025 16:57:35 +0100 Subject: [PATCH v6 1/6] rust: str: implement `PartialEq` for `BStr` Precedence: bulk X-Mailing-List: linux-kbuild@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Message-Id: <20250211-module-params-v3-v6-1-24b297ddc43d@kernel.org> References: <20250211-module-params-v3-v6-0-24b297ddc43d@kernel.org> In-Reply-To: <20250211-module-params-v3-v6-0-24b297ddc43d@kernel.org> To: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Alice Ryhl , Masahiro Yamada , Nathan Chancellor , Nicolas Schier , Luis Chamberlain Cc: Trevor Gross , Adam Bratschi-Kaye , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kbuild@vger.kernel.org, Petr Pavlu , Sami Tolvanen , Daniel Gomez , Simona Vetter , Greg KH , linux-modules@vger.kernel.org, Andreas Hindborg X-Mailer: b4 0.15-dev X-Developer-Signature: v=1; a=openpgp-sha256; l=795; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=lS6k9hPNj5ZHeaqOmPt5Xc0PPaJv+8aNNMGM3N8QSTo=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBnq3NxpEdKrw7VKvsqeaNLYuaq6LndyZHC8+5+n pRRlmpKaz2JAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCZ6tzcQAKCRDhuBo+eShj dw+pEAC6/QVtAg4A3oBQ7z4Ku8vzlRNdoim0qKw//6tc+D8C3OBz2nSKfW0Il//zkukqBz91Z5I q7+qAwa2b4fFpuYZ88s0rfucUNmRNE+R2XxEv9r8wGF+aI1cUusSVNy3Ax40lhyWigYKJEC2lwu SDA0bBbHDiOIsLQV4EaRrCp5XlSHkjrlnHi7bxDhWOHm4WfywC/C+EOE4ktjrHqMKXohqA5g70I FipxpmuB2DDiY52b6D+es0f95S5n9PWcRxx4PGlEfvU3mex+QSNMCZ/lIDTzGyrCIOz2b9Ws7nh 39fi4Xre1Qq4vZHQdT+r6RksFygoYovNpPqL9oI6CUheGrPi+a0rWwSSEClivOw76AVxZSfFwL+ HhDDHJUDHSA53NM2nls9Xy0K98Rzerr7hL6gQMt1271aQO5VAOT/AV+gvi4wzBBRfY+h32TO0F4 qO8DRRd5ks58PIgl7XNVWKWXY46zpvSGofVvqwOxg7oLRc/jnd6UaCQbnth1k2tkndk1vZ9Kdk9 en6/m6iwuCdt+S0awo0F7xG6dTfAUQhQK7l0FB/hWeUJDMs8frlVJB1KBgISs+663aJvlDLH0Fc 6kVaL/iD78+pIZe/UQXOq320KB10GW2yGxK81KEd4Y+1oKwQyBdRb0xP4v0qXJw/kGEZrTyij6p YzM4u95IGZs3H3A== X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Implement `PartialEq` for `BStr` by comparing underlying byte slices. Reviewed-by: Alice Ryhl Reviewed-by: Gary Guo Signed-off-by: Andreas Hindborg --- rust/kernel/str.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 28e2201604d67..002dcddf7c768 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -108,6 +108,12 @@ fn deref(&self) -> &Self::Target { } } +impl PartialEq for BStr { + fn eq(&self, other: &Self) -> bool { + self.deref().eq(other.deref()) + } +} + /// Creates a new [`BStr`] from a string literal. /// /// `b_str!` converts the supplied string literal to byte string, so non-ASCII From patchwork Tue Feb 11 15:57:36 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Andreas Hindborg X-Patchwork-Id: 13970175 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 4B43B254AEA; Tue, 11 Feb 2025 15:59:06 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1739289546; cv=none; b=OEbxgzvbz9QL48oJh4m2g3WF4wLHAdbX7NxNfvY5sPcGqCHcucrMN5hgmVLfoMo4mf+ZQ12jA47/CoASTzMZTyL62q+nb10gfNBVlUxXAOytjZHnwzR9dr+qIMiZ5WOdxY6sWSNgkw3L9tX5GcEYzmRmidN5RPZuqEJvom86dmg= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1739289546; c=relaxed/simple; bh=QOkxN9z10V8zzjGozLOHFgjU4k/qJwDqa62nwSaqLms=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=UuL5RLPYFI/0nG0qflxgF3KvHXhBHk27SsLaDIc87Xbec868ztyVWKJldRK/TOSDOIjT6FSY7HmhbJCl1pPhwCjCRVsLgmr3zCwZz7qHSlOe3TS+t5+sp/8Lb71acCkAo0VKaJeg6WFq21f7bIOzjVf4Fog13gxO8Vt+1jc8klQ= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=BLym5K5y; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="BLym5K5y" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 392A7C4CEDD; Tue, 11 Feb 2025 15:59:01 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1739289546; bh=QOkxN9z10V8zzjGozLOHFgjU4k/qJwDqa62nwSaqLms=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=BLym5K5yvCiqM460Wy8LsCe5uBmAUoUsHqOGfmy9LgQgevQPGYgNQXjtNTb24kRT5 Hc61hfr85nVdqililZXJwdnyvVtFvpTK0BPPMeafU4bDCtuywHrFySM3IYwB4SWUyh ESYS1ZYa7TozHMd8XMG85ocGHFaI0vqV1Ep0LG2lw/IJa505zKlSnBm++Npsg2HK1A 2g67FjpbTp4dhHE3363JepdmYB4sugj/VtESo2xPrOuJyO71/SFowUUEGZyhp5buVf fmrSIPSukHDbvKtdjqb7o5cqHcGoxE5N5BYfqKPcUlI5gHXbtLi2Fmvp0oWfbVLfI2 fbR5oULWaUOlg== From: Andreas Hindborg Date: Tue, 11 Feb 2025 16:57:36 +0100 Subject: [PATCH v6 2/6] rust: str: implement `Index` for `BStr` Precedence: bulk X-Mailing-List: linux-kbuild@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Message-Id: <20250211-module-params-v3-v6-2-24b297ddc43d@kernel.org> References: <20250211-module-params-v3-v6-0-24b297ddc43d@kernel.org> In-Reply-To: <20250211-module-params-v3-v6-0-24b297ddc43d@kernel.org> To: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Alice Ryhl , Masahiro Yamada , Nathan Chancellor , Nicolas Schier , Luis Chamberlain Cc: Trevor Gross , Adam Bratschi-Kaye , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kbuild@vger.kernel.org, Petr Pavlu , Sami Tolvanen , Daniel Gomez , Simona Vetter , Greg KH , linux-modules@vger.kernel.org, Andreas Hindborg X-Mailer: b4 0.15-dev X-Developer-Signature: v=1; a=openpgp-sha256; l=983; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=QOkxN9z10V8zzjGozLOHFgjU4k/qJwDqa62nwSaqLms=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBnq3NyuNFJuVu1Dz8XbnHqnIYRa7T4brhyLKeZq 5rDIPMnB/OJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCZ6tzcgAKCRDhuBo+eShj d8fbD/9aSq2fjwCchNjP+OSpo3mdFF3mmk6WsQy+PgP3dElhNCaMYnVgIWMhSYiGna4Fga/i4KY JJzgWg2q+CBm3WoZG/Rrph0FYW0LmGmuvAPS9iFN2LDFuJtITVho28SPeKkPYZzi97T4LPswTRu Rg06sDnD593uPNp+fdhuaC00kA69PItT0rh8qsQURqMGh/8DtZ70zR0UcKB95BXUZoe0/9kkq7o xs6DM8ck+6t/YrevSGamyMubNdZxymJyf605z7zFr3DLaSyvB/q+7fohS+vQFdmdnteyrETYC9r q9MzEwOk4/ubnMSpqWm5yq0M/j8HWBY5f9h0S6f8BU2hjxIfSRkIs1QrobXXWJLJPOooA5SEAHb MFpmDGhZZfoYgq+W6SYrcIogSfzcDx9XqJXWCOeF3kWIGkV3DEIBoIfbAdZpvWt+T0vzsWjNWOD 93WOCrQWAGA92d0VG+AzJORE4wdxjpgLAIWJmVph2bA6ldg6zO20o43ssXbA54LIVX9x73vF/X9 65Nr6DV0jKd3m2UXcu0rj/nL+oERXCL98wmmufUZ72OM/gXZAU/eoCjZPN+zoH88iBMvNJs3E+Z rEn28cxo+tUzx/yoEUnL8C6wqSPynUrsXmc/0ioDMtnl1nIcV6rBnKubHmamFstjU/9UG1DkaNx bYVBfmpgWo2hCMw== X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 The `Index` implementation on `BStr` was lost when we switched `BStr` from a type alias of `[u8]` to a newtype. This patch adds back `Index` by implementing `Index` for `BStr` when `Index` would be implemented for `[u8]`. Signed-off-by: Andreas Hindborg --- rust/kernel/str.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 002dcddf7c768..1eb945bed77d6 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -114,6 +114,17 @@ fn eq(&self, other: &Self) -> bool { } } +impl Index for BStr +where + Idx: core::slice::SliceIndex<[u8], Output = [u8]>, +{ + type Output = Self; + + fn index(&self, index: Idx) -> &Self::Output { + BStr::from_bytes(&self.0[index]) + } +} + /// Creates a new [`BStr`] from a string literal. /// /// `b_str!` converts the supplied string literal to byte string, so non-ASCII From patchwork Tue Feb 11 15:57:37 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Andreas Hindborg X-Patchwork-Id: 13970171 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id A5A2225332A; Tue, 11 Feb 2025 15:58:42 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1739289522; cv=none; b=uiJZ6CrSVl6UUzc1JEsu7cSeQ/ppPj6TjebleIeZ610hIQpuf3IqxxNKtZKqFdSASBNCt462GI71UwwKNkgld0GwkQJwdE78hGDYTbQCG+w6kppS6kkamHlEhwiS7yTCjmXgIAmyFceHQNoAcuy8yJc6c2L3tvUnu0DzTY/YBSw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1739289522; c=relaxed/simple; bh=Xz+5d+IiM2MkTzUVhpWZQYb4mXaS8mDDiRO4o00oaDY=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=qZCF2VTFaJzc79sA+tVg/Di8owZY10i4Fqywe13ea5P0SjM7d8OdWlnpXbzX1sJupMT0TBTqpjcONMITdnW0DAvpT6sGs6WS/5g/d3XzYiIDJf7SY50PIbHeJ6jplOv9wjPPKzAXoP4rPsZqCGaoMqUfxxMH7a0BzqsDvrLP1EU= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=k8DYuahm; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="k8DYuahm" Received: by smtp.kernel.org (Postfix) with ESMTPSA id EBE01C4CEDD; Tue, 11 Feb 2025 15:58:36 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1739289522; bh=Xz+5d+IiM2MkTzUVhpWZQYb4mXaS8mDDiRO4o00oaDY=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=k8DYuahm1ns8l7X3utNH+QQDjoTZ8StYyELgqzDIEsw/dvyzX05UZHkFGPkab9/rV IGxs/PH5JpvHBlVkY//Am37mJPCHga1dQMNlUIddfS1+19HqPWvsKSJxyqkzm4LaNt Kg+RtgfUctBrcF7144d698gPSrctU6T1TvRs5bR/cX8vcvsmHwSoTbggl4ZJ+ICh1p Vs9aRn52LYltDQVHuRVzcVqlXLimVXZ4M2WBaxEYg2W9yhweOZYdQJIaBXaV/NGyZJ RDY7d2A1SwLdDKQJPd3bj5Pz5zfj2aXupRDwwnagXAmfbIP3QjsPNRXryRdbrCOMz8 4ZQkhwiTao34g== From: Andreas Hindborg Date: Tue, 11 Feb 2025 16:57:37 +0100 Subject: [PATCH v6 3/6] rust: str: implement `AsRef` for `[u8]` and `BStr` Precedence: bulk X-Mailing-List: linux-kbuild@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Message-Id: <20250211-module-params-v3-v6-3-24b297ddc43d@kernel.org> References: <20250211-module-params-v3-v6-0-24b297ddc43d@kernel.org> In-Reply-To: <20250211-module-params-v3-v6-0-24b297ddc43d@kernel.org> To: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Alice Ryhl , Masahiro Yamada , Nathan Chancellor , Nicolas Schier , Luis Chamberlain Cc: Trevor Gross , Adam Bratschi-Kaye , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kbuild@vger.kernel.org, Petr Pavlu , Sami Tolvanen , Daniel Gomez , Simona Vetter , Greg KH , linux-modules@vger.kernel.org, Andreas Hindborg X-Mailer: b4 0.15-dev X-Developer-Signature: v=1; a=openpgp-sha256; l=844; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=Xz+5d+IiM2MkTzUVhpWZQYb4mXaS8mDDiRO4o00oaDY=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBnq3NzkuMPzfvD9jbWSliaEZmU5g5Etpdx4wRDz rYJlZhSIVuJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCZ6tzcwAKCRDhuBo+eShj d9aGEADEFlDXKp5Zha9XktLTlkP8VgWwhhQcMfZGoHmp8R7LszzfgdLaxOHZvy8DvC0Qn0O7V82 38csrbjptQvDjoDZXZa3j7vlp3cc2KXG4TL1fsVmoxeW2Jht3eJEhx4LPDA0VDKbns1jbdfXXJq X/wFYuOFtnPouSrjZeFZ0MoexWSdt30bhosdeczkAN6vEWPCeoN1oDJkyiuODCrwk446qA/94Z0 +kkjDTaP5dkQSa1sUZiriJZiRQ1uyaCwus5xVgntCDftS70mm+OT/JTOp9yIC1nnHwWYhknw7Ap axic9JOcio8E0bt9v/8xZTjWDtn4jsRCFb001jRFxbzkLburBFvprm8ZvC+SM51RkzMfGK3QBio xf4Amz9eCs9opxZvZkVvRpnEPbPhXthKYSqNy8UdKKJCMjWe3C5kssnmf9MgcBJZtIvoJUsa6Be qw0TCNShpzQ+6NgZYN1KQKnHtz+9dnFTzKaDiyFguYH7fot3YkhniejgtT0JGnZun8inE6aC2ET +1mxL94gN2wLlttbc+zeIIcX4deJeuB4BEwlgcc1mq9iTuDCoAnk3bgPZFaIb0M5xrRfPQpHA3s PF+MX8EYHh8WtU0WuZvNX65tVdGoFCKV9RqGT38GDADCFOBbW9P8J7MNHt83z4flqiI3qBS/1Lk 814OS3Xmxreo+WA== X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Implement `AsRef` for `[u8]` and `BStr` so these can be used interchangeably for operations on `BStr`. Signed-off-by: Andreas Hindborg --- rust/kernel/str.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 1eb945bed77d6..389341455b962 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -125,6 +125,18 @@ fn index(&self, index: Idx) -> &Self::Output { } } +impl AsRef for [u8] { + fn as_ref(&self) -> &BStr { + BStr::from_bytes(self) + } +} + +impl AsRef for BStr { + fn as_ref(&self) -> &BStr { + self + } +} + /// Creates a new [`BStr`] from a string literal. /// /// `b_str!` converts the supplied string literal to byte string, so non-ASCII From patchwork Tue Feb 11 15:57:38 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Andreas Hindborg X-Patchwork-Id: 13970173 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 5853B253B71; Tue, 11 Feb 2025 15:58:54 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1739289535; cv=none; b=mkzpdX9rXSUF4hse6vKe/MwQv5cJYVkLqyHLza4E1J2ajt4xyUGSPcBrEjFUMpm4vpO7iSyLQOZ9VUfKzPlEyPRM4AxTj6ttTzQCWQ2MQWgKqy6JPutBL7EM0czfeK2mQ6y3UWEGOfsNTQLy107TrHfzTGMYoeK2uXUQ9OZE4XA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1739289535; c=relaxed/simple; bh=+uIy7BR1x85ogRbzllORPBppY/EGsUDcto8p+IOopDY=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=OamDJ1eAvd0KDVK9tOwy824fmXZK4c9ka8Ov48S1hSPg+yXF+EzA05VHiL3n8Yo6s319B3GW6YudoTE+rCVRkXJOdAAZ7xG2mJe/ftbRF6ZjsLDxIuW2AseTOWufzXfW2MCNBRy09ss8az0H0PaEibCnriCdDU3QZGgpJRFTqk0= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=P26YLJDQ; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="P26YLJDQ" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 3DF87C4CEDD; Tue, 11 Feb 2025 15:58:49 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1739289534; bh=+uIy7BR1x85ogRbzllORPBppY/EGsUDcto8p+IOopDY=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=P26YLJDQCFPqyJJEiIKyjWxWumuwksNEim7zIlMRx3/iW4D2tpG/A8PlGkFJKcV5x MnOooWiyWgSE3/Di+DWQUwILD6Kh1ONyOTIbmjHc832wpzLqphBTrJR53kY4/dg+zG Z5clhmpp5u6h7QR/YoIjHIVb1pDIWNMLwvPy9A+7pDCExYn0hUg4553r54bqOEZmAl ZzJm9n0yOrLmzasJIyN2aSk58oQE+cOOpGooZDaHPS+58Brp2IlBUT+fJ4qwxyKdNy IfnftzAbsgkv3foPdyt3i/z+Kk88LmDoOIoL/ky1dYHSWemgP9ieFN6YTLtZAUryOo Bt8NM2ERWLxxA== From: Andreas Hindborg Date: Tue, 11 Feb 2025 16:57:38 +0100 Subject: [PATCH v6 4/6] rust: str: implement `strip_prefix` for `BStr` Precedence: bulk X-Mailing-List: linux-kbuild@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Message-Id: <20250211-module-params-v3-v6-4-24b297ddc43d@kernel.org> References: <20250211-module-params-v3-v6-0-24b297ddc43d@kernel.org> In-Reply-To: <20250211-module-params-v3-v6-0-24b297ddc43d@kernel.org> To: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Alice Ryhl , Masahiro Yamada , Nathan Chancellor , Nicolas Schier , Luis Chamberlain Cc: Trevor Gross , Adam Bratschi-Kaye , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kbuild@vger.kernel.org, Petr Pavlu , Sami Tolvanen , Daniel Gomez , Simona Vetter , Greg KH , linux-modules@vger.kernel.org, Andreas Hindborg X-Mailer: b4 0.15-dev X-Developer-Signature: v=1; a=openpgp-sha256; l=1603; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=+uIy7BR1x85ogRbzllORPBppY/EGsUDcto8p+IOopDY=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBnq3N0+VK1vMqJKMsR66k6TYqa/4dOKJ+Tud6jC brxn3LYGriJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCZ6tzdAAKCRDhuBo+eShj d8k/D/9+n6N/CxDdIs+azmilRQ898rHMZJQqLVNALHRIaWeHgWem5IpgJFnELyv3olInE3BBkFR iFzXkM6zviowcdlzL0fSJMXF9/2IxWDueDTmOB1JkQY+26mRPouZmmEYvB0K3Oew5Ls94xP0IJD q26UWIE70giD/1DEA9Grf7eTy/LWO3/DQxyigyvr2w6Z7qzF58Sk6/ImijEadG3fbdTaH3Fwimm 6ompGRma0ZwPayDROHYS4N+i1BtFBI69a9Pggd+EYKHOKRe839UPOx1qalXl0zEdlpjd+wpgmFz ifaU+uSWFSw3gJlru13AiZ5bnfUoQ7JGXLTPZDXRAe3e6BX3rhSebrqQ5KQdOv/tOaqNDnMhG5R NnNUIR0sWZMb7vrzpFUbKVhKtMiOYlRxGGf1FoclFRDl6PL674iqpCNRTay9rNf8yjIUfrxRTAL RwXiM20Cpg7KElx2zv6RYlI9TwCEhJBzb7Zq6gXBkvOMQcPAg6qvEhBXIR2Bau/hXi86mGD5Le/ 9oD0i717TPW2cvpo62hsIkSKlGxT4kDSe6jqmXBkxSV9c4DPqVdREeAsRs2fc/uGDb4SIOZlkZI Zf80KqlNUjhJCFCV21LPy1ZtekJlGOiAqik3ycrruSrgqkiy3HV+ex3FW5fNb/w9HRKz17mTujd vsFG6HZaIoj0wVA== X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Implement `strip_prefix` for `BStr` by deferring to `slice::strip_prefix` on the underlying `&[u8]`. Reviewed-by: Gary Guo Reviewed-by: Alice Ryhl Signed-off-by: Andreas Hindborg --- It is also possible to get this method by implementing `core::slice::SlicePattern` for `BStr`. `SlicePattern` is unstable, so this seems more reasonable. --- rust/kernel/str.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 389341455b962..c102adac32757 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -31,6 +31,22 @@ pub const fn from_bytes(bytes: &[u8]) -> &Self { // SAFETY: `BStr` is transparent to `[u8]`. unsafe { &*(bytes as *const [u8] as *const BStr) } } + + /// Strip a prefix from `self`. Delegates to [`slice::strip_prefix`]. + /// + /// # Example + /// ``` + /// use kernel::b_str; + /// assert_eq!(Some(b_str!("bar")), b_str!("foobar").strip_prefix(b_str!("foo"))); + /// assert_eq!(None, b_str!("foobar").strip_prefix(b_str!("bar"))); + /// assert_eq!(Some(b_str!("foobar")), b_str!("foobar").strip_prefix(b_str!(""))); + /// assert_eq!(Some(b_str!("")), b_str!("foobar").strip_prefix(b_str!("foobar"))); + /// ``` + pub fn strip_prefix(&self, pattern: impl AsRef) -> Option<&BStr> { + self.deref() + .strip_prefix(pattern.as_ref().deref()) + .map(Self::from_bytes) + } } impl fmt::Display for BStr { From patchwork Tue Feb 11 15:57:39 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Andreas Hindborg X-Patchwork-Id: 13970174 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 0C1BC253F2C; Tue, 11 Feb 2025 15:59:00 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1739289541; cv=none; b=ayEKaS4x58b0f7zbuIpsk9hDZjM+MvtkANGoQ2al7GtZBc3YwdH3+pNY0+Kbj0+lalVdb1+MzoLRqbQ5op60Vuz7yXFMxXWZuG65IeSCeavO4eE+lL5li3PcxhiMDnxC/IKOq7GLdCY/Cy5GzIuOEFVhlincNkVG2kiOrkwlVbw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1739289541; c=relaxed/simple; bh=V1sVaUZMSeiGO+++YI7QwQ+UtECeBzIOktHPUUQ9T30=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=pvKlurn2tbSeS/1c7UYcQ0qzhcpHTA/4oQ4sIKphpGipNrSdPZRchUi32mFQ81k+kW+cgnANwuo/vgqxrW9r5ouD2CFPkEjmshIcYWn1KqsRm10AYIAk96H7YcHMBG2UeofLBJpPV9x9Ed9QDvxd2VgtButyWhYNRWfwJBjrTN8= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=Y3sGaztk; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="Y3sGaztk" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 79EC8C4CEE5; Tue, 11 Feb 2025 15:58:55 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1739289540; bh=V1sVaUZMSeiGO+++YI7QwQ+UtECeBzIOktHPUUQ9T30=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=Y3sGaztkYbYVCC72v5hWyBWRAJtfSIw0tG/ctncIAYK6bGgaMWxKF0Uq8vB/hqGyq 3zkI2EELd8c21TYVhBYoxLg16XrzBbbfxY1IN42BJrgPW8bKzG0c5oVkWxi9bhPn3n mooKyD3Z+QbWUKvKBy+lz5zf0JisXxcRkcpiQoJVmTiTdJ0Y+QfVKYFbFG2keq9hEZ 3r9eJvLselkEMhzkHNltFhAOUYN7lAf4K2RE1dJyTwENhu64bfJBSgvAlCHtOqE4gJ gHghj5jNYFOUy58HzcR+DOHcm3jGCr2xhOhTDqRLqlXkINfxNi+Dango4SfLE6srsW T66vTGz6qlffw== From: Andreas Hindborg Date: Tue, 11 Feb 2025 16:57:39 +0100 Subject: [PATCH v6 5/6] rust: str: add radix prefixed integer parsing functions Precedence: bulk X-Mailing-List: linux-kbuild@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Message-Id: <20250211-module-params-v3-v6-5-24b297ddc43d@kernel.org> References: <20250211-module-params-v3-v6-0-24b297ddc43d@kernel.org> In-Reply-To: <20250211-module-params-v3-v6-0-24b297ddc43d@kernel.org> To: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Alice Ryhl , Masahiro Yamada , Nathan Chancellor , Nicolas Schier , Luis Chamberlain Cc: Trevor Gross , Adam Bratschi-Kaye , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kbuild@vger.kernel.org, Petr Pavlu , Sami Tolvanen , Daniel Gomez , Simona Vetter , Greg KH , linux-modules@vger.kernel.org, Andreas Hindborg X-Mailer: b4 0.15-dev X-Developer-Signature: v=1; a=openpgp-sha256; l=5317; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=V1sVaUZMSeiGO+++YI7QwQ+UtECeBzIOktHPUUQ9T30=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBnq3N11RczktN9XFM3kVE507y9nMG3Yv9MuRh2t RY8MUg/abSJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCZ6tzdQAKCRDhuBo+eShj dwxQEADCZzFtUnaBh8SZ3StKq2ZzbGlv7Cci2zq7ASgNHFngvfmhhTPnv0OgWf2HIsre8kXHplB yRuPiAc0n23xH/y2ZRE6bYG/C/i+/w8gOJJ4JTPG8Jhl1fIxNxBRrVcnOVE/Emo0GOdnVFwQ8cD LpyMgdxtgLWXnripAy88e88V5kvlErn93YpTkbJr3x023l5uNjS5BVOMmFUtU7H1w3srC3vir3e isqPLJHUhKyJUrotlHalbkv3+5Umgat3oPNwWWuZH0hFtRqPIo+mRgPeCKJtfCtvm6m/txc4SR3 5rNJcxsouT8TNsGq215zXtvSXNCnrMmlusKDh17Zujqlxyf0mDAlsLcsYSUT4eMnHY3JAqZT6pl HBXxyRwaYeKOtFvFFrTHEMkmdAZsyxPq3DrdK3CkjF9fBrooVQABdbXOMrxC0yr4+VW0DbvQ1r/ 2IfR4WeemR8p5UcV6bHcsUHMsTSlKx9lMGAWn1xT6LMmVDNr7Xwwv7OO39v+W9/aVfXTtlToVTG +RMzHWGMBUFkhnqGVCkdPuz4DE9AwQ2BZmDkz9JQnVubiwoycyozZhuT1v5PeF+XhyDs0fUi4HL 3aJqXN4LhbcKDXYWr3dCYY93EbAQCdi3U3aWfjsJtGMFZSVfhfDw5hM6AJKZb3nNqUyEgivJBNN I0qvgVF67SNkWkA== X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Add the trait `ParseInt` for parsing string representations of integers where the string representations are optionally prefixed by a radix specifier. Implement the trait for the primitive integer types. Signed-off-by: Andreas Hindborg --- rust/kernel/str.rs | 111 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index c102adac32757..192cd0ff5974f 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -945,3 +945,114 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { macro_rules! fmt { ($($f:tt)*) => ( core::format_args!($($f)*) ) } + +pub mod parse_int { + //! Integer parsing functions for parsing signed and unsigned integers + //! potentially prefixed with `0x`, `0o`, or `0b`. + + use crate::alloc::flags; + use crate::prelude::*; + use crate::str::BStr; + use core::ops::Deref; + + /// Trait that allows parsing a [`&BStr`] to an integer with a radix. + /// + /// [`&BStr`]: kernel::str::BStr + // This is required because the `from_str_radix` function on the primitive + // integer types is not part of any trait. + pub trait FromStrRadix: Sized { + /// Parse `src` to `Self` using radix `radix`. + fn from_str_radix(src: &BStr, radix: u32) -> Result; + } + + /// Extract the radix from an integer literal optionally prefixed with + /// one of `0x`, `0X`, `0o`, `0O`, `0b`, `0B`, `0`. + fn strip_radix(src: &BStr) -> (u32, &BStr) { + match src.deref() { + [b'0', b'x' | b'X', ..] => (16, &src[2..]), + [b'0', b'o' | b'O', ..] => (8, &src[2..]), + [b'0', b'b' | b'B', ..] => (2, &src[2..]), + [b'0', ..] => (8, src), + _ => (10, src), + } + } + + /// Trait for parsing string representations of integers. + /// + /// Strings beginning with `0x`, `0o`, or `0b` are parsed as hex, octal, or + /// binary respectively. Strings beginning with `0` otherwise are parsed as + /// octal. Anything else is parsed as decimal. A leading `+` or `-` is also + /// permitted. Any string parsed by [`kstrtol()`] or [`kstrtoul()`] will be + /// successfully parsed. + /// + /// [`kstrtol()`]: https://www.kernel.org/doc/html/latest/core-api/kernel-api.html#c.kstrtol + /// [`kstrtoul()`]: https://www.kernel.org/doc/html/latest/core-api/kernel-api.html#c.kstrtoul + /// + /// # Example + /// ``` + /// use kernel::str::parse_int::ParseInt; + /// use kernel::b_str; + /// + /// assert_eq!(Ok(0), u8::from_str(b_str!("0"))); + /// + /// assert_eq!(Ok(0xa2u8), u8::from_str(b_str!("0xa2"))); + /// assert_eq!(Ok(-0xa2i32), i32::from_str(b_str!("-0xa2"))); + /// + /// assert_eq!(Ok(-0o57i8), i8::from_str(b_str!("-0o57"))); + /// assert_eq!(Ok(0o57i8), i8::from_str(b_str!("057"))); + /// + /// assert_eq!(Ok(0b1001i16), i16::from_str(b_str!("0b1001"))); + /// assert_eq!(Ok(-0b1001i16), i16::from_str(b_str!("-0b1001"))); + /// + /// assert_eq!(Ok(127), i8::from_str(b_str!("127"))); + /// assert!(i8::from_str(b_str!("128")).is_err()); + /// assert_eq!(Ok(-128), i8::from_str(b_str!("-128"))); + /// assert!(i8::from_str(b_str!("-129")).is_err()); + /// assert_eq!(Ok(255), u8::from_str(b_str!("255"))); + /// assert!(u8::from_str(b_str!("256")).is_err()); + /// ``` + pub trait ParseInt: FromStrRadix { + /// Parse a string according to the description in [`Self`]. + fn from_str(src: &BStr) -> Result { + match src.iter().next() { + None => Err(EINVAL), + Some(sign @ b'-') | Some(sign @ b'+') => { + let (radix, digits) = strip_radix(BStr::from_bytes(&src[1..])); + let mut n_digits: KVec = + KVec::with_capacity(digits.len() + 1, flags::GFP_KERNEL)?; + n_digits.push(*sign, flags::GFP_KERNEL)?; + n_digits.extend_from_slice(digits, flags::GFP_KERNEL)?; + Self::from_str_radix(BStr::from_bytes(&n_digits), radix).map_err(|_| EINVAL) + } + Some(_) => { + let (radix, digits) = strip_radix(src); + Self::from_str_radix(digits, radix).map_err(|_| EINVAL) + } + } + } + } + + macro_rules! impl_parse_int { + ($ty:ty) => { + impl FromStrRadix for $ty { + fn from_str_radix(src: &BStr, radix: u32) -> Result { + <$ty>::from_str_radix(core::str::from_utf8(src).map_err(|_| EINVAL)?, radix) + .map_err(|_| EINVAL) + } + } + + impl ParseInt for $ty {} + }; + } + + impl_parse_int!(i8); + impl_parse_int!(u8); + impl_parse_int!(i16); + impl_parse_int!(u16); + impl_parse_int!(i32); + impl_parse_int!(u32); + impl_parse_int!(i64); + impl_parse_int!(u64); + impl_parse_int!(isize); + impl_parse_int!(usize); +} From patchwork Tue Feb 11 15:57:40 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Andreas Hindborg X-Patchwork-Id: 13970176 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E454C253B57; Tue, 11 Feb 2025 15:59:11 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1739289552; cv=none; b=hi2S82D1+URP0g3NtvFhsm7MJxb3jT4/bPH6DZ9amad9vZ6hgr7B2AkA5bILyvXuEnSY4XToFeYNyVDfNkvyZma5wmsUauhISH9aSfEWQ9jX9cbqSgIjSf0O+qpqH/UJnX9R60MxDK4n2UboIW4zs8d4nnx8OL8xqtmDj7CLrFE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1739289552; c=relaxed/simple; bh=1qzizfR1uEhS63niTpT8rA33QmsPH9Ypdy2VfD3QRe0=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=nHY3fTer0aUW1EIdVl8uycBoyZz2FWEhhDIROUGXJmE7Q1ZgHAht82thPPr8VO7ad45Jt0Y3HO59lvplAfi5AWU3iNvTVIyGV30lmV/uoGf0Jr1W8cJuQnZnRPfa+wz18EkL3XsSZLqrl/kCngYCznxU0szMtIiEOvuITNeqgDk= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=HJeQNe7g; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="HJeQNe7g" Received: by smtp.kernel.org (Postfix) with ESMTPSA id D3654C4CEE5; Tue, 11 Feb 2025 15:59:06 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1739289551; bh=1qzizfR1uEhS63niTpT8rA33QmsPH9Ypdy2VfD3QRe0=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=HJeQNe7gODTA+iscQ7SrH35/S/FJXZVQO9lMXPh2bdX0OAtS1V2tmQ+vVJeVHT56U X57E922ZpUn7tSIYodBiYeX5t2rJPn+WhOmkO02oTiusjMEV7UCwWFeO1XxQB4Gqmi cDzX/Yi2DMtuzskIwcEIYsIKR3K2FmQzi+jshZDw+992WqxEk1tkNZjlG26ZLfAFiX IKoCeszYMSUPhybJ+IL0nvd3+RxuN0BSmKPqWB3iVJUJfDr8TqdKp4djRYPDwEwCha /tEbJsqiKYVZL2pITQ/7RNJbzhRtRWQIpAQ0MXIasjR/T/fHwz+mhj7DZyahbGHwaD lmNXpagdN7UhQ== From: Andreas Hindborg Date: Tue, 11 Feb 2025 16:57:40 +0100 Subject: [PATCH v6 6/6] rust: add parameter support to the `module!` macro Precedence: bulk X-Mailing-List: linux-kbuild@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Message-Id: <20250211-module-params-v3-v6-6-24b297ddc43d@kernel.org> References: <20250211-module-params-v3-v6-0-24b297ddc43d@kernel.org> In-Reply-To: <20250211-module-params-v3-v6-0-24b297ddc43d@kernel.org> To: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Alice Ryhl , Masahiro Yamada , Nathan Chancellor , Nicolas Schier , Luis Chamberlain Cc: Trevor Gross , Adam Bratschi-Kaye , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kbuild@vger.kernel.org, Petr Pavlu , Sami Tolvanen , Daniel Gomez , Simona Vetter , Greg KH , linux-modules@vger.kernel.org, Andreas Hindborg X-Mailer: b4 0.15-dev X-Developer-Signature: v=1; a=openpgp-sha256; l=24418; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=1qzizfR1uEhS63niTpT8rA33QmsPH9Ypdy2VfD3QRe0=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBnq3N29LsFpd5Kog1KsZiqfILFwNEdZKZXImljx H82DH5tnpOJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCZ6tzdgAKCRDhuBo+eShj dzJDEAC9UDD9uVyiIuUIE3YwvgW6kfvD9cerOOuQ1srSaqPLbkvYnykur441leCP/23tU6B/7hi 3Uo1U9pt62ubKVZ3n4hOwYHu9c2QKpxcKBVif+BVXnu0KD/Fw9m1178CM2cjGk+lVXu28BFTssP jhxHOfV2EnlNaUIkUzi/Lc+++WkjfjRhvzrXxiNNdD0QOV5K3pkAN+okf2gyMwjSV+kMfcVjSqZ K11JbFNU0yu2+9A2bGqk9NfplT3TKjxYzwoG/AliW0iqxJNZDNB/iffMEPMIcIefE/EN5QOmsac A2RjLPtScmSdwmlHr60JfkeVBKJUYgWq3xJZPLveNasdHGSxN0EwQQM1S/onNDFIHa8ZlusvEaW oJv0AMoMSQ4u8vdKNLqjemfLux7j9270ZFoggR3jny5pv1f9zULmj8IpL40ILrJDDSKPFcrdRbb zMqkG2+QVacPqLfInoCI0tFjYRPg6wXBw846QZGrf7l6Nf6FawLSLNVDbgGLSGJmrYqhvwwY8Gy +1EhnniWggMgYmZXEIITt+l6ZGn9kZBupXxYjcc9lW2o2VcKxAVH9p06eN4ezby+U+JCQk9ylJ/ B8cGlpafTcQ50RN3KOSAXOCZP6TCSH95wU/KKp/hc6SKft1sbYOHlLMou2C0AWF0RJZKpVGa1z6 B018OI8j8a6bMaA== X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 This patch includes changes required for Rust kernel modules to utilize module parameters. This code implements read only support for integer types without `sysfs` support. Signed-off-by: Andreas Hindborg Acked-by: Petr Pavlu # from modules perspective --- rust/kernel/lib.rs | 1 + rust/kernel/module_param.rs | 225 +++++++++++++++++++++++++++++++++++++++++++ rust/macros/helpers.rs | 25 +++++ rust/macros/lib.rs | 31 ++++++ rust/macros/module.rs | 191 ++++++++++++++++++++++++++++++++---- samples/rust/rust_minimal.rs | 10 ++ 6 files changed, 465 insertions(+), 18 deletions(-) diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index ee48cf68c3111..3d3b0d346b248 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -57,6 +57,7 @@ pub mod kunit; pub mod list; pub mod miscdevice; +pub mod module_param; #[cfg(CONFIG_NET)] pub mod net; pub mod of; diff --git a/rust/kernel/module_param.rs b/rust/kernel/module_param.rs new file mode 100644 index 0000000000000..6c0f5691f33c0 --- /dev/null +++ b/rust/kernel/module_param.rs @@ -0,0 +1,225 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Types for module parameters. +//! +//! C header: [`include/linux/moduleparam.h`](srctree/include/linux/moduleparam.h) + +use crate::prelude::*; +use crate::str::BStr; + +/// Newtype to make `bindings::kernel_param` [`Sync`]. +#[repr(transparent)] +#[doc(hidden)] +pub struct RacyKernelParam(pub ::kernel::bindings::kernel_param); + +// SAFETY: C kernel handles serializing access to this type. We never access +// from Rust module. +unsafe impl Sync for RacyKernelParam {} + +/// Types that can be used for module parameters. +/// +/// Note that displaying the type in `sysfs` will fail if +/// [`Display`](core::fmt::Display) implementation would write more than +/// [`PAGE_SIZE`] - 1 bytes. +/// +/// [`PAGE_SIZE`]: `bindings::PAGE_SIZE` +pub trait ModuleParam: Sized { + /// The [`ModuleParam`] will be used by the kernel module through this type. + /// + /// This may differ from `Self` if, for example, `Self` needs to track + /// ownership without exposing it or allocate extra space for other possible + /// parameter values. + // This is required to support string parameters in the future. + type Value: ?Sized; + + /// Parse a parameter argument into the parameter value. + /// + /// `Err(_)` should be returned when parsing of the argument fails. + /// + /// Parameters passed at boot time will be set before [`kmalloc`] is + /// available (even if the module is loaded at a later time). However, in + /// this case, the argument buffer will be valid for the entire lifetime of + /// the kernel. So implementations of this method which need to allocate + /// should first check that the allocator is available (with + /// [`crate::bindings::slab_is_available`]) and when it is not available + /// provide an alternative implementation which doesn't allocate. In cases + /// where the allocator is not available it is safe to save references to + /// `arg` in `Self`, but in other cases a copy should be made. + /// + /// [`kmalloc`]: srctree/include/linux/slab.h + fn try_from_param_arg(arg: &'static [u8]) -> Result; +} + +/// Set the module parameter from a string. +/// +/// Used to set the parameter value at kernel initialization, when loading +/// the module or when set through `sysfs`. +/// +/// `param.arg` is a pointer to `*mut T` as set up by the [`module!`] +/// macro. +/// +/// See `struct kernel_param_ops.set`. +/// +/// # Safety +/// +/// If `val` is non-null then it must point to a valid null-terminated +/// string. The `arg` field of `param` must be an instance of `T`. +/// +/// # Invariants +/// +/// Currently, we only support read-only parameters that are not readable +/// from `sysfs`. Thus, this function is only called at kernel +/// initialization time, or at module load time, and we have exclusive +/// access to the parameter for the duration of the function. +/// +/// [`module!`]: macros::module +unsafe extern "C" fn set_param( + val: *const kernel::ffi::c_char, + param: *const crate::bindings::kernel_param, +) -> core::ffi::c_int +where + T: ModuleParam, +{ + // NOTE: If we start supporting arguments without values, val _is_ allowed + // to be null here. + if val.is_null() { + crate::pr_warn_once!("Null pointer passed to `module_param::set_param`"); + return crate::error::code::EINVAL.to_errno(); + } + + // SAFETY: By function safety requirement, val is non-null and + // null-terminated. By C API contract, `val` is live and valid for reads + // for the duration of this function. + let arg = unsafe { CStr::from_char_ptr(val).as_bytes() }; + + crate::error::from_result(|| { + let new_value = T::try_from_param_arg(arg)?; + + // SAFETY: `param` is guaranteed to be valid by C API contract + // and `arg` is guaranteed to point to an instance of `T`. + let old_value = unsafe { (*param).__bindgen_anon_1.arg as *mut T }; + + // SAFETY: `old_value` is valid for writes, as we have exclusive + // access. `old_value` is pointing to an initialized static, and + // so it is properly initialized. + unsafe { core::ptr::replace(old_value, new_value) }; + Ok(0) + }) +} + +/// Drop the parameter. +/// +/// Called when unloading a module. +/// +/// # Safety +/// +/// The `arg` field of `param` must be an initialized instance of `T`. +unsafe extern "C" fn free(arg: *mut core::ffi::c_void) +where + T: ModuleParam, +{ + // SAFETY: By function safety requirement, `arg` is an initialized + // instance of `T`. By C API contract, `arg` will not be used after + // this function returns. + unsafe { core::ptr::drop_in_place(arg as *mut T) }; +} + +macro_rules! impl_int_module_param { + ($ty:ident) => { + impl ModuleParam for $ty { + type Value = $ty; + + fn try_from_param_arg(arg: &'static [u8]) -> Result { + let bstr = BStr::from_bytes(arg); + <$ty as crate::str::parse_int::ParseInt>::from_str(bstr) + } + } + }; +} + +impl_int_module_param!(i8); +impl_int_module_param!(u8); +impl_int_module_param!(i16); +impl_int_module_param!(u16); +impl_int_module_param!(i32); +impl_int_module_param!(u32); +impl_int_module_param!(i64); +impl_int_module_param!(u64); +impl_int_module_param!(isize); +impl_int_module_param!(usize); + +/// A wrapper for kernel parameters. +/// +/// This type is instantiated by the [`module!`] macro when module parameters are +/// defined. You should never need to instantiate this type directly. +#[repr(transparent)] +pub struct ModuleParamAccess { + data: core::cell::UnsafeCell, +} + +// SAFETY: We only create shared references to the contents of this container, +// so if `T` is `Sync`, so is `ModuleParamAccess`. +unsafe impl Sync for ModuleParamAccess {} + +impl ModuleParamAccess { + #[doc(hidden)] + pub const fn new(value: T) -> Self { + Self { + data: core::cell::UnsafeCell::new(value), + } + } + + /// Get a shared reference to the parameter value. + // Note: When sysfs access to parameters are enabled, we have to pass in a + // held lock guard here. + pub fn get(&self) -> &T { + // SAFETY: As we only support read only parameters with no sysfs + // exposure, the kernel will not touch the parameter data after module + // initialization. + unsafe { &*self.data.get() } + } + + /// Get a mutable pointer to the parameter value. + pub const fn as_mut_ptr(&self) -> *mut T { + self.data.get() + } +} + +#[doc(hidden)] +#[macro_export] +/// Generate a static [`kernel_param_ops`](srctree/include/linux/moduleparam.h) struct. +/// +/// # Examples +/// +/// ```ignore +/// make_param_ops!( +/// /// Documentation for new param ops. +/// PARAM_OPS_MYTYPE, // Name for the static. +/// MyType // A type which implements [`ModuleParam`]. +/// ); +/// ``` +macro_rules! make_param_ops { + ($ops:ident, $ty:ty) => { + /// + /// Static [`kernel_param_ops`](srctree/include/linux/moduleparam.h) + /// struct generated by `make_param_ops` + #[doc = concat!("for [`", stringify!($ty), "`].")] + pub static $ops: $crate::bindings::kernel_param_ops = $crate::bindings::kernel_param_ops { + flags: 0, + set: Some(set_param::<$ty>), + get: None, + free: Some(free::<$ty>), + }; + }; +} + +make_param_ops!(PARAM_OPS_I8, i8); +make_param_ops!(PARAM_OPS_U8, u8); +make_param_ops!(PARAM_OPS_I16, i16); +make_param_ops!(PARAM_OPS_U16, u16); +make_param_ops!(PARAM_OPS_I32, i32); +make_param_ops!(PARAM_OPS_U32, u32); +make_param_ops!(PARAM_OPS_I64, i64); +make_param_ops!(PARAM_OPS_U64, u64); +make_param_ops!(PARAM_OPS_ISIZE, isize); +make_param_ops!(PARAM_OPS_USIZE, usize); diff --git a/rust/macros/helpers.rs b/rust/macros/helpers.rs index 563dcd2b7ace5..ffc9f0cccddc8 100644 --- a/rust/macros/helpers.rs +++ b/rust/macros/helpers.rs @@ -10,6 +10,17 @@ pub(crate) fn try_ident(it: &mut token_stream::IntoIter) -> Option { } } +pub(crate) fn try_sign(it: &mut token_stream::IntoIter) -> Option { + let peek = it.clone().next(); + match peek { + Some(TokenTree::Punct(punct)) if punct.as_char() == '-' => { + let _ = it.next(); + Some(punct.as_char()) + } + _ => None, + } +} + pub(crate) fn try_literal(it: &mut token_stream::IntoIter) -> Option { if let Some(TokenTree::Literal(literal)) = it.next() { Some(literal.to_string()) @@ -107,6 +118,20 @@ pub(crate) struct Generics { pub(crate) ty_generics: Vec, } +/// Parse a token stream of the form `expected_name: "value",` and return the +/// string in the position of "value". +/// +/// # Panics +/// +/// - On parse error. +pub(crate) fn expect_string_field(it: &mut token_stream::IntoIter, expected_name: &str) -> String { + assert_eq!(expect_ident(it), expected_name); + assert_eq!(expect_punct(it), ':'); + let string = expect_string(it); + assert_eq!(expect_punct(it), ','); + string +} + /// Parses the given `TokenStream` into `Generics` and the rest. /// /// The generics are not present in the rest, but a where clause might remain. diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs index d61bc6a56425e..2778292f8cee1 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -24,6 +24,30 @@ /// The `type` argument should be a type which implements the [`Module`] /// trait. Also accepts various forms of kernel metadata. /// +/// The `params` field describe module parameters. Each entry has the form +/// +/// ```ignore +/// parameter_name: type { +/// default: default_value, +/// description: "Description", +/// } +/// ``` +/// +/// `type` may be one of +/// +/// - [`i8`] +/// - [`u8`] +/// - [`i8`] +/// - [`u8`] +/// - [`i16`] +/// - [`u16`] +/// - [`i32`] +/// - [`u32`] +/// - [`i64`] +/// - [`u64`] +/// - [`isize`] +/// - [`usize`] +/// /// C header: [`include/linux/moduleparam.h`](srctree/include/linux/moduleparam.h) /// /// [`Module`]: ../kernel/trait.Module.html @@ -40,6 +64,12 @@ /// description: "My very own kernel module!", /// license: "GPL", /// alias: ["alternate_module_name"], +/// params: { +/// my_parameter: i64 { +/// default: 1, +/// description: "This parameter has a default of 1", +/// }, +/// }, /// } /// /// struct MyModule(i32); @@ -48,6 +78,7 @@ /// fn init(_module: &'static ThisModule) -> Result { /// let foo: i32 = 42; /// pr_info!("I contain: {}\n", foo); +/// pr_info!("i32 param is: {}\n", module_parameters::my_parameter.read()); /// Ok(Self(foo)) /// } /// } diff --git a/rust/macros/module.rs b/rust/macros/module.rs index cdf94f4982dfc..e6af3ae5fe80e 100644 --- a/rust/macros/module.rs +++ b/rust/macros/module.rs @@ -26,6 +26,7 @@ struct ModInfoBuilder<'a> { module: &'a str, counter: usize, buffer: String, + param_buffer: String, } impl<'a> ModInfoBuilder<'a> { @@ -34,10 +35,11 @@ fn new(module: &'a str) -> Self { module, counter: 0, buffer: String::new(), + param_buffer: String::new(), } } - fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { + fn emit_base(&mut self, field: &str, content: &str, builtin: bool, param: bool) { let string = if builtin { // Built-in modules prefix their modinfo strings by `module.`. format!( @@ -51,8 +53,14 @@ fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { format!("{field}={content}\0", field = field, content = content) }; + let buffer = if param { + &mut self.param_buffer + } else { + &mut self.buffer + }; + write!( - &mut self.buffer, + buffer, " {cfg} #[doc(hidden)] @@ -75,20 +83,116 @@ fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { self.counter += 1; } - fn emit_only_builtin(&mut self, field: &str, content: &str) { - self.emit_base(field, content, true) + fn emit_only_builtin(&mut self, field: &str, content: &str, param: bool) { + self.emit_base(field, content, true, param) } - fn emit_only_loadable(&mut self, field: &str, content: &str) { - self.emit_base(field, content, false) + fn emit_only_loadable(&mut self, field: &str, content: &str, param: bool) { + self.emit_base(field, content, false, param) } fn emit(&mut self, field: &str, content: &str) { - self.emit_only_builtin(field, content); - self.emit_only_loadable(field, content); + self.emit_internal(field, content, false); + } + + fn emit_internal(&mut self, field: &str, content: &str, param: bool) { + self.emit_only_builtin(field, content, param); + self.emit_only_loadable(field, content, param); + } + + fn emit_param(&mut self, field: &str, param: &str, content: &str) { + let content = format!("{param}:{content}", param = param, content = content); + self.emit_internal(field, &content, true); + } + + fn emit_params(&mut self, info: &ModuleInfo) { + let Some(params) = &info.params else { + return; + }; + + for param in params { + let ops = param_ops_path(¶m.ptype); + + // Note: The spelling of these fields is dictated by the user space + // tool `modinfo`. + self.emit_param("parmtype", ¶m.name, ¶m.ptype); + self.emit_param("parm", ¶m.name, ¶m.description); + + write!( + self.param_buffer, + " + pub(crate) static {param_name}: + ::kernel::module_param::ModuleParamAccess<{param_type}> = + ::kernel::module_param::ModuleParamAccess::new({param_default}); + + #[link_section = \"__param\"] + #[used] + static __{module_name}_{param_name}_struct: + ::kernel::module_param::RacyKernelParam = + ::kernel::module_param::RacyKernelParam(::kernel::bindings::kernel_param {{ + name: if cfg!(MODULE) {{ + ::kernel::c_str!(\"{param_name}\").as_bytes_with_nul() + }} else {{ + ::kernel::c_str!(\"{module_name}.{param_name}\").as_bytes_with_nul() + }}.as_ptr(), + // SAFETY: `__this_module` is constructed by the kernel at load time + // and will not be freed until the module is unloaded. + #[cfg(MODULE)] + mod_: unsafe {{ + (&::kernel::bindings::__this_module + as *const ::kernel::bindings::module) + .cast_mut() + }}, + #[cfg(not(MODULE))] + mod_: ::core::ptr::null_mut(), + ops: &{ops} as *const ::kernel::bindings::kernel_param_ops, + perm: 0, // Will not appear in sysfs + level: -1, + flags: 0, + __bindgen_anon_1: + ::kernel::bindings::kernel_param__bindgen_ty_1 {{ + arg: {param_name}.as_mut_ptr().cast() + }}, + }}); + ", + module_name = info.name, + param_type = param.ptype, + param_default = param.default, + param_name = param.name, + ops = ops, + ) + .unwrap(); + } + } +} + +fn param_ops_path(param_type: &str) -> &'static str { + match param_type { + "i8" => "::kernel::module_param::PARAM_OPS_I8", + "u8" => "::kernel::module_param::PARAM_OPS_U8", + "i16" => "::kernel::module_param::PARAM_OPS_I16", + "u16" => "::kernel::module_param::PARAM_OPS_U16", + "i32" => "::kernel::module_param::PARAM_OPS_I32", + "u32" => "::kernel::module_param::PARAM_OPS_U32", + "i64" => "::kernel::module_param::PARAM_OPS_I64", + "u64" => "::kernel::module_param::PARAM_OPS_U64", + "isize" => "::kernel::module_param::PARAM_OPS_ISIZE", + "usize" => "::kernel::module_param::PARAM_OPS_USIZE", + t => panic!("Unsupported parameter type {}", t), } } +fn expect_param_default(param_it: &mut token_stream::IntoIter) -> String { + assert_eq!(expect_ident(param_it), "default"); + assert_eq!(expect_punct(param_it), ':'); + let sign = try_sign(param_it); + let default = try_literal(param_it).expect("Expected default param value"); + assert_eq!(expect_punct(param_it), ','); + let mut value = sign.map(String::from).unwrap_or_default(); + value.push_str(&default); + value +} + #[derive(Debug, Default)] struct ModuleInfo { type_: String, @@ -98,6 +202,50 @@ struct ModuleInfo { description: Option, alias: Option>, firmware: Option>, + params: Option>, +} + +#[derive(Debug)] +struct Parameter { + name: String, + ptype: String, + default: String, + description: String, +} + +fn expect_params(it: &mut token_stream::IntoIter) -> Vec { + let params = expect_group(it); + assert_eq!(params.delimiter(), Delimiter::Brace); + let mut it = params.stream().into_iter(); + let mut parsed = Vec::new(); + + loop { + let param_name = match it.next() { + Some(TokenTree::Ident(ident)) => ident.to_string(), + Some(_) => panic!("Expected Ident or end"), + None => break, + }; + + assert_eq!(expect_punct(&mut it), ':'); + let param_type = expect_ident(&mut it); + let group = expect_group(&mut it); + assert_eq!(group.delimiter(), Delimiter::Brace); + assert_eq!(expect_punct(&mut it), ','); + + let mut param_it = group.stream().into_iter(); + let param_default = expect_param_default(&mut param_it); + let param_description = expect_string_field(&mut param_it, "description"); + expect_end(&mut param_it); + + parsed.push(Parameter { + name: param_name, + ptype: param_type, + default: param_default, + description: param_description, + }) + } + + parsed } impl ModuleInfo { @@ -112,6 +260,7 @@ fn parse(it: &mut token_stream::IntoIter) -> Self { "license", "alias", "firmware", + "params", ]; const REQUIRED_KEYS: &[&str] = &["type", "name", "license"]; let mut seen_keys = Vec::new(); @@ -140,6 +289,7 @@ fn parse(it: &mut token_stream::IntoIter) -> Self { "license" => info.license = expect_string_ascii(it), "alias" => info.alias = Some(expect_string_array(it)), "firmware" => info.firmware = Some(expect_string_array(it)), + "params" => info.params = Some(expect_params(it)), _ => panic!( "Unknown key \"{}\". Valid keys are: {:?}.", key, EXPECTED_KEYS @@ -183,28 +333,30 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream { let info = ModuleInfo::parse(&mut it); let mut modinfo = ModInfoBuilder::new(info.name.as_ref()); - if let Some(author) = info.author { - modinfo.emit("author", &author); + if let Some(author) = &info.author { + modinfo.emit("author", author); } - if let Some(description) = info.description { - modinfo.emit("description", &description); + if let Some(description) = &info.description { + modinfo.emit("description", description); } modinfo.emit("license", &info.license); - if let Some(aliases) = info.alias { + if let Some(aliases) = &info.alias { for alias in aliases { - modinfo.emit("alias", &alias); + modinfo.emit("alias", alias); } } - if let Some(firmware) = info.firmware { + if let Some(firmware) = &info.firmware { for fw in firmware { - modinfo.emit("firmware", &fw); + modinfo.emit("firmware", fw); } } // Built-in modules also export the `file` modinfo string. let file = std::env::var("RUST_MODFILE").expect("Unable to fetch RUST_MODFILE environmental variable"); - modinfo.emit_only_builtin("file", &file); + modinfo.emit_only_builtin("file", &file, false); + + modinfo.emit_params(&info); format!( " @@ -362,14 +514,17 @@ unsafe fn __exit() {{ __MOD.assume_init_drop(); }} }} - {modinfo} }} }} + mod module_parameters {{ + {params} + }} ", type_ = info.type_, name = info.name, modinfo = modinfo.buffer, + params = modinfo.param_buffer, initcall_section = ".initcall6.init" ) .parse() diff --git a/samples/rust/rust_minimal.rs b/samples/rust/rust_minimal.rs index 4aaf117bf8e3c..d999a77c6eb9a 100644 --- a/samples/rust/rust_minimal.rs +++ b/samples/rust/rust_minimal.rs @@ -10,6 +10,12 @@ author: "Rust for Linux Contributors", description: "Rust minimal sample", license: "GPL", + params: { + test_parameter: i64 { + default: 1, + description: "This parameter has a default of 1", + }, + }, } struct RustMinimal { @@ -20,6 +26,10 @@ impl kernel::Module for RustMinimal { fn init(_module: &'static ThisModule) -> Result { pr_info!("Rust minimal sample (init)\n"); pr_info!("Am I built-in? {}\n", !cfg!(MODULE)); + pr_info!( + "My parameter: {}\n", + *module_parameters::test_parameter.get() + ); let mut numbers = KVec::new(); numbers.push(72, GFP_KERNEL)?;