From patchwork Thu Jan 19 17:40:32 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Wedson Almeida Filho X-Patchwork-Id: 45878 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:eb09:0:0:0:0:0 with SMTP id s9csp460296wrn; Thu, 19 Jan 2023 09:46:05 -0800 (PST) X-Google-Smtp-Source: AMrXdXtTglkzADu/WW67GEoyqyAx1EvRqXY90OmgqjGye52/pNKAir17FXNiiHH6uXRgvsTwGlj6 X-Received: by 2002:a17:90a:4401:b0:229:2427:532f with SMTP id s1-20020a17090a440100b002292427532fmr11475579pjg.40.1674150365726; Thu, 19 Jan 2023 09:46:05 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1674150365; cv=none; d=google.com; s=arc-20160816; b=wWDbiGS6t1hXCKM3UGy75LolFMOV/bNeaHGA64RJwmigwVkomUUrI+kUdDLkdptgMU AfegkKgANUq4QB01tba8JNuduamoI/qKR3FAEHuUVt8KYi1a3+hunSXvhfyBS4/Q8EG3 Ud8S0h5SqjO6S51OsKAol/AGBS2omPSySQlzrOmr3OBX7NKYkqjBlzVAPntQd9zhCXxz MhCcfPT17o5n8gA+4MtyWgfNoNvCnKPUtuhLQfOVgFA5gbxEPLwF+tVGnu6GaSOPSd7r /N7l9e3+NkPPLjVi0MnEf6EgeU0QeaLSHCHve8wJqnOqmuLeSyNGKP2eN0n4ToC8RBIj IjsQ== 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 :message-id:date:subject:cc:to:from:dkim-signature; bh=+sej2ZxxI8+9iAYbhNxmaN6Ujy8XCLYxGf1h6Atn53o=; b=n8vooRqedr+kGUJXYIEQbrxZvJK2kyvVCncP0JNg9AQOgiO7jd+Dl3eNToWRELdEXS rCiVEBLIhkItZRXI8MtMVtPWjhE5rLlnYenh5LvYCP8QSEi2nOPrK0L8jznFCwHrfX1o m6+qVuLqjnKz3I46gsNNCksNL9jCCoc0TqPVnqKSDeyrnIQo8gkiVOJETwUFP9cHTs/M c8bD4AfLwSKvTiiS2r1FQ+FNkyDeuflHGBWSGtbgYY/Jrakw5K89sFDfbM+0KZgLZGj/ pl/tNHO1IWYjAmZKeSyI2PIKDUxF7BfXdGNAhFDqWDBBOF2e4I86EsV0xXvakrYu8aoy YX+Q== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@gmail.com header.s=20210112 header.b=oXH2HzaB; 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=NONE sp=QUARANTINE dis=NONE) header.from=gmail.com Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id v5-20020a17090a0c8500b00229a8c10f51si5302368pja.163.2023.01.19.09.45.53; Thu, 19 Jan 2023 09:46:05 -0800 (PST) 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=@gmail.com header.s=20210112 header.b=oXH2HzaB; 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=NONE sp=QUARANTINE dis=NONE) header.from=gmail.com Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S230255AbjASRlX (ORCPT + 99 others); Thu, 19 Jan 2023 12:41:23 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:48256 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S229614AbjASRlU (ORCPT ); Thu, 19 Jan 2023 12:41:20 -0500 Received: from mail-oi1-x232.google.com (mail-oi1-x232.google.com [IPv6:2607:f8b0:4864:20::232]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 82FDF5421C; Thu, 19 Jan 2023 09:40:59 -0800 (PST) Received: by mail-oi1-x232.google.com with SMTP id p133so2282941oig.8; Thu, 19 Jan 2023 09:40:59 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20210112; h=content-transfer-encoding:mime-version:message-id:date:subject:cc :to:from:from:to:cc:subject:date:message-id:reply-to; bh=+sej2ZxxI8+9iAYbhNxmaN6Ujy8XCLYxGf1h6Atn53o=; b=oXH2HzaBjYUWyrxXrR0aA6Trc8tK3yh35yGvu1GnMLz2SAhX4u5RQpxt5ma5Wl75oh VTRKvtXos1Z2WX7lK5t0u9Zs5bqPHiH2MSPs8EAp5WP9KkdYCxXJUXtVL3V6OJSknG0w AcaKL0SIUL8BC9N9CfCzOrgk2fcNODHN6ZwWYyCqSJjSsg9rmz3gT6AcoQAKeth5xk6P C5EQJNyRyVGERAEpsi2iaR5f3oRWpRBDw2hSJd8TFCLQx2YFuis42RB7K8YWmwD7H1Zn QsxwFXiPR7LJqRmX5cCW0N+LEOvZqpcIVbuisVzO4d1iXH9WH4Wmmk5rw4QaX4raT1Q+ APPA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=content-transfer-encoding:mime-version:message-id:date:subject:cc :to:from:x-gm-message-state:from:to:cc:subject:date:message-id :reply-to; bh=+sej2ZxxI8+9iAYbhNxmaN6Ujy8XCLYxGf1h6Atn53o=; b=SP56YPl+17g4mzKIo74s6s7MqysUD+9GU8NTwNsRdaVDJUj2tT03GspGHNpgBzUWwx ebmOLJ+H5jcIIsAa+w1IHiiSw3qWOn53sAQKr51abwlr9BowZ+R9uGHfr/MewPjfQedm Xw3JP0nb39sjVUJcsVWCKVpSpwre5vDjktmrJZ6yASJhI13MDY0eCnEhGjGleS8gdoiH cmp3lv2Do/Q1k3s5YQyFs8zKjTewKCkIduFL4R/Xz4n1Shs7Wv+HMo2w1Dj/FYpiVhCo 9f1K2xExF9/MmjmFRYU5kKBuQ/RgTPLuU9EKU1mzGKo32G/2xVWYC26/tc76htEoT5bo oVOQ== X-Gm-Message-State: AFqh2krUfyytv0iVmTzKs4Yyvma7i85HYezhk64n/HBcP2xBcHNc6r8B Q3pqgIIqi7oR5AU67IbKKmEu2pKj8gFuN905 X-Received: by 2002:aca:3c88:0:b0:35e:bc08:35f6 with SMTP id j130-20020aca3c88000000b0035ebc0835f6mr4959874oia.8.1674150058819; Thu, 19 Jan 2023 09:40:58 -0800 (PST) Received: from wedsonaf-dev.home.lan ([189.124.190.154]) by smtp.googlemail.com with ESMTPSA id i7-20020a056808054700b003631fe1810dsm10226906oig.47.2023.01.19.09.40.55 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 19 Jan 2023 09:40:58 -0800 (PST) From: Wedson Almeida Filho To: rust-for-linux@vger.kernel.org Cc: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?B?= =?utf-8?q?j=C3=B6rn_Roy_Baron?= , linux-kernel@vger.kernel.org, Wedson Almeida Filho Subject: [PATCH 1/5] rust: types: introduce `ScopeGuard` Date: Thu, 19 Jan 2023 14:40:32 -0300 Message-Id: <20230119174036.64046-1-wedsonaf@gmail.com> X-Mailer: git-send-email 2.34.1 MIME-Version: 1.0 X-Spam-Status: No, score=-2.1 required=5.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,FREEMAIL_FROM, RCVD_IN_DNSWL_NONE,SPF_HELO_NONE,SPF_PASS autolearn=ham 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?1755473894069264028?= X-GMAIL-MSGID: =?utf-8?q?1755473894069264028?= This allows us to run some code when the guard is dropped (e.g., implicitly when it goes out of scope). We can also prevent the guard from running by calling its `dismiss()` method. Signed-off-by: Wedson Almeida Filho Reviewed-by: Vincenzo Palazzo --- rust/kernel/types.rs | 127 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 126 insertions(+), 1 deletion(-) diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index e84e51ec9716..f0ad4472292d 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -2,7 +2,132 @@ //! Kernel types. -use core::{cell::UnsafeCell, mem::MaybeUninit}; +use alloc::boxed::Box; +use core::{ + cell::UnsafeCell, + mem::MaybeUninit, + ops::{Deref, DerefMut}, +}; + +/// Runs a cleanup function/closure when dropped. +/// +/// The [`ScopeGuard::dismiss`] function prevents the cleanup function from running. +/// +/// # Examples +/// +/// In the example below, we have multiple exit paths and we want to log regardless of which one is +/// taken: +/// ``` +/// # use kernel::ScopeGuard; +/// fn example1(arg: bool) { +/// let _log = ScopeGuard::new(|| pr_info!("example1 completed\n")); +/// +/// if arg { +/// return; +/// } +/// +/// pr_info!("Do something...\n"); +/// } +/// +/// # example1(false); +/// # example1(true); +/// ``` +/// +/// In the example below, we want to log the same message on all early exits but a different one on +/// the main exit path: +/// ``` +/// # use kernel::ScopeGuard; +/// fn example2(arg: bool) { +/// let log = ScopeGuard::new(|| pr_info!("example2 returned early\n")); +/// +/// if arg { +/// return; +/// } +/// +/// // (Other early returns...) +/// +/// log.dismiss(); +/// pr_info!("example2 no early return\n"); +/// } +/// +/// # example2(false); +/// # example2(true); +/// ``` +/// +/// In the example below, we need a mutable object (the vector) to be accessible within the log +/// function, so we wrap it in the [`ScopeGuard`]: +/// ``` +/// # use kernel::ScopeGuard; +/// fn example3(arg: bool) -> Result { +/// let mut vec = +/// ScopeGuard::new_with_data(Vec::new(), |v| pr_info!("vec had {} elements\n", v.len())); +/// +/// vec.try_push(10u8)?; +/// if arg { +/// return Ok(()); +/// } +/// vec.try_push(20u8)?; +/// Ok(()) +/// } +/// +/// # assert_eq!(example3(false), Ok(())); +/// # assert_eq!(example3(true), Ok(())); +/// ``` +/// +/// # Invariants +/// +/// The value stored in the struct is nearly always `Some(_)`, except between +/// [`ScopeGuard::dismiss`] and [`ScopeGuard::drop`]: in this case, it will be `None` as the value +/// will have been returned to the caller. Since [`ScopeGuard::dismiss`] consumes the guard, +/// callers won't be able to use it anymore. +pub struct ScopeGuard(Option<(T, F)>); + +impl ScopeGuard { + /// Creates a new guarded object wrapping the given data and with the given cleanup function. + pub fn new_with_data(data: T, cleanup_func: F) -> Self { + // INVARIANT: The struct is being initialised with `Some(_)`. + Self(Some((data, cleanup_func))) + } + + /// Prevents the cleanup function from running and returns the guarded data. + pub fn dismiss(mut self) -> T { + // INVARIANT: This is the exception case in the invariant; it is not visible to callers + // because this function consumes `self`. + self.0.take().unwrap().0 + } +} + +impl ScopeGuard<(), Box> { + /// Creates a new guarded object with the given cleanup function. + pub fn new(cleanup: impl FnOnce()) -> ScopeGuard<(), impl FnOnce(())> { + ScopeGuard::new_with_data((), move |_| cleanup()) + } +} + +impl Deref for ScopeGuard { + type Target = T; + + fn deref(&self) -> &T { + // The type invariants guarantee that `unwrap` will succeed. + &self.0.as_ref().unwrap().0 + } +} + +impl DerefMut for ScopeGuard { + fn deref_mut(&mut self) -> &mut T { + // The type invariants guarantee that `unwrap` will succeed. + &mut self.0.as_mut().unwrap().0 + } +} + +impl Drop for ScopeGuard { + fn drop(&mut self) { + // Run the cleanup function if one is still present. + if let Some((data, cleanup)) = self.0.take() { + cleanup(data) + } + } +} /// Stores an opaque value. /// From patchwork Thu Jan 19 17:40:33 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Wedson Almeida Filho X-Patchwork-Id: 45877 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:eb09:0:0:0:0:0 with SMTP id s9csp460160wrn; Thu, 19 Jan 2023 09:45:48 -0800 (PST) X-Google-Smtp-Source: AMrXdXvQr1BdDjz/+5CV3S56B1eT3ruAs9+PjV094GFg+s3f+KLtgQzQ2ZtgfHrDw/XOtzTbxKyh X-Received: by 2002:a17:90a:4fa4:b0:226:f7d7:50f4 with SMTP id q33-20020a17090a4fa400b00226f7d750f4mr34780322pjh.21.1674150347798; Thu, 19 Jan 2023 09:45:47 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1674150347; cv=none; d=google.com; s=arc-20160816; b=cfVFGuGkE77SX+fzeJhf0oDkAQQ9ZU3CEjTa74olX03VNdVZ2CxyElBuUxwPQsc/1+ 6J1Sws3hUh/5GDCguFjHJ+TdWc+YTUAkvAW7JbkKL+mA49z7gAlSvww+vQF7wlcsmZjz j46Fdy2Di5VWcLE068A3se8eDqBSIQHslmvczW8q2Kx1+oDch7llO6FHaDQiPHQBpiBp 6Akd79QCM96EyaaoMv25yeNfojCuUGCIA5aubiohnODuicUxANf1LHr0EB2IJZ3PKjmK EhCmyH2lFItnEyNcOruCzeCsXh8eQ6s3HbLjt7VoCnGHY8spgVpYWU5GA4PEyEASqpOH 7fDQ== 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 :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=ZwxU4+6BfOCgB1/4NzWZU6FV5+g31u+lXUwKNUQPWUE=; b=WvwwU5rWT0L5JpHeQMkYWtutluYYnO/a5zQmrgA7Pl1/3CdL5E92wueGB0xkOQjHXo JRimlOwXOD5qWWnhrteHWrGVWeJQHyqTo0NICeDRkSiWxzvv3Qpqh//EM6TZfL+C2WPQ 3sBBBmXV48trnJom+6BszQJm9BpK3wAEC2tF1sI5jUY/+YXNCDZlj/d+hrh9DpqghCZ5 zuiBawneIxRnkaT6jdXod1R8wJJ5XMPljOqhfgWjyKNgfJg44nR8+cc0ZsbyaN481J9o Tmskm7D2hCIkNcyCDfoR2kBldaxQkEC/vhLiWa8XD1P33pxI0l7D4bTH1dEeKK8ZXwzE 42DA== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@gmail.com header.s=20210112 header.b=c+dYUuSK; 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=NONE sp=QUARANTINE dis=NONE) header.from=gmail.com Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id np5-20020a17090b4c4500b002238dff236esi7007311pjb.148.2023.01.19.09.45.35; Thu, 19 Jan 2023 09:45:47 -0800 (PST) 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=@gmail.com header.s=20210112 header.b=c+dYUuSK; 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=NONE sp=QUARANTINE dis=NONE) header.from=gmail.com Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S230077AbjASRl1 (ORCPT + 99 others); Thu, 19 Jan 2023 12:41:27 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:48310 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S229852AbjASRlV (ORCPT ); Thu, 19 Jan 2023 12:41:21 -0500 Received: from mail-oa1-x33.google.com (mail-oa1-x33.google.com [IPv6:2001:4860:4864:20::33]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id A676490857; Thu, 19 Jan 2023 09:41:02 -0800 (PST) Received: by mail-oa1-x33.google.com with SMTP id 586e51a60fabf-12c8312131fso3396868fac.4; Thu, 19 Jan 2023 09:41:02 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20210112; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=ZwxU4+6BfOCgB1/4NzWZU6FV5+g31u+lXUwKNUQPWUE=; b=c+dYUuSKYuS+4cZUhnvuhXuGCB2QiKzx0DR+8tgWN3eHX5UzXiXHfHfTwj2WoMmzYH ba5Qtrz3izgo0A2Q13X3Vu3pZ/YhqWE+kCyY53E+Lq/wAGaPoaZRyGMJ04He/K+7g9yK eahq4wyCfE0+HlAZJG1aRwK/g+M2QdGhKcPC5lj94CdgILTaStho2MHfxhq9hj67R2Fb 9FV3sJD1kmT/JnOpLuNmUR3Qd3d363foX4A7w9mJTBBLraIxdMFjuYYpuSoiM9R/eixg f19OufXWkBCWzaxc1RLq6HoiJug6w44q3buT5J689WzbLCe4PGRN8gBHKSkxvMbZFqc3 vxpA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=ZwxU4+6BfOCgB1/4NzWZU6FV5+g31u+lXUwKNUQPWUE=; b=q09sSd150cPkyqeKc1L1rJ0reo4T5F0T9xPk2PiOWgpBHVH8kloLLVHTMsOarfhw8v QcT9g5gn7wz0JlmvClvMEiu8kkXSMrdixvV2fkledHvzEutPKiNENAyE6qXtIHkDV6e0 KzcWEhctkaeXavsAboKIjE4QeOxxu2mn/4BCn0rLmn0w62NXZOq3e8Sh1K3Ht3YVNt4w L9YqFp955l5rEuJfdae2M52RcEOOihqh0QSeqP9o5rWwnmmESMn5P0GArvZ58dj6oz2C OIP97D3koj8TW2oFMiI2V15oC3c7HVD/4KqNld5UO8uq/N1z+fg1A+qT/gtWlZ9EPRAW hnIw== X-Gm-Message-State: AFqh2kqs8qJ74GJTL5xXkSGi9dPzQmizFchgORWPzqDrg618P0Z5LcIQ rTZeWOgv+9Xplk/ZOk355qRfPwZVlq9JGpbe X-Received: by 2002:a05:6870:659e:b0:15e:d586:6d46 with SMTP id fp30-20020a056870659e00b0015ed5866d46mr15435524oab.34.1674150061906; Thu, 19 Jan 2023 09:41:01 -0800 (PST) Received: from wedsonaf-dev.home.lan ([189.124.190.154]) by smtp.googlemail.com with ESMTPSA id i7-20020a056808054700b003631fe1810dsm10226906oig.47.2023.01.19.09.40.59 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 19 Jan 2023 09:41:01 -0800 (PST) From: Wedson Almeida Filho To: rust-for-linux@vger.kernel.org Cc: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?B?= =?utf-8?q?j=C3=B6rn_Roy_Baron?= , linux-kernel@vger.kernel.org, Wedson Almeida Filho Subject: [PATCH 2/5] rust: types: introduce `ForeignOwnable` Date: Thu, 19 Jan 2023 14:40:33 -0300 Message-Id: <20230119174036.64046-2-wedsonaf@gmail.com> X-Mailer: git-send-email 2.34.1 In-Reply-To: <20230119174036.64046-1-wedsonaf@gmail.com> References: <20230119174036.64046-1-wedsonaf@gmail.com> MIME-Version: 1.0 X-Spam-Status: No, score=-2.1 required=5.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,FREEMAIL_FROM, RCVD_IN_DNSWL_NONE,SPF_HELO_NONE,SPF_PASS autolearn=ham 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?1755473875293850318?= X-GMAIL-MSGID: =?utf-8?q?1755473875293850318?= It was originally called `PointerWrapper`. It is used to convert a Rust object to a pointer representation (void *) that can be stored on the C side, used, and eventually returned to Rust. Signed-off-by: Wedson Almeida Filho Reviewed-by: Vincenzo Palazzo Reviewed-by: Martin Rodriguez Reboredo --- rust/kernel/lib.rs | 1 + rust/kernel/types.rs | 54 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index e0b0e953907d..223564f9f0cc 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -16,6 +16,7 @@ #![feature(coerce_unsized)] #![feature(core_ffi_c)] #![feature(dispatch_from_dyn)] +#![feature(generic_associated_types)] #![feature(receiver_trait)] #![feature(unsize)] diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index f0ad4472292d..5475f6163002 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -9,6 +9,60 @@ use core::{ ops::{Deref, DerefMut}, }; +/// Used to transfer ownership to and from foreign (non-Rust) languages. +/// +/// Ownership is transferred from Rust to a foreign language by calling [`Self::into_foreign`] and +/// later may be transferred back to Rust by calling [`Self::from_foreign`]. +/// +/// This trait is meant to be used in cases when Rust objects are stored in C objects and +/// eventually "freed" back to Rust. +pub trait ForeignOwnable { + /// Type of values borrowed between calls to [`ForeignOwnable::into_foreign`] and + /// [`ForeignOwnable::from_foreign`]. + type Borrowed<'a>; + + /// Converts a Rust-owned object to a foreign-owned one. + /// + /// The foreign representation is a pointer to void. + fn into_foreign(self) -> *const core::ffi::c_void; + + /// Borrows a foreign-owned object. + /// + /// # Safety + /// + /// `ptr` must have been returned by a previous call to [`ForeignOwnable::into_foreign`] for + /// which a previous matching [`ForeignOwnable::from_foreign`] hasn't been called yet. + /// Additionally, all instances (if any) of values returned by [`ForeignOwnable::borrow_mut`] + /// for this object must have been dropped. + unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> Self::Borrowed<'a>; + + /// Mutably borrows a foreign-owned object. + /// + /// # Safety + /// + /// `ptr` must have been returned by a previous call to [`ForeignOwnable::into_foreign`] for + /// which a previous matching [`ForeignOwnable::from_foreign`] hasn't been called yet. + /// Additionally, all instances (if any) of values returned by [`ForeignOwnable::borrow`] and + /// [`ForeignOwnable::borrow_mut`] for this object must have been dropped. + unsafe fn borrow_mut(ptr: *const core::ffi::c_void) -> ScopeGuard { + // SAFETY: The safety requirements ensure that `ptr` came from a previous call to + // `into_foreign`. + ScopeGuard::new_with_data(unsafe { T::from_foreign(ptr) }, |d| { + d.into_foreign(); + }) + } + + /// Converts a foreign-owned object back to a Rust-owned one. + /// + /// # Safety + /// + /// `ptr` must have been returned by a previous call to [`ForeignOwnable::into_foreign`] for + /// which a previous matching [`ForeignOwnable::from_foreign`] hasn't been called yet. + /// Additionally, all instances (if any) of values returned by [`ForeignOwnable::borrow`] and + /// [`ForeignOwnable::borrow_mut`] for this object must have been dropped. + unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self; +} + /// Runs a cleanup function/closure when dropped. /// /// The [`ScopeGuard::dismiss`] function prevents the cleanup function from running. From patchwork Thu Jan 19 17:40:34 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Wedson Almeida Filho X-Patchwork-Id: 45879 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:eb09:0:0:0:0:0 with SMTP id s9csp460468wrn; Thu, 19 Jan 2023 09:46:21 -0800 (PST) X-Google-Smtp-Source: AMrXdXtjBxlsLirbptG4gsc1LLbh1UvP/r5Fd9z6EClXN34gvLb2sWdlhwOMhCF3l+cvKt8Fq0Gz X-Received: by 2002:a17:90a:160f:b0:228:5b99:3b45 with SMTP id n15-20020a17090a160f00b002285b993b45mr12847806pja.7.1674150381107; Thu, 19 Jan 2023 09:46:21 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1674150381; cv=none; d=google.com; s=arc-20160816; b=YTWBLn+ottyvHwPK5BIT28bi0L0D9Z3rZWVjY8Qjuex6/1nfWj919oYgoIGnyiDsoi r1Catlca/eeBlxfeo3sSQSFtH/ZBwC3akyGQ3RHfNDzlSm10LXf5/yM9zqR1J8MTXYcY ieXHJduJyYQ9zqpwKw+G6oGSrfJnjWjuC7nMTTqqwH98fC8shrgy1IP2kuQFhnQksCfw /Gg5V9dyxh5XkYzd0KIQR7TWixLnxCnYn4uxn8p+ckU0NqFMVc1kOXnePCaBdcMmwNRH zXE1Vl8seUqB/WSyvSfv+vxYZ33+4iF257Takdnxl0DZ47FSj7MxpvXp0w1HTcfdZpD9 /V2w== 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 :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=wGMIqOBRVBwOZ5uyAthUJactG+QhEC2sAl1iIa6Sq0Y=; b=c/9fc7hoBbTxBW3om5t4ridomD6FI/mU7ospOljPkmHv3Jq1u5X17xd0S+BTtalFI+ kvAJmf3ya8Ni7/YPk2uBSUpxej4vpoHqCHKXh6NCmUTOWjbOYABkPCQ4LHtRwbXk9LDy kWZf1L8bCgYaHprsMwwKcx5O3xOfr+bp5ljD6m7qs5VJydljXaq9i97/1JUYBBLLKBEs YikLrPrUrtECE3wXzVAiBozP+cYvCDwbLUU1FAESjEAR2LqN/QOtQ4pxT6ZgFYs6pHfv ppC6VHM9FHXT+qIrfPJxBc5SSSjQKUeeWvHAKH4UzS70z0csCO5P7XGDlHesMpBz1/Wm LygA== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@gmail.com header.s=20210112 header.b=Ri4BGOfn; 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=NONE sp=QUARANTINE dis=NONE) header.from=gmail.com Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id my9-20020a17090b4c8900b0021a1261c317si6096538pjb.126.2023.01.19.09.46.07; Thu, 19 Jan 2023 09:46:21 -0800 (PST) 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=@gmail.com header.s=20210112 header.b=Ri4BGOfn; 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=NONE sp=QUARANTINE dis=NONE) header.from=gmail.com Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S230293AbjASRla (ORCPT + 99 others); Thu, 19 Jan 2023 12:41:30 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:48258 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S229593AbjASRlV (ORCPT ); Thu, 19 Jan 2023 12:41:21 -0500 Received: from mail-oi1-x235.google.com (mail-oi1-x235.google.com [IPv6:2607:f8b0:4864:20::235]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id DACEC8BABC; Thu, 19 Jan 2023 09:41:05 -0800 (PST) Received: by mail-oi1-x235.google.com with SMTP id i5so2273429oih.11; Thu, 19 Jan 2023 09:41:05 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20210112; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=wGMIqOBRVBwOZ5uyAthUJactG+QhEC2sAl1iIa6Sq0Y=; b=Ri4BGOfnQOaAKbc9bsyJzNBXcozXCwdE3vwshewu1Uw/45388Y1AnLUr0W6yjWzeQy r8Ja2PwxVoRtn3538cqmTsUfue1Q3PLgQbIQe1z9tNRbdie48JAf5V5rbeqUhk405IRz K00/7flOo9EVO9c1Q38l+6BWXt1klpjeFTyBZqHVifxYHG4mpBa0Xipy41z++9UnGY7f 5JZ5gcVizyM5QJgeobaZpxlODIpA09ohumDP0eihN1QChtKrieux5kwhx3RSBRfrFxJh iA/0Goj5GdtyhqBi+ctA03dkPXFvMDUsWbkn2rfV78L6QJQK6PAhoxp7SA9YvpSLkgrQ dVDQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=wGMIqOBRVBwOZ5uyAthUJactG+QhEC2sAl1iIa6Sq0Y=; b=DkSVoaOaD/n2pM0dOirrQ/io8BT/peCjUioR9fq58pAcW/K+aMrmRFjnJbVkdKUjU0 gUclPGd19ZU08Jn8baH0ghN0caAWQkv+1yf36jwnwu8PK78en4/V/BimywRYiRj2i2ON aanuLxC3Jv8aJe8IxJuZCAtTqHflroDm84NgZWyTDuIS2CPqjd29Y2i9UCzEjqdnaf5O SyFnr2qOy4TKwMs8TxRkImRtg6sJsgxXSTljpBOeljkAlVUzXo+1XRsna84UfxaywfXv PJOyDkhHmgJ8rcY0w/fsawPEtVtQSWA5o2GrmBZIi6TaEZscEEV9Ct3XM5mvkJga/7bR mnsQ== X-Gm-Message-State: AFqh2kqK0lTY/NfmMXPO2AJFXyLc5YmNufkcWCsz7X1zIFYk5/QBmcyt nSFXfa9tG2KCoU4q1ZoxFE4obdheNiaPVwfQ X-Received: by 2002:aca:1c09:0:b0:367:18f4:dbef with SMTP id c9-20020aca1c09000000b0036718f4dbefmr5472968oic.0.1674150065168; Thu, 19 Jan 2023 09:41:05 -0800 (PST) Received: from wedsonaf-dev.home.lan ([189.124.190.154]) by smtp.googlemail.com with ESMTPSA id i7-20020a056808054700b003631fe1810dsm10226906oig.47.2023.01.19.09.41.02 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 19 Jan 2023 09:41:04 -0800 (PST) From: Wedson Almeida Filho To: rust-for-linux@vger.kernel.org Cc: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?B?= =?utf-8?q?j=C3=B6rn_Roy_Baron?= , linux-kernel@vger.kernel.org, Wedson Almeida Filho Subject: [PATCH 3/5] rust: types: implement `ForeignOwnable` for `Box` Date: Thu, 19 Jan 2023 14:40:34 -0300 Message-Id: <20230119174036.64046-3-wedsonaf@gmail.com> X-Mailer: git-send-email 2.34.1 In-Reply-To: <20230119174036.64046-1-wedsonaf@gmail.com> References: <20230119174036.64046-1-wedsonaf@gmail.com> MIME-Version: 1.0 X-Spam-Status: No, score=-2.1 required=5.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,FREEMAIL_FROM, RCVD_IN_DNSWL_NONE,SPF_HELO_NONE,SPF_PASS autolearn=ham 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?1755473910328221584?= X-GMAIL-MSGID: =?utf-8?q?1755473910328221584?= This allows us to hand ownership of Rust dynamically allocated objects to the C side of the kernel. Signed-off-by: Wedson Almeida Filho Reviewed-by: Gary Guo Reviewed-by: Vincenzo Palazzo Reviewed-by: Alice Ferrazzi --- rust/kernel/types.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index 5475f6163002..e037c262f23e 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -63,6 +63,28 @@ pub trait ForeignOwnable { unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self; } +impl ForeignOwnable for Box { + type Borrowed<'a> = &'a T; + + fn into_foreign(self) -> *const core::ffi::c_void { + Box::into_raw(self) as _ + } + + unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> &'a T { + // SAFETY: The safety requirements for this function ensure that the object is still alive, + // so it is safe to dereference the raw pointer. + // The safety requirements of `from_foreign` also ensure that the object remains alive for + // the lifetime of the returned value. + unsafe { &*ptr.cast() } + } + + unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self { + // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous + // call to `Self::into_foreign`. + unsafe { Box::from_raw(ptr as _) } + } +} + /// Runs a cleanup function/closure when dropped. /// /// The [`ScopeGuard::dismiss`] function prevents the cleanup function from running. From patchwork Thu Jan 19 17:40:35 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Wedson Almeida Filho X-Patchwork-Id: 45881 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:eb09:0:0:0:0:0 with SMTP id s9csp461129wrn; Thu, 19 Jan 2023 09:47:54 -0800 (PST) X-Google-Smtp-Source: AMrXdXtn5Al5KebqioVPoOCqwuVhSxZuBGhKs7hhBfc/2AMl2ulQOPyPV7n2jCZNjsMaQzNt4xRG X-Received: by 2002:aa7:84c1:0:b0:58d:9b18:a36e with SMTP id x1-20020aa784c1000000b0058d9b18a36emr11923193pfn.31.1674150473730; Thu, 19 Jan 2023 09:47:53 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1674150473; cv=none; d=google.com; s=arc-20160816; b=ulEDWuFy3827BiJewJfZZzzi2X8AY5CzMs3cGik8Hlzl3VBk6LON3TF9qf6s1Tscx9 +fJrBkAUKVrD/ndwqIgVGOCoT4ARLjb24OZiLWszbno9Smay9UFZ4zWGvEMkWPanmC3g 05AhORNefMrcyPTiFENwlzmw+E36PgbpwRk+4Dopwcf8CLAtLWb1ceuFfo3+0vMvsLMP kcC9bo4eSZphWbyKrPip6daum6bh1NzR1bGUWzPxUVixUILNph1c49KwhZsWU3SyLMr1 MuGQO7zKL3+l4xCJFdoz70uvgQpniErwuQBk7oeENbfSk9+Q/HLtv9sTffYOCCMd77td PRkQ== 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 :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=NO/tLxVBmWB1dJAexFMTC87LMSP1V8gc/xUgEhy6fvI=; b=Nv7K6gYhun/KL08u7nIGAB10q+xxUnFzgcE4hgmN2d6eg12r+TjTUdozhkXnE1LvFP +g/uRrz3szG6fjha0pO99V5N5ofuUL27itdclQarM8LfuPSkXD0pVAV60YHNmbDTOSSW GZqfyM8dVN4lt6OuGF80obXEosTTaZh7G7VAD7jhxVXFWKQQK4KTg8iPm/h1QYcwRyoD EWIRg/7pG8bBouUt6Mtz0RqnT4qYF5P8e9oHdXESRN4AvuQrefpGnrqJM7ecAqgLODiW NMdtG02481FoaPct6Uem+bAv2s7acZiJMh6W6mbNhPqJKlH2dur3LRL54vUPD393ItL3 HzkQ== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@gmail.com header.s=20210112 header.b="YBF/bv8H"; 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=NONE sp=QUARANTINE dis=NONE) header.from=gmail.com Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id y71-20020a62644a000000b0058a71b56a06si27772240pfb.130.2023.01.19.09.47.41; Thu, 19 Jan 2023 09:47:53 -0800 (PST) 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=@gmail.com header.s=20210112 header.b="YBF/bv8H"; 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=NONE sp=QUARANTINE dis=NONE) header.from=gmail.com Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S230089AbjASRld (ORCPT + 99 others); Thu, 19 Jan 2023 12:41:33 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:48256 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S229609AbjASRlW (ORCPT ); Thu, 19 Jan 2023 12:41:22 -0500 Received: from mail-oi1-x22c.google.com (mail-oi1-x22c.google.com [IPv6:2607:f8b0:4864:20::22c]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id E0AE2798F9; Thu, 19 Jan 2023 09:41:08 -0800 (PST) Received: by mail-oi1-x22c.google.com with SMTP id v17so2297841oie.5; Thu, 19 Jan 2023 09:41:08 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20210112; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=NO/tLxVBmWB1dJAexFMTC87LMSP1V8gc/xUgEhy6fvI=; b=YBF/bv8HlX6jUtB0z4bb1xtYgg4EdDkd80BPaxQb8LIoAa6fmzgul3M6qSS5yRI8Cy fGIybIuQB5cT1uuCDHK3kr9/mIHcetjAftYjO88JzxaBX8e5VWpkkxPeu/gwtlmfwySs VUy4NLBcyyxcgsWBDrf78+meibyXGyuM4zzRsXhSpU5LrIWbeXMSjwbopFHonDvUeJag pYYIYKAD2jAqT2JzLQLfu5E1Iqk6teivVTyqrFiOhABiX1/yEc8lpFrYnFfj3TUGHiVK m88jKaFFsb/qKwQ0K9mlhfcJlgzHvGqzU1zR+vl0tVUIbsbu5f7FqlHMeSgZQqyTghny OCJA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=NO/tLxVBmWB1dJAexFMTC87LMSP1V8gc/xUgEhy6fvI=; b=ZZ0MyAIDcewrtMHq9udoGHkTzPVtU9QbsqSRRaKXKC+ExaalGiOo6EH1H1CFcowBcz 0x0kf/268TS7b+w/DY6P3Q+7so51m4lH4FdbYlPOLAd88ZNMtZdxKvAlPm+YMJE/hnT+ F4XSFWJPskaLw7tqCPvvP+TZ9OdMVW2B92BQwIz+YBYfDlTdTIp7EmSRWEAzz2Dc4ncO tFfh4/CgrRWWUBYHjAxXwt+vR8WKnURE5cZ/ElAXwPGXX/Md9hIyhngeJ2tW6NgE9g3x ose5x9e000yQ2e9G8iMqTcM504nkGEYEsbsfy1BoGJlnGyjmSAtgpAUsTEf4xnR+s3qx Cgzg== X-Gm-Message-State: AFqh2kq0s8BI8EsZ/DrzAH/0hC2vM+uQUUs1jKmEsYArmjiaxGx9rts5 FmBLlbdoPeOEyZyyAvtTlyVCXar7Lh729VYj X-Received: by 2002:aca:1710:0:b0:36e:b552:1ec3 with SMTP id j16-20020aca1710000000b0036eb5521ec3mr576626oii.38.1674150068191; Thu, 19 Jan 2023 09:41:08 -0800 (PST) Received: from wedsonaf-dev.home.lan ([189.124.190.154]) by smtp.googlemail.com with ESMTPSA id i7-20020a056808054700b003631fe1810dsm10226906oig.47.2023.01.19.09.41.05 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 19 Jan 2023 09:41:08 -0800 (PST) From: Wedson Almeida Filho To: rust-for-linux@vger.kernel.org Cc: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?B?= =?utf-8?q?j=C3=B6rn_Roy_Baron?= , linux-kernel@vger.kernel.org, Wedson Almeida Filho Subject: [PATCH 4/5] rust: types: implement `ForeignOwnable` for the unit type Date: Thu, 19 Jan 2023 14:40:35 -0300 Message-Id: <20230119174036.64046-4-wedsonaf@gmail.com> X-Mailer: git-send-email 2.34.1 In-Reply-To: <20230119174036.64046-1-wedsonaf@gmail.com> References: <20230119174036.64046-1-wedsonaf@gmail.com> MIME-Version: 1.0 X-Spam-Status: No, score=-2.1 required=5.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,FREEMAIL_FROM, RCVD_IN_DNSWL_NONE,SPF_HELO_NONE,SPF_PASS autolearn=ham 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?1755474006769420102?= X-GMAIL-MSGID: =?utf-8?q?1755474006769420102?= This allows us to use the unit type `()` when we have no object whose ownership must be managed but one implementing the `ForeignOwnable` trait is needed. Signed-off-by: Wedson Almeida Filho Reviewed-by: Vincenzo Palazzo --- rust/kernel/types.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index e037c262f23e..8f80cffbff59 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -85,6 +85,19 @@ impl ForeignOwnable for Box { } } +impl ForeignOwnable for () { + type Borrowed<'a> = (); + + fn into_foreign(self) -> *const core::ffi::c_void { + // We use 1 to be different from a null pointer. + 1usize as _ + } + + unsafe fn borrow<'a>(_: *const core::ffi::c_void) -> Self::Borrowed<'a> {} + + unsafe fn from_foreign(_: *const core::ffi::c_void) -> Self {} +} + /// Runs a cleanup function/closure when dropped. /// /// The [`ScopeGuard::dismiss`] function prevents the cleanup function from running. From patchwork Thu Jan 19 17:40:36 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Wedson Almeida Filho X-Patchwork-Id: 45880 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:eb09:0:0:0:0:0 with SMTP id s9csp460709wrn; Thu, 19 Jan 2023 09:46:50 -0800 (PST) X-Google-Smtp-Source: AMrXdXtc7OS/HX8iGOEEbH5lBDXEJuCC8jG1be4bDjcEdKAjwgJi663JBlo9MOc4Vklrbc/MUoy2 X-Received: by 2002:a17:902:edd1:b0:194:706c:d05d with SMTP id q17-20020a170902edd100b00194706cd05dmr10585449plk.13.1674150410360; Thu, 19 Jan 2023 09:46:50 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1674150410; cv=none; d=google.com; s=arc-20160816; b=0mUa1ZBO4KIF+NcCGukw7Fbl2Wuiw6inF1NsQJ3ykXxCP1Sgza5zDaROQph1McCdO2 DEaUX7H9mw6p5XlsDGz1cQ9cg0w6jmeePO/BPtHLArAoEmZG2xVcy7IWZvgKGkM+9j05 8MT+vmQpTkvMgWAiFE99HApT4TQ2lyIC9VtlBlPfEcfq4v+PrjRFanhWfn7VIef/Hzam 8DOt4ZKEGqCx54j/0Pe4s6IMCKxx47/i2KVfaJoeZDIvc852ihcoHn56J+l66lWBZIWA MVLzftOz7yVSFeJYCFcqmWnJYaLuu4UspJqyU7EQvahTiU0I+p2oEBdQUzfRU1ySQfUN wApg== 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 :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=ewZt9xECZEPZ1KuMvtcM156VR5vfWcAYIR5vc+17fj0=; b=nmhonyEldAeQLtBxn3y5HW6KS3UpAkXt9ycHUr3UgZawZBtQ3/Hmdq18gYhzgAJ6KS zI2oKgv5DmRYnTc2QlObZG0/CyKGti3tjbV6H59fngK+WMwXVwxgoKZGxaRqNIMkiCi2 kGEVFcf52pm9k7zdZhDBChZdEEAjqRhj+YUmhm2/eHDCYy+sLOP21mTqZnBVhGb/U4/+ +Pjs9wlGfz/rYxMZAIFgmaj38zeBrMS8NXbJiESLWVumIZcIq+I0d0PZfwxUNhaWcqWa ETVS+GleAt3Rh3xNj/ONeiBdOq2cgjJID/iGCK4VLC/B132M/i8uOtxpUmViF70E/0Wv bg/g== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@gmail.com header.s=20210112 header.b="ec4/wN56"; 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=NONE sp=QUARANTINE dis=NONE) header.from=gmail.com Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id l8-20020a170902f68800b00192ab6aa296si7432973plg.243.2023.01.19.09.46.38; Thu, 19 Jan 2023 09:46:50 -0800 (PST) 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=@gmail.com header.s=20210112 header.b="ec4/wN56"; 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=NONE sp=QUARANTINE dis=NONE) header.from=gmail.com Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S230106AbjASRlg (ORCPT + 99 others); Thu, 19 Jan 2023 12:41:36 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:48332 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S230095AbjASRlX (ORCPT ); Thu, 19 Jan 2023 12:41:23 -0500 Received: from mail-oi1-x22f.google.com (mail-oi1-x22f.google.com [IPv6:2607:f8b0:4864:20::22f]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 3692D8BAA9; Thu, 19 Jan 2023 09:41:12 -0800 (PST) Received: by mail-oi1-x22f.google.com with SMTP id p185so2313484oif.2; Thu, 19 Jan 2023 09:41:12 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20210112; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=ewZt9xECZEPZ1KuMvtcM156VR5vfWcAYIR5vc+17fj0=; b=ec4/wN56BlwB+jpQj7V9tlgsO2eAholWn2jaBPb+Aq4vRxqrhQ/euBYEL0rsNd8ILt CpnFtaM95PSAXdbDqW0OS1S/TlE4cXSsgKc/sb1H0j96NkENDO6Vy5EY5BytRdybIIFn HLMyXsWSfQjwBH8IyFtDKe2CrX2a44HSKJprlQsyyq+yDwEDiu9LuCE4sOeJz7c0UUg8 P+krDC8NSc5kGvXQoJlKWSYQG19xUhffer3/ZiK5FhOZ7VHTVzBJ9r1PXW2eVO7UEMhS AewRsNU7+sf7azdBkf7RKBIglXHBB7GeKrjJ5Fvy8u4WLV4hzintzuY/N6EqKHcTxIk5 beXQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=ewZt9xECZEPZ1KuMvtcM156VR5vfWcAYIR5vc+17fj0=; b=vv3qNBywbHidakBeumB1yvk+9/oALAdHKDZivKlprn7viyWrDyhjmyv56gOD1XP13X 2XYrDUlhdpBG/ewet88fXu8Ld6AhnhkcsHogIigj93Gt6qqN5oQa4Le57kYk8yJBTTmH IZ7jb6pibHF0iFWnKtJ6p3QTwlu2SuB3ZnH8NSs+knnxhgCm1LcEYlESVEhz22R4JcBp ZhE7JZztbKeu0B0wiZFrX/N4yc4FY45MCGx4KlUVOufo/eVaxf7pyECD7ss59mXINpLM YvyVX3whrMJLKM20ZAluUcmeE7nXC2cTeJ0o5cOEDc1yVdjdh+4Kj6RHNWlgnLFEGce2 HQpA== X-Gm-Message-State: AFqh2kog79lYjL96/5Ofrb2n8sd7ivHM1BF55vaudFov4dH9kSBZotse A4T1A5XbnVJpQEyYiBeAbuUkCcRGA9d5CLqU X-Received: by 2002:aca:230f:0:b0:364:d7f0:3847 with SMTP id e15-20020aca230f000000b00364d7f03847mr4873263oie.38.1674150071475; Thu, 19 Jan 2023 09:41:11 -0800 (PST) Received: from wedsonaf-dev.home.lan ([189.124.190.154]) by smtp.googlemail.com with ESMTPSA id i7-20020a056808054700b003631fe1810dsm10226906oig.47.2023.01.19.09.41.08 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 19 Jan 2023 09:41:11 -0800 (PST) From: Wedson Almeida Filho To: rust-for-linux@vger.kernel.org Cc: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?B?= =?utf-8?q?j=C3=B6rn_Roy_Baron?= , linux-kernel@vger.kernel.org, Wedson Almeida Filho Subject: [PATCH 5/5] rust: types: implement `ForeignOwnable` for `Arc` Date: Thu, 19 Jan 2023 14:40:36 -0300 Message-Id: <20230119174036.64046-5-wedsonaf@gmail.com> X-Mailer: git-send-email 2.34.1 In-Reply-To: <20230119174036.64046-1-wedsonaf@gmail.com> References: <20230119174036.64046-1-wedsonaf@gmail.com> MIME-Version: 1.0 X-Spam-Status: No, score=-2.1 required=5.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,FREEMAIL_FROM, RCVD_IN_DNSWL_NONE,SPF_HELO_NONE,SPF_PASS autolearn=ham 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?1755473940916009647?= X-GMAIL-MSGID: =?utf-8?q?1755473940916009647?= This allows us to hand ownership of Rust ref-counted objects to the C side of the kernel. Signed-off-by: Wedson Almeida Filho Reviewed-by: Gary Guo Reviewed-by: Vincenzo Palazzo Reviewed-by: Alice Ferrazzi --- rust/kernel/sync/arc.rs | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index ff73f9240ca1..519a6ec43644 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -15,7 +15,11 @@ //! //! [`Arc`]: https://doc.rust-lang.org/std/sync/struct.Arc.html -use crate::{bindings, error::Result, types::Opaque}; +use crate::{ + bindings, + error::Result, + types::{ForeignOwnable, Opaque}, +}; use alloc::boxed::Box; use core::{ marker::{PhantomData, Unsize}, @@ -189,6 +193,32 @@ impl Arc { } } +impl ForeignOwnable for Arc { + type Borrowed<'a> = ArcBorrow<'a, T>; + + fn into_foreign(self) -> *const core::ffi::c_void { + ManuallyDrop::new(self).ptr.as_ptr() as _ + } + + unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> ArcBorrow<'a, T> { + // SAFETY: By the safety requirement of this function, we know that `ptr` came from + // a previous call to `Arc::into_foreign`. + let inner = NonNull::new(ptr as *mut ArcInner).unwrap(); + + // SAFETY: The safety requirements of `from_foreign` ensure that the object remains alive + // for the lifetime of the returned value. Additionally, the safety requirements of + // `ForeignOwnable::borrow_mut` ensure that no new mutable references are created. + unsafe { ArcBorrow::new(inner) } + } + + unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self { + // SAFETY: By the safety requirement of this function, we know that `ptr` came from + // a previous call to `Arc::into_foreign`, which owned guarantees that `ptr` is valid and + // owns a reference. + unsafe { Self::from_inner(NonNull::new(ptr as _).unwrap()) } + } +} + impl Deref for Arc { type Target = T;