From patchwork Wed Apr 5 19:36:35 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: y86-dev X-Patchwork-Id: 79885 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a59:b0ea:0:b0:3b6:4342:cba0 with SMTP id b10csp551020vqo; Wed, 5 Apr 2023 12:48:30 -0700 (PDT) X-Google-Smtp-Source: AKy350aawY+RnoBz5tBz/TfMIHJB4APi34MbsCVy+uTPCOfvbZB3IQb6pTb6LzgXEv2poZ2OFjPH X-Received: by 2002:a17:906:6d09:b0:930:e634:3d52 with SMTP id m9-20020a1709066d0900b00930e6343d52mr3768524ejr.24.1680724110110; Wed, 05 Apr 2023 12:48:30 -0700 (PDT) ARC-Seal: i=1; a=rsa-sha256; t=1680724110; cv=none; d=google.com; s=arc-20160816; b=d+K7xvibNpoWDXz/3O6EhjNNTXqccTgxI/CKjPPTyaN0HwxYuLtCW6zRi8iyNZv9cl gdQtHw3BBYySHmjdraAr88NcfwBHCsKOZEhc1SsfdjypeB6WfLmQ+MgvlBxpnONKSIKW rkFsgFhUVDp/JXRhRWoBpoanomTp3DwABxce7nkHKU0Zi2nMua5btIvMCJtc4XDfZqkt qcU7ZmfkxWcys55h19w7mucKKAJsN5i+p9RTh5AAW26bf0wbR0uof0xGJjnXhP73bjKP q2EnDZqf1vTpkfjU2KMgFa1EYVetzhgz1LMaKCgZ3qzmpcBywivrDFd8r+cauyqb8JM8 gWkA== 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:references:in-reply-to:message-id:subject:cc:from:to :dkim-signature:date; bh=rQ0nPIiJCYuONUdlBX7Jess/7/le2Ye/jbd2l3BM7gs=; b=gBsf3CwhNFQolwaMYocUFDZI54zTH7UcpsN2IFluKkOSkQhVbgZovNhJVbxTx3sLpC YlpFQKHtqVGPEkKPKnJuq780b1Q7VoAxpDD/b+a6PxoXB0ZgNWU/emgPC7Wox6s0Zn0b GOgFr7SCfvNivQXclVrlFnNWXLIEmmX2he8Mk1eVUyXeoawTSchvXucgw8WrGo8CyogZ 2fVJdpF5uR2wCBD4YbCBSn1v2wKG1O5eh4XjU6G1LwVsvjJ2bsbfy0XQ2dUkzDXTf+Px LxlYHb/WSnJtGJmY0EJrOXmJV6L7jBMVHD51ItVuqt4CqAJHICO9MALYQYyfdbvZFogx PP3A== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@protonmail.com header.s=protonmail3 header.b=OB0cXCAT; 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: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id n2-20020a170906088200b008d89608d4a2si4644622eje.204.2023.04.05.12.48.05; Wed, 05 Apr 2023 12:48:30 -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=OB0cXCAT; 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 S234244AbjDETho (ORCPT + 99 others); Wed, 5 Apr 2023 15:37:44 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:56660 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S233978AbjDETh0 (ORCPT ); Wed, 5 Apr 2023 15:37:26 -0400 Received: from mail-40131.protonmail.ch (mail-40131.protonmail.ch [185.70.40.131]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 725AE6E87 for ; Wed, 5 Apr 2023 12:36:55 -0700 (PDT) Date: Wed, 05 Apr 2023 19:36:35 +0000 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=protonmail.com; s=protonmail3; t=1680723402; x=1680982602; bh=rQ0nPIiJCYuONUdlBX7Jess/7/le2Ye/jbd2l3BM7gs=; h=Date:To:From:Cc:Subject:Message-ID:In-Reply-To:References: Feedback-ID:From:To:Cc:Date:Subject:Reply-To:Feedback-ID: Message-ID:BIMI-Selector; b=OB0cXCAT8KPyh5sJqZD72dctiecqZyhcJtXqtwTwilCoqreMC86SP4Re43jRS5Vn3 QjJhcsB9M2T5QUUTdd4WlUrSMXCfntEnaOBS5bBmcXqC/KX0QZhv0/rauQFB4uzvbg sbtLjGd67ARDpv6WJ046BmTO91lGZmsrQVxO+bHQq86uH+Ox1LaX8F0OZdnoNDfWiU x7W6oB/F/zophz0Ev/5F7eKaQL2d/zYeUFRJ+t82ZOgKbEt3zrKBvrT+n+eStdpDG4 nYJ+2vS2QT50GaNsFpjeZkSP1hmMA8LNvqQlJxpBrubTxcpK5cy7NwalDvK/pKJU6C aFFGzSj8OpQhg== To: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Alice Ryhl , Andreas Hindborg From: Benno Lossin Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev, Benno Lossin , Alice Ryhl , Andreas Hindborg Subject: [PATCH v6 11/15] rust: init: add `Zeroable` trait and `init::zeroed` function Message-ID: <20230405193445.745024-12-y86-dev@protonmail.com> In-Reply-To: <20230405193445.745024-1-y86-dev@protonmail.com> References: <20230405193445.745024-1-y86-dev@protonmail.com> Feedback-ID: 40624463:user:proton MIME-Version: 1.0 X-Spam-Status: No, score=-0.2 required=5.0 tests=DKIM_SIGNED,DKIM_VALID, DKIM_VALID_AU,DKIM_VALID_EF,FREEMAIL_FROM,RCVD_IN_MSPIKE_H2, SPF_HELO_PASS,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 X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1762366964363016314?= X-GMAIL-MSGID: =?utf-8?q?1762366964363016314?= 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 Reviewed-by: Alice Ryhl Reviewed-by: Gary Guo Cc: Andreas Hindborg Reviewed-by: Andreas Hindborg --- rust/kernel/init.rs | 97 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 95 insertions(+), 2 deletions(-) -- 2.39.2 diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index 99751375e7c8..ffd539e2f5ef 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::PhantomData, mem::MaybeUninit, - pin::Pin, ptr, + alloc::AllocError, + cell::Cell, + convert::Infallible, + marker::PhantomData, + mem::MaybeUninit, + num::*, + pin::Pin, + ptr::{self, NonNull}, }; #[doc(hidden)] @@ -1323,3 +1329,90 @@ pub unsafe trait PinnedDrop: __internal::HasPinData { /// automatically. fn drop(self: Pin<&mut Self>, only_call_from_drop: __internal::OnlyCallFromDrop); } + +/// 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 this type. In other words, +/// this is not UB: +/// +/// ```rust,ignore +/// let val: Self = 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 pattern 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, )*) => { + $(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 optimization guarantee). + Option, Option, Option, Option, + Option, Option, + Option, Option, Option, Option, + Option, Option, + + // SAFETY: All zeros is equivalent to `None` (option layout optimization 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 pointers is not allowed to be + // null. + // + // When `Pointee` gets stabilized, we could use + // `T: ?Sized where ::Metadata: Zeroable` + {} *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 { + ($(,)?) => {}; + ($first:ident, $($t:ident),* $(,)?) => { + // SAFETY: All elements are zeroable and padding can be zero. + unsafe impl<$first: Zeroable, $($t: Zeroable),*> Zeroable for ($first, $($t),*) {} + impl_tuple_zeroable!($($t),* ,); + } +} + +impl_tuple_zeroable!(A, B, C, D, E, F, G, H, I, J);