From patchwork Thu Jan 9 10:54:56 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Andreas Hindborg X-Patchwork-Id: 13932378 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 9E9012163AB; Thu, 9 Jan 2025 10:56:23 +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=1736420183; cv=none; b=Te0WTJRGJhNoOBH8K5moQ4zyTavhRC/3HdKvXS/4Ah+ECknz59nSe2dYcvBsfVn1ttjWz5K6ma4h+VJHy4YYZ3VSxym/DT8eg2eFJGL8mDSXqkKxEzq9wb/fKqQ6J2EyjciszWHOU0cVa3CNSJUBCx2jzoBvLA3+qVhDTcVATcU= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1736420183; c=relaxed/simple; bh=PQh7gi5LDDzekiROzXHh4yXB+03ry8mMFRR1lHgFddE=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=NwF+dazm26oQoFMj1ICVsAw7TaGeD6PSp7hMr2JkZ3zxinAarWcnB1g4jxCPSOWVA7+seky0ejZvUPk+E6fCU9rJm+NrYF8YS7Tq9KyRBWM4d7auyTGDRwsIGVEXQMtnrE+TEVGO1b3k4ZBggFD5nWwZOiIFGAyn+jO4lhFm008= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=pQvLR6TW; 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="pQvLR6TW" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 0E2C2C4CEE3; Thu, 9 Jan 2025 10:56:17 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1736420183; bh=PQh7gi5LDDzekiROzXHh4yXB+03ry8mMFRR1lHgFddE=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=pQvLR6TWBZC/+787SEbj9ZooTf0+5ICwODcmCiKu45dVdKlwBvvd8vhJ+Y3XC3+2x +4VFa72S6WB4Dqp9eXwY22oCx+grxoZgh9UkVhMP0kWkv82HErQw0NqfSAxi9/NwA1 rwfuDxWV2AU1UHsWfZ/zkpmqywnwii1H8PNNRiHpWv0zTR7cqpCUlVlRX0PVfUqXtW 6tpQpyeD8vwMcfpvxPbq0HaR0H88Yhwf8OBZ8SxFn4tPq1WL/6LKk9gYVs9QUV1CHu irYVN+nxfTeqQwhKKw6Rh/amHPd0PJWRMvhGSC5tfrcUxvjxL7oQL+iQsXOiXSSNwk eBg7U9LL1rHBA== From: Andreas Hindborg Date: Thu, 09 Jan 2025 11:54:56 +0100 Subject: [PATCH v4 1/4] rust: str: implement `PartialEq` for `BStr` Precedence: bulk X-Mailing-List: linux-modules@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Message-Id: <20250109-module-params-v3-v4-1-c208bcfbe11f@kernel.org> References: <20250109-module-params-v3-v4-0-c208bcfbe11f@kernel.org> In-Reply-To: <20250109-module-params-v3-v4-0-c208bcfbe11f@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=807; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=PQh7gi5LDDzekiROzXHh4yXB+03ry8mMFRR1lHgFddE=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBnf6sbwYSVWyBS99iiUpHpkpFCttvCoNsgE15Mf iMbCC14gZiJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCZ3+rGwAKCRDhuBo+eShj d6W9EAC0l+wvOATtCMVJZG/c3H02SYDJtr1PTlH+BCem0J6vXRo7sQvDDiY9RO85YNvYU1PAtHQ TxT2UAMjgE4n1GbBp5eppn8SCMPLXXZzshMmdhSdWYalIZvcIR4l0Wepg2qirDanIVflVVoZp72 REH5li5fkp8TI2WkPlCE4L/8qJmz64I+qrLJN1yF56BbMLUsBt7SNOiXDVPVz/Y0O7zjgl2VFnb 4zIzzLihE9dvYIBPtkoqw823ySLG9bRVquE92tD0NWQ7KSAI/9gCus8+N0r6kn4dqoHM/ISa6j1 6ioqqW6jseBwCOZWhsenzYYneEd+MONnpdOgyEg3zRMqvk9Lq/NnK3kXdaLmyGBgpa+wHoYGG/U 9pdHbrFArBvpbqKicNKwxNz0CfLGCPV2dVY6BwqT2YwHdY+NfOU6wh3NO0flIDUUPa/kfdW8nzP gfdtMuAjauzFI0iN8D4+LHsa2q3yoReyoU0nt8b9qAUJgsugMRuQDmPiTMGyc8QDQ3hBVK5QJrj CHPBUeAR4I5aI/FSMrxSclstlg2VTGa60CRHTzqKoB7DSqRvUcW+jJNPsx8OErhiVlbJ8c1DyAY gm3hEckNbP8AoO8myIM60neqSn7smyakAWzNKjam9hSxBO3rVYJl0XDOtBivkpdGJ+W4JqLD3Yr EETeBePiIX5vCAw== 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 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 d04c12a1426d1c1edeb88325bcd9c63bf45f9b60..c441acf76ebd1f14919b6d233edffbbbbf944619 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -106,6 +106,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 Thu Jan 9 10:54:57 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Andreas Hindborg X-Patchwork-Id: 13932377 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 693B02165F8; Thu, 9 Jan 2025 10:56: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=1736420177; cv=none; b=jJ/2EZCAZnu1uZChYafxptBlCHaCw3ibmA5f2hu/GMIqaASxAHOPwTvBqUeLttBClgNr4e+DQ8W5ypLsVaYC+G4oCuY61aaWG6xojQ7HZ1cack/eXJUDhc1Lbge2qO5NScFqRjqX9hJsi5rgJgLHtSHRRZK1zdJhClK12P9CT3A= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1736420177; c=relaxed/simple; bh=W1dON2DXJk8wtFufY6Ee10/Ghnqv3HpHBRkp7n4UJys=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=PQmexMnp9vRMY1LyH48vcSbqdaUGuXuXGPhQGMWKLhXC0r/3nef8Vd2IViwtfPSTd2ypW1ueYPryI5to6DhCohIDEwYqnZPW4t7ioMAT+984t9gEZNi3PgcqqVtauB2lxvsg2geP5Az+N6nxbw8ebaE/V9UAVbIXdenZASF2RFo= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=T4qnPb6v; 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="T4qnPb6v" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 0550CC4CED2; Thu, 9 Jan 2025 10:56:11 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1736420177; bh=W1dON2DXJk8wtFufY6Ee10/Ghnqv3HpHBRkp7n4UJys=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=T4qnPb6vB/g1dsmadqbnLZhAItE155FvmUe5rcVZhNVhj4Tw8q2S00nADb4yD0DOY vDip/XWXBTT4M98afS6yccHYaR1bQTJlHkUaKnujJ2jCxKB12dC9leLXuwSau+joVT GVLogd8OnxRKvn5qosmjAW0aqt6yUnGT6IMSq/QS1jB61ZIjhb0FQqJVTaDeet2bcv SUNH5xbJIh1kTVxFAJ1tGSfgP/3pJ3eHuZYFt1dD07hPdUuk8X4KNERKshIlpmJLm3 0k3cEUzYHyiHM79xPrYoSTWbXo047sE8J3pA+LgBQBadNwVD3CfswQRXUjtVpY6eps ojt1zlzC8cHDA== From: Andreas Hindborg Date: Thu, 09 Jan 2025 11:54:57 +0100 Subject: [PATCH v4 2/4] rust: str: implement `strip_prefix` for `BStr` Precedence: bulk X-Mailing-List: linux-modules@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Message-Id: <20250109-module-params-v3-v4-2-c208bcfbe11f@kernel.org> References: <20250109-module-params-v3-v4-0-c208bcfbe11f@kernel.org> In-Reply-To: <20250109-module-params-v3-v4-0-c208bcfbe11f@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=1549; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=W1dON2DXJk8wtFufY6Ee10/Ghnqv3HpHBRkp7n4UJys=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBnf6scMkN4yyIsQKfHYtE7Al2bfHy2wfNu9D8ai +9Xuiiwk0SJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCZ3+rHAAKCRDhuBo+eShj d6D5D/sGR3bbD9c3YL8rsKzAGrmOoApL8g450ceqj5RihPxAEICAWXQKJY82B4RxcmLMSVoIYue SYsgzGIP4Mb5llS5wE5vUj8Ljhfd4GYyVKshNgXua1Hb4cQnib8EEKRaNR18gFCAS7q6yYbpjKl W6X6X++BSNZKj1DPEogwBwSguRXyykWtGs94NxLAwQax5kInqfNrkbjWk2c8dl62GybHpdKyaiU iP3PUxhgJhzr4ZQYVERzjCbHOA5xU6kOoXgaqtymfZGEigZHgsVgMwFjG8iL0w8ZsITGtvb6fuK jQQlyOkJv37q0b2bZVL+8axUnDc4Z8lapm3Ziz+uBinsqC5W2j/zE5b2f8iQ6klW6nBGIlvhP1S 4h0FslaOZvdAMFF06vbHeUmqepS6rJtVt9WgzRT09ethVrEX/hW2duf7O3EI1CU8JrT0Zkp/PiO mi7PKMXkzVtxgBgXhBxN8bsfVH1Q1QaPTOsBKbE3RpE9jtagCMAxEI4r+iToQyNQROqGl/LfCmE 5kBKw5VDFREBXAIh/NG1yoyyRh2SzcAO1QLX6TitdfGPbe2jNOE2LV00DYrTldZjNiaM3ppvEqn pxwSUPPi7ossxIHh6YV1eNxbmyLbg5m6oObq5WwZNrNK2T6z/HTi646tvh+vocxr/lZCiRaBgbv fDlwfrlVHd6Jc+w== 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]`. 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 c441acf76ebd1f14919b6d233edffbbbbf944619..9c446ff1ad7adba7ca09a5ae9df00fd369a32899 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 Thu Jan 9 10:54:58 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Andreas Hindborg X-Patchwork-Id: 13932375 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 02D50215F40; Thu, 9 Jan 2025 10:56: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=1736420167; cv=none; b=LQK7j1sy/XqK/ex1z92fOlQlRAuMk4anVbM6DUUr3s0XMqzeyya8T02XB94fAEPAp/XqjA+GnaDXijNO2ZehO1+661XFuYOTv8inFGTHs5aUNW3A8E0W98GqsbGAyQRBIvImzaFPt+Rcw8PvbY6BgEtcCx7cQK7ES7jFZO9qK9o= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1736420167; c=relaxed/simple; bh=9Jvtzmz9CGw5UkzzEbTj5597T6hycLzFVKCBbyGKOEk=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=RrVsyoH72P/wVrrMJyby3yacKjUgxS+OgzzFNgBAMiAGSZ5Pla1HslfzLDegJbTZSsW9t7Tk2o8Gewg8oe/q8jc+cDsLkBL0jd6On6/a1x7Z+eUdRisiseYawwSY0VFboWkxaWBTIVulaeXpvd4MOKgYs20mUQT7QykNPZQs8RA= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=r5UYGQG8; 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="r5UYGQG8" Received: by smtp.kernel.org (Postfix) with ESMTPSA id D56E4C4CED2; Thu, 9 Jan 2025 10:56:00 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1736420165; bh=9Jvtzmz9CGw5UkzzEbTj5597T6hycLzFVKCBbyGKOEk=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=r5UYGQG8di552obmkiy9rdYVHTf29MxWBw3eLLOghWPCMW8uxWneIZh6zCCN1831N pVUHI3tDFQDMK7jtC9klQNMhwlf9gftjqu8oVq5u/oO4sXB/JH4QC7z5gpJyFiKNYV u2tQq6XzYmnHcDbC3V0IRjk9xCQzLXmNMudtZ8BI1Yd0/wXs8WzCeRQfAVxJr27rQ7 zHDN4JrgRTnChtdhnrNHY0BNtRDrEUlnKT9PsPKUN6o6aaQHbV/qUaF8F4+3ZT/T7+ OW968HTu7lhrjPFWnzMWA07+YwMVKrKfOUrqIVOScDI1XbFnSu6yFGlLM42M6ekHKh AKuqncLG70gdw== From: Andreas Hindborg Date: Thu, 09 Jan 2025 11:54:58 +0100 Subject: [PATCH v4 3/4] rust: str: add radix prefixed integer parsing functions Precedence: bulk X-Mailing-List: linux-modules@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Message-Id: <20250109-module-params-v3-v4-3-c208bcfbe11f@kernel.org> References: <20250109-module-params-v3-v4-0-c208bcfbe11f@kernel.org> In-Reply-To: <20250109-module-params-v3-v4-0-c208bcfbe11f@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=5660; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=9Jvtzmz9CGw5UkzzEbTj5597T6hycLzFVKCBbyGKOEk=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBnf6sdQD7nrP2TPEcZDOjSuKs9q9tpFSF+rDJEs SUl+cPb7a6JAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCZ3+rHQAKCRDhuBo+eShj d6LaD/4iARaBgUcCEuuwbzwPSloqofsU0Z6q1uy83BH9OyuYBDhDySvGDLGoOPH3GsVVdbmEdYP j4C99RDa9AeDEAsHK70RvjY/uk6qps4CQlv7p2Jo8dUtDBzPDphbLc4vNJcz+6ZCMsmDVq4cDSo 1DE/CG/r+a4s34YnRXYmATVYwlk8ahBUekKa9us3SJGfJAc+iLlG94QaTQ+kP+/ZVR3gZet2Y0L NAcpdJa3/xZ847LvMneLeXxQ1netBRneRpvQax0leTyF9/fdN/Efqv048ArGuGV+fu2feQiy/hz zRBhoLnx5xI0N2UfqxIech7NMhFG9QWhWij9o/2gjvPYSYiWCPt/LxdsrKSxjQLXSbKIgiM0Ebq 1BAWYmsuagDin2+u7xkk0D3HHIL9vIsRhPlaqhwVKSUdtbY4Xz6NqOQEihrc6I4qFsmG5HZVJoU 0IcSISd8ejr+Ap3MSMckkhjLJjP8WERT4casru0ccdkWCm6jTVu+XABxolo2+ZodTIsVRHrsikN 5ucNew0/sEuJ4A6aDTq35tMulQ3uCzbX22HsvsJZP8M78AsiLvhnh5bjox6FII4dBJ1doKxBOL5 zFRKRjItkB1qqSFsNmkMurwfFcxeQRRZs2mPfaCrJgDyPZLSXFfFtRaObkElhGlhlOutA8meNe3 PHljkXwhjst3JDg== 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 | 118 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 118 insertions(+) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 9c446ff1ad7adba7ca09a5ae9df00fd369a32899..14da40213f9eafa07a104eba3129efe07c8343f3 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -914,3 +914,121 @@ 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; + + /// 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) { + if let Some(n) = src.strip_prefix(b_str!("0x")) { + (16, n) + } else if let Some(n) = src.strip_prefix(b_str!("0X")) { + (16, n) + } else if let Some(n) = src.strip_prefix(b_str!("0o")) { + (8, n) + } else if let Some(n) = src.strip_prefix(b_str!("0O")) { + (8, n) + } else if let Some(n) = src.strip_prefix(b_str!("0b")) { + (2, n) + } else if let Some(n) = src.strip_prefix(b_str!("0B")) { + (2, n) + } else if let Some(n) = src.strip_prefix(b_str!("0")) { + (8, n) + } else { + (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 Thu Jan 9 10:54:59 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Andreas Hindborg X-Patchwork-Id: 13932376 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 B2584215F40; Thu, 9 Jan 2025 10:56: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=1736420171; cv=none; b=uvcqEBKRIBA8yFvfyouuGyX45XI1ZKZrqdS3+vI+K8bcAyp+6zis5Z5/H0d8hLI72SsD8WIdfGQNDv6ki+3d6LzId/aaIKdKk2EbymQArHvDgO2HYvGr1rnAifHJzQcVUBWGddpxsUeSW1Qd6PpAig1OOhPKNXa2S80RByZKieM= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1736420171; c=relaxed/simple; bh=JI2hJURbSmYd5Qh12/YrHYDHG4B5yp27TFTmQO+faec=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=vDtff+0J/jT4I2ORBGP+sd8LTD1cQohEUkaiteT01UWvBTHeHnzwg1aFe8yfQC8N0Mkb3xWNUxFU5crdsgmnENHUdxRnjItt9lp1lrAcaVGHNP58yP8ruggx5V6oYpFuXWoDQeP0lE3u7QByYu5fN9O8ny2pUdScRHZh0lBri5g= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=D+DSsp96; 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="D+DSsp96" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 3EA3DC4CEDF; Thu, 9 Jan 2025 10:56:06 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1736420171; bh=JI2hJURbSmYd5Qh12/YrHYDHG4B5yp27TFTmQO+faec=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=D+DSsp96gQi3PtdgG+JAZQaaU1+vpg929kSh0JIfIybxIt7bMQTQk9fwO3iD8ajtD zdIvuS+fc5+eU3jg0gvBbWj37d2RdfSj/vZ13bIS7pY/OsVaRA5r8FwYp7eMS11i/J wUkTmbarSGuTgHqZdeE0t2gUXQegAk/wXrKochAFECvT7xV+Y8F4OdPYFMT7hyXAEG Jh3AkZt6MxViJXclIg9RioussFnV1NkEATZaGi8g6nTfHXjpMUneZTtgNJ+FmlJ7sd TE0n7PQHtIWOGwD7PbWFIViZYLZObJNLSDpU4Oj426OYANMqHD4k5HufFjHS6EW1G/ 3g/mcRgOg7yUQ== From: Andreas Hindborg Date: Thu, 09 Jan 2025 11:54:59 +0100 Subject: [PATCH v4 4/4] rust: add parameter support to the `module!` macro Precedence: bulk X-Mailing-List: linux-modules@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Message-Id: <20250109-module-params-v3-v4-4-c208bcfbe11f@kernel.org> References: <20250109-module-params-v3-v4-0-c208bcfbe11f@kernel.org> In-Reply-To: <20250109-module-params-v3-v4-0-c208bcfbe11f@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=23928; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=JI2hJURbSmYd5Qh12/YrHYDHG4B5yp27TFTmQO+faec=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBnf6seKBNpPUMjCT8VUod2yY6CioxVw7AKAw4Hp l5j/6ZjdGyJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCZ3+rHgAKCRDhuBo+eShj dwR3D/wPX9zUjJhZqMjzjQL8pzSQJUUz53SfcnJMG37GRU2aBJV0PVCNBP5Nc0ecEamrXZvfmi1 LkAduNpU3jTw4juhk6SqUpBm7RTrktqFGPPf0pCIDMqTKhuYbpis7jHhyhoTHX+DFWEP65EBXAC +BAUP5xhGBylVpftyjI3M3a1GUr5VFRz8lmc1+1MJQhGklrH+GuBijyBN5KVdoyT4gpP2jTlDQ/ fi75aodbY0NUGD3x0ewuEaNp7a4rtgjjlf2fOyZHoSUhTaO18YXKfteojdtlmk985kfsSfdUW/R myU8xjDJ9uBo0vddDoxHTckWLaJ5yPQc7WzvyHcSC2yqZxArHh/o5V0QD9toTMWS4kI+cW3ElhM 3O2dtkZz1Y/3fWO6meEelzd8pS2bKhg8pXTiVW6hUfOxkyXej/HCOZbF06Vy5TQBVFIkfnMzIKI k88RKHnZSlbtvVWW5KqrziDnjBz/1MwjzOtryITr3vjh/1tzMF3zmYdgpjmCt7wxsXEkVqjmJn8 aTk/q8iZBwXw4COFsweRwBDuArsHNqS3iRgoqSzuJASj2/J377y6375IeyiNC9SbltnF8aQ7WNU wiUTXziXGLGlpGaFB/K2o3rCfHbsyBFkKx6BTFJxSpdbUV59A86X74NDOhSSKbL4jBRDsGCSh5b H9tSfmlOfPKwkeQ== 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 4253c9a7fe7df935dc714bc3036d299bd80054a0..707ec81411c7aecccdd14e02cbf011642bc02e07 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -46,6 +46,7 @@ pub mod kunit; pub mod list; pub mod miscdevice; +pub mod module_param; #[cfg(CONFIG_NET)] pub mod net; pub mod once_lite; diff --git a/rust/kernel/module_param.rs b/rust/kernel/module_param.rs new file mode 100644 index 0000000000000000000000000000000000000000..6cb64096090a37c4f9c4ce73e23b7ac049e32d20 --- /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 core::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, an + // 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 4ab94e44adfe3206faad159e81417ea41a35815b..0fe581fbc53266bf22fe07f5c35495affbe0d67d 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 2587f41b0d3929af7ceac5f42b4711f70b4f8749..627279cf318b14b50128045bce980f9d60b9c6d0 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) {{ + c\"{module_name}.{param_name}\" + }} else {{ + c\"{param_name}\" + }}.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!( " @@ -358,14 +507,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)?;