From patchwork Fri Mar 31 21:54:04 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: y86-dev X-Patchwork-Id: 78024 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a59:b0ea:0:b0:3b6:4342:cba0 with SMTP id b10csp878002vqo; Fri, 31 Mar 2023 15:27:35 -0700 (PDT) X-Google-Smtp-Source: AKy350Y2yxqCIYYPYsJZuDfn/UwfdEbqaEVbXqlcVJovOe3xvQfQwkdL9GNeY/QX/+rl23p4EyDf X-Received: by 2002:a17:902:fa46:b0:1a0:514c:c2d2 with SMTP id lb6-20020a170902fa4600b001a0514cc2d2mr25032871plb.68.1680301655098; Fri, 31 Mar 2023 15:27:35 -0700 (PDT) ARC-Seal: i=1; a=rsa-sha256; t=1680301655; cv=none; d=google.com; s=arc-20160816; b=nbLwQcUbsi4Hda7UmjNIKgZk47q3Z4aBUdc/U55pEXrRPEBtus054l2jQST0lgQ6// suSyCe+TQWkABmoxYPN7VXpUlArxyT8Fvb9gqHT/NMcgE7q3C87rOcJdIvtnTNxFswxr N23eht26WrJs/H8Ub2pS6QU6SVOJQuUKq4OQeswLAu5m62CVREnxhyEKOGegppA0tX1i whPtzr0kiRC2h1Cfrkux1NqAJ3aR2K5TIO/yl5eFjjn0oyvrnzu+SEeGWTjL/46gurt6 jq5hSuoJdH1E9oeEDqaEJfoz4Mq4LiEbwhmv8lSJ4WwifU9aWxzda6Zr/c26yH1DS2q7 LI7A== 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 Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id u17-20020a170902e81100b001a05d12eeb3si3638295plg.189.2023.03.31.15.27.23; Fri, 31 Mar 2023 15:27:35 -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 S233302AbjCaV5B (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 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 X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1761923988691630985?= X-GMAIL-MSGID: =?utf-8?q?1761923988691630985?= 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(-) -- 2.39.2 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::PhantomData, 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::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. + {} *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);