From patchwork Tue Oct 1 14:59:50 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818234 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id B9825CEACDC for ; Tue, 1 Oct 2024 15:01:45 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 4100A680012; Tue, 1 Oct 2024 11:01:45 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 397AE280068; Tue, 1 Oct 2024 11:01:45 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 238DF680012; Tue, 1 Oct 2024 11:01:45 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0011.hostedemail.com [216.40.44.11]) by kanga.kvack.org (Postfix) with ESMTP id 01DF3280068 for ; Tue, 1 Oct 2024 11:01:44 -0400 (EDT) Received: from smtpin01.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay07.hostedemail.com (Postfix) with ESMTP id AD7F0161659 for ; Tue, 1 Oct 2024 15:01:44 +0000 (UTC) X-FDA: 82625347728.01.117CFE6 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf14.hostedemail.com (Postfix) with ESMTP id 17B3B10003E for ; Tue, 1 Oct 2024 15:01:38 +0000 (UTC) Authentication-Results: imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=f2MmSos8; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf14.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794805; a=rsa-sha256; cv=none; b=V6Eu3/gdlIHrdMLL5+Tj3UoakgWX5KYDwjjwtpuvkZX1tO62atGN6mKd8jgap+5jV3AawK /FdR2rXI+IkMVQ5WgnFr8how8YGsIbigemW0SLQEZP44P/OTR6M/ej0k158sk427dJqsWX wLGVViK7MmxSijLQKXS/5A8JnQeVdFM= ARC-Authentication-Results: i=1; imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=f2MmSos8; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf14.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794805; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=rHyFQBBk5RrGDk8w+tgTdk7ajuh4HCOorMplvVjfkmM=; b=PbT3pMukKMR+je4u566pUgdVfHS3zl8GJ/m9SlKDfpe1OB7gEJJKll1X90ZHwIh0Gz3tFM ggKjU9V10ei/NIfG2zOf6n+upmqgZ9wdsD6vf4eGy0K6qJBmfSXncFuYnSBlBWlCnXOyEz tH+PA2L6gAzPWSHxyvp1ooJquqMi2Hk= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id E53ADA40276; Tue, 1 Oct 2024 15:01:29 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 0317CC4CED4; Tue, 1 Oct 2024 15:01:32 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794897; bh=p24MKJcAJjQGLu5qkqjJ+M2DWuKlcDIgb3JoJfs9n3E=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=f2MmSos8vj270iKzg1Gd1ajTMn1iamxKzb6p6Kq7NIGGkGp+bd2EQjmTp2iiwAU9M OgfxOrLOq5lLJz2Eb6XY9YFUl9FNrYqBf7NsR2ebhpGoea959lfPbDAvA72PqerXBi Urq54dnJmsLqzHcjYKaYwfxUJjSVoDkJ1wa+8EdrQ2WfVwQXsHmu02sHOsXHgs3lKl tvKUCEzVWOvOK+MqTaU+J3GhmkBn3tP314jCa/8tmjJIT2k/IEF7k1UOG9vgzDhuwy dt63f5s4DYvjact7iJYzeMReTeRQbjaUjC4g6KXXpDPooIACjc65RgkDG50OXuIz2V 9kXt0QYmCngCA== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 15/29] rust: alloc: introduce `ArrayLayout` Date: Tue, 1 Oct 2024 16:59:50 +0200 Message-ID: <20241001150008.183102-16-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: 17B3B10003E X-Rspam-User: X-Rspamd-Server: rspam05 X-Stat-Signature: cxtjrja6ykzp3xok14y4eyj9doi1p4ow X-HE-Tag: 1727794898-206630 X-HE-Meta: U2FsdGVkX1/ZLD9WzE4aIVpcgtdcphXxWK7FI98pGRdJaH3Iwusl/35lgXga7KJ/QuMCkLsP51wFb4PcMvpmKZTQNZTPctIQDsUYQ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rr3EriXN+STQu5eNLEH+5ZR9tTm8ot/bUZm5TiGPAY20yIkUulPc5HkW6W+BV3e0CvAxdqgSmO45/eMZLPBIy/Q89YR6aJZIOVPnQSUIgBArvMi651szXXu/wzBSsaVw33Uz4vqUpnLA== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: From: Benno Lossin When allocating memory for arrays using allocators, the `Layout::array` function is typically used. It returns a result, since the given size might be too big. However, `Vec` and its iterators store their allocated capacity and thus they already did check that the size is not too big. The `ArrayLayout` type provides this exact behavior, as it can be infallibly converted into a `Layout`. Instead of a `usize` capacity, `Vec` and other similar array-storing types can use `ArrayLayout` instead. Signed-off-by: Benno Lossin Signed-off-by: Danilo Krummrich Reviewed-by: Gary Guo --- rust/kernel/alloc.rs | 1 + rust/kernel/alloc/layout.rs | 91 +++++++++++++++++++++++++++++++++++++ 2 files changed, 92 insertions(+) create mode 100644 rust/kernel/alloc/layout.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index ebe58247504f..bf143a71d53d 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -5,6 +5,7 @@ #[cfg(not(any(test, testlib)))] pub mod allocator; pub mod kbox; +pub mod layout; pub mod vec_ext; #[cfg(any(test, testlib))] diff --git a/rust/kernel/alloc/layout.rs b/rust/kernel/alloc/layout.rs new file mode 100644 index 000000000000..a9c987aad8fb --- /dev/null +++ b/rust/kernel/alloc/layout.rs @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Memory layout. +//! +//! Custom layout types extending or improving [`Layout`]. + +use core::{alloc::Layout, marker::PhantomData}; + +/// Error when constructing an [`ArrayLayout`]. +pub struct LayoutError; + +/// A layout for an array `[T; n]`. +/// +/// # Invariants +/// +/// - `len * size_of::() <= isize::MAX` +pub struct ArrayLayout { + len: usize, + _phantom: PhantomData T>, +} + +impl Clone for ArrayLayout { + fn clone(&self) -> Self { + *self + } +} +impl Copy for ArrayLayout {} + +const ISIZE_MAX: usize = isize::MAX as usize; + +impl ArrayLayout { + /// Creates a new layout for `[T; 0]`. + pub const fn empty() -> Self { + // INVARIANT: `0 * size_of::() <= isize::MAX` + Self { + len: 0, + _phantom: PhantomData, + } + } + + /// Creates a new layout for `[T; len]`. + /// + /// # Errors + /// + /// When `len * size_of::()` overflows or when `len * size_of::() > isize::MAX`. + pub const fn new(len: usize) -> Result { + match len.checked_mul(size_of::()) { + Some(len) if len <= ISIZE_MAX => { + // INVARIANT: we checked above that `len * size_of::() <= isize::MAX` + Ok(Self { + len, + _phantom: PhantomData, + }) + } + _ => Err(LayoutError), + } + } + + /// Creates a new layout for `[T; len]`. + /// + /// # Safety + /// + /// `len` must be a value, for which `len * size_of::() <= isize::MAX` is true. + pub unsafe fn new_unchecked(len: usize) -> Self { + // INVARIANT: By the safety requirements of this function + // `len * size_of::() <= isize::MAX`. + Self { + len, + _phantom: PhantomData, + } + } + + /// Returns the number of array elements represented by this layout. + pub const fn len(&self) -> usize { + self.len + } + + /// Returns `true` when no array elements are represented by this layout. + pub const fn is_empty(&self) -> bool { + self.len == 0 + } +} + +impl From> for Layout { + fn from(value: ArrayLayout) -> Self { + let res = Layout::array::(value.len); + // SAFETY: by the type invariant of `ArrayLayout` we have + // `len * size_of::() <= isize::MAX` and thus the result must be `Ok`. + unsafe { res.unwrap_unchecked() } + } +}