Received: by 2002:a05:6358:11c7:b0:104:8066:f915 with SMTP id i7csp1683250rwl; Fri, 31 Mar 2023 15:13:16 -0700 (PDT) X-Google-Smtp-Source: AKy350YvKm6Dfh9MQs1k5wvNXNPqXtZ2NRgLQENSzKP4cCls2E64Pdrjq2JEzH5I7gRphQavkB3o X-Received: by 2002:a17:906:207:b0:933:23c4:820b with SMTP id 7-20020a170906020700b0093323c4820bmr6096481ejd.4.1680300796417; Fri, 31 Mar 2023 15:13:16 -0700 (PDT) ARC-Seal: i=1; a=rsa-sha256; t=1680300796; cv=none; d=google.com; s=arc-20160816; b=mlL5y1PUFVh5qurUkwmSRBviLMrOlEZevOdSo+V3wCvbbsU3XAA5WBo8O/JexbxtpD 6JX3NfvJ9Wooz85DDwN6mwcNRkO84JhrEWla8lbCX+FbAMm/0/5e3etMSJFlSxEPgljk YeUR4DQ+3UiD0Cq0XBFvJsv9lUyaeIg9Wo/Mne/9iAymLotmEmxHwsbo9eR5oIRpnDKT 9h1zhdF3GNpS1twpoh86IkHTxP5wwFV6JSLf8X+8xADp9HtPx9TrLhdlbsMaqLPsUvpo +kVY1wGHB8+4McFbdbS14LMRA2B7Rtyw/+3xAXI8EaYxzG5YD0WtcSRAmRwfCfumJ+VH MOcA== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :feedback-id:message-id:subject:cc:from:to:dkim-signature:date; bh=tbeoCLL5wBqVLfIxQMLYa/pwVZdYzKbff0TZ81OcW1Y=; b=dVuDzfjdwY+GHPaycv215f6rgtmKtCazju8n9KloVoPqAlkI7wvQJ9g8AVLL3JRo43 LIlpv4R/g4QKaNreYW69dw6i68EkQ0rjvFlRNBnx4DOWN6k+/ZvZs6WkPZy7QtTLi11V lmWIUxNYqLtH4GxkO53OhzUISx7IgAt3JBDlSckc5SvB8a4Q/YH2jh7dODXvbqF3pznX oo3rRapnRYQIxjbaXqCtWuQMA7V5mvEPnDNzlgOvLnI1xQ7WhmCbs721iKd2ISii2caR WoQyKfN6UeE967gWrAG6jxZWc8g7CdoH7G2tuuXNpmYhxSrIFw7FzFkQkXwIfvDYYUib 0z7g== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@protonmail.com header.s=protonmail3 header.b=Wkj2CPI+; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=QUARANTINE sp=QUARANTINE dis=NONE) header.from=protonmail.com Return-Path: Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id bl23-20020a170906c25700b0092421451065si2668552ejb.902.2023.03.31.15.12.51; Fri, 31 Mar 2023 15:13:16 -0700 (PDT) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@protonmail.com header.s=protonmail3 header.b=Wkj2CPI+; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=QUARANTINE sp=QUARANTINE dis=NONE) header.from=protonmail.com Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S229850AbjCaV5B (ORCPT + 99 others); Fri, 31 Mar 2023 17:57:01 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:51584 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S233258AbjCaV4z (ORCPT ); Fri, 31 Mar 2023 17:56:55 -0400 Received: from mail-0201.mail-europe.com (mail-0201.mail-europe.com [51.77.79.158]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id F2DA618F9A; Fri, 31 Mar 2023 14:56:22 -0700 (PDT) Date: Fri, 31 Mar 2023 21:54:04 +0000 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=protonmail.com; s=protonmail3; t=1680299654; x=1680558854; bh=tbeoCLL5wBqVLfIxQMLYa/pwVZdYzKbff0TZ81OcW1Y=; h=Date:To:From:Cc:Subject:Message-ID:Feedback-ID:From:To:Cc:Date: Subject:Reply-To:Feedback-ID:Message-ID:BIMI-Selector; b=Wkj2CPI+CxUz9qnTXoJ0BESJfECV+o263NE7aT9uB162R0xjR8Jo70mF3KabF9QyP 27jouhyKuFefarQoMzF1T0hXOsAD+2r7BCMI7d7VwiGGOQ+9YcKyWLiRWzGiYxjhSt Hl/mHsetRwFDTHJVF6XH14lzZjPTqtiDDgEY2ZKHlc3LUprzztDkxOYnSn2ZAL5Rwf nCe4wgLcH92pX61a692W0nSCMb07ghH0Te5l+peVZ8A6kC/TnZ3mVMzCZDsr0BmJjw 2Z0Y3aNdbILTFWDYlmlEHTn1KHLCZUEBe/rAdA7IRq8nF7Jv3SIDW/nJYrUb9Rnl2o k9PtLPfNM61Ug== To: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , =?utf-8?Q?Bj=C3=B6rn_Roy_Baron?= , Alice Ryhl From: y86-dev@protonmail.com Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev, Benno Lossin , Alice Ryhl , Andreas Hindborg Subject: [PATCH v4 11/15] rust: init: add `Zeroable` trait and `init::zeroed` function Message-ID: <20230331215053.585759-12-y86-dev@protonmail.com> Feedback-ID: 40624463:user:proton MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: quoted-printable X-Spam-Status: No, score=-0.9 required=5.0 tests=DKIM_SIGNED,DKIM_VALID, DKIM_VALID_AU,DKIM_VALID_EF,FREEMAIL_FROM,RCVD_IN_DNSWL_LOW, SPF_HELO_NONE,SPF_PASS autolearn=unavailable autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org From: Benno Lossin Add the `Zeroable` trait which marks types that can be initialized by writing `0x00` to every byte of the type. Also add the `init::zeroed` function that creates an initializer for a `Zeroable` type that writes `0x00` to every byte. Signed-off-by: Benno Lossin Cc: Gary Guo Cc: Alice Ryhl Cc: Andreas Hindborg --- rust/kernel/init.rs | 94 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 92 insertions(+), 2 deletions(-) diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index 5661f30bb0e4..fef14c3c0642 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -195,8 +195,14 @@ use crate::{ }; use alloc::boxed::Box; use core::{ - alloc::AllocError, cell::Cell, convert::Infallible, marker::PhantomDat= a, mem::MaybeUninit, - pin::Pin, ptr, + alloc::AllocError, + cell::Cell, + convert::Infallible, + marker::PhantomData, + mem::MaybeUninit, + num::*, + pin::Pin, + ptr::{self, NonNull}, }; #[doc(hidden)] @@ -1328,3 +1334,87 @@ pub unsafe trait PinnedDrop: __internal::HasPinData = { /// automatically. fn drop(self: Pin<&mut Self>, only_call_from_drop: __internal::OnlyCal= lFromDrop); } + +/// Marker trait for types that can be initialized by writing just zeroes. +/// +/// # Safety +/// +/// The bit pattern consisting of only zeroes is a valid bit pattern for t= his type. In other words, +/// this is not UB: +/// +/// ```rust,ignore +/// let val: Self =3D unsafe { core::mem::zeroed() }; +/// ``` +pub unsafe trait Zeroable {} + +/// Create a new zeroed T. +/// +/// The returned initializer will write `0x00` to every byte of the given = `slot`. +#[inline] +pub fn zeroed() -> impl Init { + // SAFETY: Because `T: Zeroable`, all bytes zero is a valid bit patter= n for `T` + // and because we write all zeroes, the memory is initialized. + unsafe { + init_from_closure(|slot: *mut T| { + slot.write_bytes(0, 1); + Ok(()) + }) + } +} + +macro_rules! impl_zeroable { + ($($({$($generics:tt)*})? $t:ty, )*) =3D> { + $(unsafe impl$($($generics)*)? Zeroable for $t {})* + }; +} + +impl_zeroable! { + // SAFETY: All primitives that are allowed to be zero. + bool, + char, + u8, u16, u32, u64, u128, usize, + i8, i16, i32, i64, i128, isize, + f32, f64, + + // SAFETY: These are ZSTs, there is nothing to zero. + {} PhantomData, core::marker::PhantomPinned, Infallible,= (), + + // SAFETY: Type is allowed to take any value, including all zeros. + {} MaybeUninit, + + // SAFETY: All zeros is equivalent to `None` (option layout optimizati= on guarantee). + Option, Option, Option, Option, + Option, Option, + Option, Option, Option, Option, + Option, Option, + + // SAFETY: All zeros is equivalent to `None` (option layout optimizati= on guarantee). + // + // In this case we are allowed to use `T: ?Sized`, since all zeros is = the `None` variant. + {} Option>, + {} Option>, + + // SAFETY: `null` pointer is valid. + // + // We cannot use `T: ?Sized`, since the VTABLE pointer part of fat poi= nters is not allowed to be + // null. + {} *mut T, {} *const T, + + // SAFETY: `null` pointer is valid and the metadata part of these fat = pointers is allowed to be + // zero. + {} *mut [T], {} *const [T], *mut str, *const str, + + // SAFETY: `T` is `Zeroable`. + {} [T; N], {} Wrapping, +} + +macro_rules! impl_tuple_zeroable { + ($(,)?) =3D> {}; + ($first:ident, $($t:ident),* $(,)?) =3D> { + // SAFETY: All elements are zeroable and padding can be zero. + unsafe impl<$first: Zeroable, $($t: Zeroable),*> Zeroable for ($fi= rst, $($t),*) {} + impl_tuple_zeroable!($($t),* ,); + } +} + +impl_tuple_zeroable!(A, B, C, D, E, F, G, H, I, J); -- 2.39.2