From patchwork Tue Feb 4 12:02:08 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Andreas Hindborg X-Patchwork-Id: 13959036 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 1FB8F20D4FC; Tue, 4 Feb 2025 12:04: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=1738670683; cv=none; b=OEZKBbf6rjqAiaxvqMw9zSz1vKV59g96+FoO+5ZADc6ApGq+ANo7vIG82xww4C7i6LhfBFUCYZxttXdrEtKP2QIZRtWeHjGFNATolAwzXVXg9JGDyHvWS2r25CuI9zUc9v51DO59p89tKk/stijApew71B6mn69FBLvClGWs8vs= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738670683; c=relaxed/simple; bh=0arBoyu3Hidy2Bd0UioU3I9Dhsom6btci9xWGQw7wPM=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=tAeXbykwNCw4aRpNyImsSX4O1gmzVN9PqGemoRAvMu29KkhMGoYRKyWeTU2JmlfoPLqS4cmFFXj0W+WAM5WJw3/DYDiqtXbPLwGbX0iYIu8ud5ooPtz9IXK9QJdvADyJUpaJzBlWgM0+GTPt5PuRRtj07CvDL+04Xv7cjxMpvcY= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=WCboyeFO; 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="WCboyeFO" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 4FF92C4CEDF; Tue, 4 Feb 2025 12:04:37 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1738670682; bh=0arBoyu3Hidy2Bd0UioU3I9Dhsom6btci9xWGQw7wPM=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=WCboyeFO93OyLDaB3BQ3LHgMLQ+n+0bkkVBDXvlC4y7scGqZtGlIBtWMhFEQH2JH8 mMDRiJRK4A5pVK+iyzZLKXHfb3J7Y8Xx/IWX7hkc6fziAPDfv7papkGxnrYCPJaCXW dQkRMZJIcbQrkg3Xvwxl85qTxKJKuj4Y5lZKJG/DgNSvjxqvpUKutI6aM4jvKbyATe nYyRH3F9Au5ZWkvv/Kglred5uf15ZzPWpso83fPj8Cruee/bTnbATg8N0vIo+fzdCE sYD4XIWvWgudArQ1F5v/Txwf6xJhVGOQGR+36l6v1iYQMEqKLqw1d2WERSXQuTNumD wrQsnj8c3Xw/w== From: Andreas Hindborg Date: Tue, 04 Feb 2025 13:02:08 +0100 Subject: [PATCH v5 1/5] 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: <20250204-module-params-v3-v5-1-bf5ec2041625@kernel.org> References: <20250204-module-params-v3-v5-0-bf5ec2041625@kernel.org> In-Reply-To: <20250204-module-params-v3-v5-0-bf5ec2041625@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=849; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=0arBoyu3Hidy2Bd0UioU3I9Dhsom6btci9xWGQw7wPM=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBnogHXYEu6tWoU6mU3Vx+FudFkvhTU7P/pK4Lhf FdL32HTc6KJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCZ6IB1wAKCRDhuBo+eShj d2K0EAChe2kjKfA+M7h37KcqfhRdnBKojjgbo0udmJQyrFXOUmd+BGUichd/0//xlok3X+M1h/D PsPeOg9A4Nwg8EtZASUxLe62hDnv9RURMzSmjUbGKeW9kz1kLxfsehE4NrCUFRBWxU7wfD8c3PU 9GXAXTK8ay3XB9vDSaDQ6E8TBa3JgNSUJb9qLsqW1Y3VCM9pCFDotT9D5vRVvrj4nZnmzUcjEEA HIaP0R3BvbfLhmHBY1kzCKtf6V1FPga9CnUXZqzOf5JYUAogJqXhkOuieEVGrku79il08SXiMDA QgfJc0FhxhHX2WcRzpZsuwa0D44esIfe7fmPqSKm9T2lGrKiRkN8O7WiVfCcR8I9pGYHY+BAu6G DtwFpiOT2fQgVqSD2EDzpTQNCMww2bMOQqjipjgcA0//ZsxzZpFqYuOiiRO3RXlCQa1H65rLCc+ wHa1wSp8iJ33Mbkv2TXaXpwX7D9M2zoPR8ln/JkzN2ic91ML2bsjKvzz9d4TRtBhlx9xcSFOtnR BBIkMFVtZHmVfEHZjsZADbgR9qkZLUzRADdw2A67bbemlPRbL/TzguR34LpISLs+Hz+F8rNCgBU OJ3itTvKv8slpikH+E3FXwggBE4J8tctfs3Q+tOamsB4Vp/4zytXdk198t+f9PFR4qf9J6A1JKE ZHSGGzSns1mkPbA== 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 28e2201604d67800f8d6b8f69065dc32710b891e..002dcddf7c7687522a0acbff3ce6f65fa890e216 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 4 12:02:09 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Andreas Hindborg X-Patchwork-Id: 13959037 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 3499920D4FC; Tue, 4 Feb 2025 12:04:48 +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=1738670689; cv=none; b=FZFsqZKZOi+zuY0COWsX7F7OC1QLj8JQ09Do+XmYwTuB/7kJPsxgHEXbA3SiGUUWq/IzLUz90TqDP86FSPD0Dsdyd5SheB3AKDxtvumTScdCgkC4oYUsZX6UIUSDBgnWGHYKFDIE/cbuEpTRW5523NCqOCSUbUXG+hNxbkYmiqA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738670689; c=relaxed/simple; bh=9vPDXVCZikkxMhidQOZWaazwuq2iUI09NMwF0gUW9wg=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=C2599r7yKr1a7PFIW6BplcNGf650hNrUFc0XVUYVF+VWkKZtpshmpIoHocxjfSSFWkhYsKVv0O+aQNjsuEplr63z/umTlO1FeLbxwtAT91T3gIz/lUOH5naZeLv4TMMbNN6puRJ9jxnIegtg/iPW1L7gQUXiHvxVwo+LnSRrkjo= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=Z6pao0g4; 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="Z6pao0g4" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 310EEC4CEE2; Tue, 4 Feb 2025 12:04:42 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1738670688; bh=9vPDXVCZikkxMhidQOZWaazwuq2iUI09NMwF0gUW9wg=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=Z6pao0g4daPzRa6LJBDNuC7MDm1Th2cwvfOc1o6NClkaA1oD/nkZ4dNMtNFnWguXx s9Utn79EwmG6fXmz7ZsbZYjCwOiRooCzHNYz6hSX8mWUA/KvsE2SO2WNsS3lzDH2EO TiOciZuzgbvFTLJgO/iCOlDaANnJSMjwOqy3YixP5K4i7gKmhul+86y6nEPRrY2y4h //WhYDY8USbuzbWhTRo7q6WxPWi++b4ZB+zqZuhlEi/kdOzBCB9EJWRoTbLSI8h6an pWOSFiOfcgfLXfqDxpI5vR4TiAWSbe9wrgYUQooqjrmElNUlqLqNDZwuziwmIHyT5R nCf3jveALtZqA== From: Andreas Hindborg Date: Tue, 04 Feb 2025 13:02:09 +0100 Subject: [PATCH v5 2/5] 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: <20250204-module-params-v3-v5-2-bf5ec2041625@kernel.org> References: <20250204-module-params-v3-v5-0-bf5ec2041625@kernel.org> In-Reply-To: <20250204-module-params-v3-v5-0-bf5ec2041625@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=1037; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=9vPDXVCZikkxMhidQOZWaazwuq2iUI09NMwF0gUW9wg=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBnogHYtdTSaVz/dqlQ5RrubPDCr5mbmsMF4q4ti GgEmSdim+aJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCZ6IB2AAKCRDhuBo+eShj d0y+EACFCOFREKetB1YvSS7kZ4bSlsoV4btfPADQcByqGyDyST6KsA+Zu1ECm2txVUKtLSZVt89 1Qa2nbUOSujvLJMoB9fFhYVLfZf6zX2o2KfpQopZ1i0CTi8KWeYzMk1ZQWTkCA4Q9gJmBr3uANj LL3rG3hdzdL6unTPibplFpHqEQUe6Yk1Mx7ATJQNM5xChgckhkq/Dpy+zBPRscQJZc6qQFPFYEJ Itc4wCc/b+wH+fIlVdwRSbtnaa6IY3tnGiSbfaE3qVjVT8fjLGwsZjWsqgqCe9wbKagQPhmrAP5 rHmdBDvG6ex3zqH+WUXPgvcZDyeaxP8MmO8urqS2nzGuCQ83XcNdt75xMnrZzdQsmLX1S9TBRvx IlEDKj8SlUTXlCMbGj1csu1vVk3n0opJ6zmX2h9VV9mIUIKgkp8vuBdTJrjntDisIi1RwanDc7k X3F0/dfR/tk4kN11l83BKHU1cw/9AsDHowB0SD8omHgxr/lj7KmIYXRBl2LFuNThqnn/pM9wI0+ xVInRDeiwO122+xOxFEKYKYi+3hmPQahaDY5TXS8oZki9lK/RNLNZcKgcG33JXK/KBzmEVqE396 nFaz9/7A8QIsUMCMpLoWQZ0GtxYya98ZjoPvDJ+/+0XPQa+Qj3OsTw4ou6wEMgmpciTwqC5Sy0H 6SBtY/8Uut6i9ig== 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 002dcddf7c7687522a0acbff3ce6f65fa890e216..1eb945bed77d6592216cf30678fcca70d4c0b3b3 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 4 12:02:10 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Andreas Hindborg X-Patchwork-Id: 13959041 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 0247A212FAD; Tue, 4 Feb 2025 12:05: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=1738670712; cv=none; b=Px0eI83m0VzqLtbFTXmmEgZqU7LLCUPQZ1Qrl/zCypKUJ4m3UEu4EA7ajtQ3RPo9KvYBScsbQqjRIlqzKXC0dSnVKn/sv1bztud9C+byBC1E4QUj/E024gXjxRGUwnnwbQcJxFE26FJVk8lRgTL48x9eD85tfa2qTkCdFYvegrY= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738670712; c=relaxed/simple; bh=Uy+G3QIpmMlPaJnwyniXgpOszKcDbT4GdwTwy3kc5ko=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=qQPgZbnvsGEQ/gA+pNHdYsXg/z17ncCEkgQz1xAnX0C6VfKORdjZTgoCqUbxKlyONfHtBiCAglpvK1MCS1U7BB2MWI+osCNaiv42EOD3Ju/I6UhHqPANn0+8q9i3/ih7Oc1Punlr6Tx+TgeUuhY+NGnOggbQN8LKz0vXsknnki4= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=f7u/zWKT; 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="f7u/zWKT" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 85853C4CEE2; Tue, 4 Feb 2025 12:05:06 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1738670711; bh=Uy+G3QIpmMlPaJnwyniXgpOszKcDbT4GdwTwy3kc5ko=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=f7u/zWKTv2wYsO4h4cbZ/BM8fffCwISDxHkPkYIBgh+wVbprp6Te1RBOlTB4QW/CK vuSV2Tv2d6B8dvd6k2MuO4nyv/gkqxROBKSijthHc0raFV0ckxBatrVxShWIgwjZuz g0Yq/srMyodBAJrjlrbSB/t6bK7Y0AlyRgDk6vh1hQqcV7an4ydVHfcqSiAw95lDOt TJ/hxVLbbGJyWyNKHtDrQkx9EVsxcAWyIsAzezXE7yCwyW3AToFUJfLO82Gy2ZTMIe 57B23iPv2zpWT+sJHYFti7w6KoF92xY2HlNH4CNHup01OhuZ0KLGIsLNWruGVVKO3m YDzHExQMyLkbg== From: Andreas Hindborg Date: Tue, 04 Feb 2025 13:02:10 +0100 Subject: [PATCH v5 3/5] 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: <20250204-module-params-v3-v5-3-bf5ec2041625@kernel.org> References: <20250204-module-params-v3-v5-0-bf5ec2041625@kernel.org> In-Reply-To: <20250204-module-params-v3-v5-0-bf5ec2041625@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=1637; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=Uy+G3QIpmMlPaJnwyniXgpOszKcDbT4GdwTwy3kc5ko=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBnogHYEzdjU6TcJv+L0vohcUEnACY4iii9YnslJ UsmC0XNsT2JAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCZ6IB2AAKCRDhuBo+eShj dyUtEAC3NcHKUIuleDVPDoaDJl+J67nBVY5Z+jHNrCUCI4If+fOoreP/q9nXtbFP3EQF6rcujmG Y7zId8rOb8JLQBqFn6ga4H79ESsxMYh26+Itvnk/FQh2PvcxKTDItCO/nnrBSo5CCncepLvK2dS ahxJgmqjwcTF4Bn5pHCbF+2/nIVJppAJ7XJgEchIMJUp+VCI12C3CF3n/jnNAY6lwYyMhoP4gbT ZyrmVL/rox3jGO0DkVcDw8wCeyAQAWQx7ZGEJVQ+FuYRflvWyjOAUcYBBvnBP1pwuVqccW5ksig CPuFU2lNbyDSpzwolAZzEnKBOawShLX9cL6/gt++8ITEavRs3OJS9NOeRA0pSANV7it00yClThQ fVkEucMRD8m9YCoT9T3Mb32LVQuqrnBdPTf1J1WHuRPoOwTitck+yF/fcfLFNTBfHqu1JCXzrRQ 1WZnHMmoePu1isAheRhs50tfWAsriv8pyxtWFgBEObtEuJEZuc6BHSOwQT0dEbuMY/iiwvwov29 udn/q9ZSxPXL78ou6g+z+2IIW3ryPJogBqn2Q4hYOGxvIMjgcfnU6cH6WlpSyLkydjlG9mPm+Ux TY9LK11qIkqraPMDus5SHezGzPwgr12iRRNOzoqELcKDkw6Z51+T2ooKOmgz0TNagPm6gaM9MUw 9WY/RW/2KT8cEEw== 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 Reviewed-by: Alice Ryhl --- 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 1eb945bed77d6592216cf30678fcca70d4c0b3b3..80601206961e5b2d682af5f7028434bba1604272 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: &Self) -> Option<&BStr> { + self.deref() + .strip_prefix(pattern.deref()) + .map(Self::from_bytes) + } } impl fmt::Display for BStr { From patchwork Tue Feb 4 12:02:11 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Andreas Hindborg X-Patchwork-Id: 13959040 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 5F80E20E028; Tue, 4 Feb 2025 12:05:05 +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=1738670706; cv=none; b=D/X+vAikPC938SkDCm/ES+J/KQyzJCzWPUsGdEBw5nACL5SRQK8gBKBqkDUSFQraffRTTVk+MqTW7yl3kI5DH9ijOvVacWVNGz31VKaMQXg4Q98hQXzhA3pzSq+FJLzeO6mp6Zq8ihl606o8lay5/f1ax7+KgipsoknlyjCBbLw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738670706; c=relaxed/simple; bh=Zb8g8SVhfu2MakmGaygCG3YC6SDGoQDfOIhOECkKc5M=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=C7PisnurzU3AMsN74H1r+J/+J0O9bfSQsrRzlOetNKTo7VWETpLjuXduxX9n2/uxDu7UHBMNB40M3Szmm3+EqcdgsiCPLSv14CG3GrsZbztiqiewhN7NGo3d30hdhYevzHlwjPfOkSw5vgxqyDqnFZcjCcboPSMul+N8o6PGnHU= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=mQWujDS0; 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="mQWujDS0" Received: by smtp.kernel.org (Postfix) with ESMTPSA id C5F42C4CEDF; Tue, 4 Feb 2025 12:05:00 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1738670705; bh=Zb8g8SVhfu2MakmGaygCG3YC6SDGoQDfOIhOECkKc5M=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=mQWujDS0lw8jpHXt2EQYkX2wCGflEP2Tf9oPHligcnAi6NoCEjmviNnmr+U48nc5J huoO4NUodBgL4kTfG72BEmWs4h2Hbd7IZpr4aByPcKMlTa/4ErDlrKlE9vjx9p8lAI GtyqVtdsyS0mKicz5Pmvuu+78axoQL5ajdrV68QQC9fyQ1nWgKAfYzX6FeBF/CzLYD XDe1G6zGbQujIyBBcaZWeGzdYFeXWfpEWzSIPnyjK6Q0giZv7j6z0PZpt7SkBegDMT nn9XthAsPbPOEcvGyB5Y/k9rlENShXhkQLz9vEdbpdaLkHTEL0XUh4Z4xkYSU7K/BM iBztwAdyd4RzA== From: Andreas Hindborg Date: Tue, 04 Feb 2025 13:02:11 +0100 Subject: [PATCH v5 4/5] 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: <20250204-module-params-v3-v5-4-bf5ec2041625@kernel.org> References: <20250204-module-params-v3-v5-0-bf5ec2041625@kernel.org> In-Reply-To: <20250204-module-params-v3-v5-0-bf5ec2041625@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=5311; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=Zb8g8SVhfu2MakmGaygCG3YC6SDGoQDfOIhOECkKc5M=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBnogHZwZkdxzH5Cbj9qLALj8ggqyU1SXjBYSRL1 RUztwMeMUaJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCZ6IB2QAKCRDhuBo+eShj dyrED/4+lfdHqYjbCd7TNc3NFKod1KMMXUFyXzK9Q/cI3Erh3fqMmxMT2KOCFUoh4g1mzD+eE4J UpZsfH960VpagPkGBrbqeSu4t+Q6nyHHXNQCDOiJ2Vwq+hMbob+5zHsUFvKd/vXl4vGKdSbxv38 KiHwSa5LIueAgpL9AA+8+lAX/LHgIgIJAxJCFDxoSoK7K57qFYXa3n8FU3iRMRQvUN+F/tLzXNw dJx2tICSQPT7GHyA9OlygbO0KWOKWmSj0gPPcjAHcBqJPxUv8JkUVwYLHWciorNoQdhLxRwZ+uP 7+1MfXeO+ZsJO1NGmWsDvcup5S/Pl60CzSqlTbpZvAYX2YGzi/llHF5Cd0odv30nRYIu4GJa7Va cwpZ0uvG87W1Go/mIF5tYyEH9+eVGqpyxkYmS9laRjI5YXwe99J3uXe2jSJyIaONc/2ootkkCsa UP/FP7vNgG3HactDAEg5HY42FKgfbOzgIMDKmEjSyuNAotZrpnu58jlz6jpyT7RHOaaT/zkRY/F oHFqXea5iwBJPlmiSjj+CaHOzpyX0N1KazYPowqhP+jD7PqiLqj+m+R3zfbNZPhaLPSSPE9T2Im hwwdbwZSyMehGu10k6w5nr7oHGgWD0BxyQc/uer7n6Y+agzFQvXyiy5cI2VJ7jwGm646C7KNHL9 ENReirt06ONqFxQ== 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 | 109 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 80601206961e5b2d682af5f7028434bba1604272..63f91635da187555b9096a63d6ee2c6df4fca071 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -933,3 +933,112 @@ 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[1..]), + _ => (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(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 4 12:02:12 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Andreas Hindborg X-Patchwork-Id: 13959038 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 09D7020DD6B; Tue, 4 Feb 2025 12:04: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=1738670697; cv=none; b=g9ecuQCfcAKB5o84+Qq+dJOcMlxnKPmpFV/Tl8XIg5CQRdMXskB1MxypJ1U/B+IGP9P5Lj0schAmq9VAs7iCj2DahYMj8qsL1jwCavBMLKocMcWzDx4vbq6cxmNFAGA+zK8j4V2cAHinBsHz4J1QgNS2YKuARFIbF3wFMY5MMnw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738670697; c=relaxed/simple; bh=ZXid7WqyFVPqqBScRL7NrGpk8FtE3ogwxkxbF/fqDBM=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=ScFhenKNI0/fJfnwIh999ROgV1XSHulPtST1cv8hLnfdDhCGaOSvd0hutsECeKPu7AhTtGPsjNBjz/TmFvFRI7aboGxYRA0xapi50WIQUratlFyAv5bw2WsbmwW3VKZ/jGU+Ez8iGlEUwyAtW5ngr7xmq6NqO3Mzyx7ddvF9JNw= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=NyVGurRm; 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="NyVGurRm" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 540A2C4CEDF; Tue, 4 Feb 2025 12:04:49 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1738670694; bh=ZXid7WqyFVPqqBScRL7NrGpk8FtE3ogwxkxbF/fqDBM=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=NyVGurRmHZIUJJyBGW6O4Q4wG4jSi11UH7fHPTH9Y1ufLQzKt/hzlLRowvpp3q1wR EDjQTbg4QCjaj2HUjguH0Gfwy2ncnmYwpXI4Zcj2hCww/qbD7DJq8lBheWb7/co544 T6iQjvxfjY2RRMRk4IfOA4O1diIhEm7/dj26vwUfEWDh6d9gV16WBeaisfDKxx9gE9 sjuk7Z73ive/9bB75ZPL3pqEEJzpfQ6RscHosmfHAQOaD7xgjKonWTWIox4hqraatJ QdybGwdrdlwbQdkXIA9z7BtmcutsF/wab9+iHAt8FvST1ZLErjHgqAOcVUH3/qUF02 oJ9t2jX17Y3eg== From: Andreas Hindborg Date: Tue, 04 Feb 2025 13:02:12 +0100 Subject: [PATCH v5 5/5] 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: <20250204-module-params-v3-v5-5-bf5ec2041625@kernel.org> References: <20250204-module-params-v3-v5-0-bf5ec2041625@kernel.org> In-Reply-To: <20250204-module-params-v3-v5-0-bf5ec2041625@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=23998; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=ZXid7WqyFVPqqBScRL7NrGpk8FtE3ogwxkxbF/fqDBM=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBnogHacM7SLgxg3nSN0Q+/YKJOvEyyf65aN6p0D NAM6OJROzqJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCZ6IB2gAKCRDhuBo+eShj dwIJD/wKwR+dCipr92fTx7WwVKIxQ6YMyZ8FEpWD0KBr+jVVIVthksFuT/JyDyRL97ETEEGUNM1 i7YkXW0iQX1R2+eNFGAB0IXHwT90s2GedvAChSRagi3dIhQGtahaWIEUHvLUC5Mc7aOPMWjGu4R XHnMGopQo5XQBkHXMzVnsCSOgo1cUDA2d2l7U0gy0pRRAvTi56+5/QdC8/KUV0E5BIQ88fa3/6O 4K1cFi8dIRD3EhQcbuFiEojDFUG0IYLv0/JcMnvO4RIKI0rAtV7DxfbydLDiBl8smg7Up0yEGDw tHfaAMselVevkSNlpEohfSfP5NC1aWwjIcEAwc8VcyghUIt1k3XbLArZX9Pzs0JE8P66u5YdcZo bOt1U798e3kXpFMFG+vrnPeCdDpxlXNSQIiOqj2KdiSWpNwnVyNRr6M+RtCSYoDrl0FR+ufVTN5 EO/O8+1gIVMw7B8lWdlJdY2O58JSYhEixSEz0nOnS+wWnpKWm3Ps5ShCjxhJgysLM/XQCC84y4F vYBqsOeGrUdkUtcglsBwgUkqZMEDVDmd9huhFhdlQwcoGu5cx9P+YXmmcWeCRPr/zzjvXehfeGH JpGn8dhSV34atMxUE505rDdh+MOdazyM2Gd2mCTHuxcyhraw+PiGezh5GmOYzdPfs9G6umewj5/ mZGIpp6MtDqTuLQ== 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 --- rust/kernel/lib.rs | 1 + rust/kernel/module_param.rs | 225 +++++++++++++++++++++++++++++++++++++++++++ rust/macros/helpers.rs | 14 +++ rust/macros/lib.rs | 31 ++++++ rust/macros/module.rs | 188 ++++++++++++++++++++++++++++++++---- samples/rust/rust_minimal.rs | 10 ++ 6 files changed, 451 insertions(+), 18 deletions(-) diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index ee48cf68c3111190e5827e8a11592946be5ade70..3d3b0d346b248a8fb30c4c1514fa798a65b3e899 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 0000000000000000000000000000000000000000..6c0f5691f33c00adbdc593a26377f5db2a528697 --- /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 563dcd2b7ace5e8322d0fddb409571cca2dd31ea..5efed578e3d5d851b460f83b29a4a95e2f106e64 100644 --- a/rust/macros/helpers.rs +++ b/rust/macros/helpers.rs @@ -107,6 +107,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 d61bc6a56425e97718518f727524de73c04e6153..2778292f8cee170f4e2c7d4f451ef9ea1329d18f 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 cdf94f4982dfc109ac5c7e9001897555de19d67e..be64f99599ec6dc84c5a845527b1658f6567a6c0 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,113 @@ 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 default = try_literal(param_it).expect("Expected default param value"); + assert_eq!(expect_punct(param_it), ','); + default +} + #[derive(Debug, Default)] struct ModuleInfo { type_: String, @@ -98,6 +199,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 +257,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 +286,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 +330,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 +511,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 4aaf117bf8e3c0cc77e188b1ad0708e3650a6654..d999a77c6eb9a0db9acf5fa03d4feca5e6525fc8 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)?;