Received: by 2002:a05:6358:11c7:b0:104:8066:f915 with SMTP id i7csp3193103rwl; Sun, 9 Apr 2023 09:50:45 -0700 (PDT) X-Google-Smtp-Source: AKy350Zc0T894DVFGuAYykIixvs3sopDWr/Z9Pu5F2SzDzhsJ+GXNsuZnVNxU0/LWVI5mGc82FRb X-Received: by 2002:aa7:c259:0:b0:4fa:8aa4:8d8b with SMTP id y25-20020aa7c259000000b004fa8aa48d8bmr5807817edo.7.1681059044843; Sun, 09 Apr 2023 09:50:44 -0700 (PDT) ARC-Seal: i=1; a=rsa-sha256; t=1681059044; cv=none; d=google.com; s=arc-20160816; b=HfGFHvFcZd3bjYqooBxdHSjBovvqtImnhIlLGTqProaJmHEYYaTx4SWo9VRN0NPZvF AiowQDw/rmlF+i9IG+3DmiKkR5Y+FXC4Y/5dihLUE6hUBVZ5DEL3erZZlX75iJ9ktm4J gwP/MkbMI3bK0LtP/HJpQfwFuUsd8nBqxkZvKrZipYyLMCKdDn3uAwhSninS49etL3DN I1s68bsgFdhZvsxi5wS1bNsK+wvy/vLsZI7E1vCWMUdlXn3pd4hGQnF8Jg59aTx8BBub Qo/q1SmRona3iHIMAmoG/g2KLImM3NO3VryY+dWbYjAqPeWaA3P6XyFDVvu7zT83vBSz dbVw== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:in-reply-to :content-language:references:cc:to:subject:from:user-agent :mime-version:date:message-id:dkim-signature; bh=ShVq2ADCVfvgmdX2n9FqpBRVYZ0AkpDjoaZsweYGyEM=; b=kGpbPwdMP2e09Tkf/O6MKfGtR0iKAyQwt4gWpuaox+gTIThrN7JUMqdEah6MY5U6pC Zjym2qd7zrklEsxL1LVGWFucBknv+SRgh1mfS+aCSgJciu1V0YqcnCW9U18zhKF/udTc 2Got5Z3Y+DiQxWrQCcU6eZs/mVNe4EPA8/p73+ole7a5legzOgkiXYE6MYm3oav/NK6b Ks4Cl2beM7C/jwhnzmfzEWE5qUPDmBuZDe9qbyhp/bPEK8eCxqO4Y16dmMbvUvIUF9k0 gZrKBiTB21JHP/wH7xSIRAV73KL/EGmP2W9zBNqUwDuAfrSDB1GfLDgN6Bvox6ejD3Zn nBTQ== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@gmail.com header.s=20210112 header.b=V81w79ox; 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 Return-Path: Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id kb21-20020a1709070f9500b0093cfe245f3csi5407993ejc.18.2023.04.09.09.50.20; Sun, 09 Apr 2023 09:50:44 -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=@gmail.com header.s=20210112 header.b=V81w79ox; 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 S229671AbjDIQtU (ORCPT + 99 others); Sun, 9 Apr 2023 12:49:20 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:60494 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S229598AbjDIQtK (ORCPT ); Sun, 9 Apr 2023 12:49:10 -0400 Received: from mail-oo1-xc35.google.com (mail-oo1-xc35.google.com [IPv6:2607:f8b0:4864:20::c35]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 3032D49CF; Sun, 9 Apr 2023 09:48:59 -0700 (PDT) Received: by mail-oo1-xc35.google.com with SMTP id c17-20020a4aa4d1000000b005418821052aso1410982oom.6; Sun, 09 Apr 2023 09:48:59 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20210112; t=1681058938; h=content-transfer-encoding:in-reply-to:content-language:references :cc:to:subject:from:user-agent:mime-version:date:message-id:from:to :cc:subject:date:message-id:reply-to; bh=ShVq2ADCVfvgmdX2n9FqpBRVYZ0AkpDjoaZsweYGyEM=; b=V81w79oxd3ulj+0F+26TD9hgwJl2xMWEYyYshXlgHMurE9DPBRgJGjmgdDSgi24I8Q CYYmbSaCYaojRpevx13uDvWr2pf9VBmtUVfea2aB98Us9OR6aknT20Htlyj7Np5BLpUl 3HYdmoHzGcOg0FHCFbEX0fzGwwF1xX6S0w/qRmNnEVhM3wqThlwq//LaTdiFKgk6B3Kd aPjTKr5PR/hjvOqfMazrrc5UH2ir+JsLiOgpwqG7lrRECbtCjcueVw2oN22yraY+6b2u JQrkpf/f7QS0PFeP4SRt3A6LshHVee1Bt1o05gDWtw8lT7xePRHuefKUlbYx+DumRzfb P3pQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; t=1681058938; h=content-transfer-encoding:in-reply-to:content-language:references :cc:to:subject:from:user-agent:mime-version:date:message-id :x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=ShVq2ADCVfvgmdX2n9FqpBRVYZ0AkpDjoaZsweYGyEM=; b=EEA/csuFTb3wFOx8ucbn0OrGJUWE8mXA0w766bRzRs9kPES6L9aNIwMM3UGTyKbrJE iyv5BExKQVsBr4gK2wqcc1Y6rpb5R58G5p4tuYZRU23MUe2EzMzM++hGkeDSgwp924c5 niHNOmZKxmCCcjyh6dixIr4Wwmx9zzjy0vJBoalhba8qmBwcmY1VHjjTg1SgaLFPtXJm bjxrd3daKLpdejbWuAvy6eZ+dEB6+NqU3rbGsgtClNIIGl26XO5HRjjdQQRw78PYY3xp iE20/dtLmHXYeK39N0MnHSVruxQT/wPEF3jSbiIhE/hHAy5LEiDbEMFUAEa1w9/KgPxJ BC5g== X-Gm-Message-State: AAQBX9eCnMJZuEbR97N4DAksoaC0k3+Z4ITcFtkDOPVcAtPHaOFzJL/I j7v0YHJTvUrinhEaqePeHEM= X-Received: by 2002:a4a:88cf:0:b0:541:b668:31c5 with SMTP id q15-20020a4a88cf000000b00541b66831c5mr1976534ooh.8.1681058938269; Sun, 09 Apr 2023 09:48:58 -0700 (PDT) Received: from [192.168.54.90] (static.220.238.itcsa.net. [190.15.220.238]) by smtp.gmail.com with ESMTPSA id t8-20020a4aadc8000000b00541854d066bsm3709260oon.10.2023.04.09.09.48.55 (version=TLS1_3 cipher=TLS_AES_128_GCM_SHA256 bits=128/128); Sun, 09 Apr 2023 09:48:57 -0700 (PDT) Message-ID: <8d76bb7f-73d8-cfe9-462c-d02d97f436b0@gmail.com> Date: Sun, 9 Apr 2023 13:48:54 -0300 MIME-Version: 1.0 User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Thunderbird/102.9.1 From: Martin Rodriguez Reboredo Subject: Re: [PATCH v3 10/13] rust: introduce `current` To: Wedson Almeida Filho , rust-for-linux@vger.kernel.org Cc: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?Q?Bj=c3=b6rn_Roy_Baron?= , linux-kernel@vger.kernel.org, Wedson Almeida Filho , Ingo Molnar , Peter Zijlstra References: <20230408075340.25237-1-wedsonaf@gmail.com> <20230408075340.25237-10-wedsonaf@gmail.com> Content-Language: en-US In-Reply-To: <20230408075340.25237-10-wedsonaf@gmail.com> Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 7bit X-Spam-Status: No, score=-3.1 required=5.0 tests=DKIM_SIGNED,DKIM_VALID, DKIM_VALID_AU,DKIM_VALID_EF,FREEMAIL_FROM,NICE_REPLY_A, RCVD_IN_DNSWL_NONE,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 On 4/8/23 04:53, Wedson Almeida Filho wrote: > From: Wedson Almeida Filho > > This allows Rust code to get a reference to the current task without > having to increment the refcount, but still guaranteeing memory safety. > > Cc: Ingo Molnar > Cc: Peter Zijlstra > Signed-off-by: Wedson Almeida Filho > --- > v1 -> v2: Make `current` a macro to prevent it from escaping the caller > v2 -> v3: > - Mention `current` macro in `Task::current` > - Hide implementation of `TaskRef` inside `Task::current` > > rust/helpers.c | 6 +++ > rust/kernel/prelude.rs | 2 + > rust/kernel/task.rs | 88 +++++++++++++++++++++++++++++++++++++++++- > 3 files changed, 95 insertions(+), 1 deletion(-) > > diff --git a/rust/helpers.c b/rust/helpers.c > index 58a194042c86..96441744030e 100644 > --- a/rust/helpers.c > +++ b/rust/helpers.c > @@ -100,6 +100,12 @@ bool rust_helper_refcount_dec_and_test(refcount_t *r) > } > EXPORT_SYMBOL_GPL(rust_helper_refcount_dec_and_test); > > +struct task_struct *rust_helper_get_current(void) > +{ > + return current; > +} > +EXPORT_SYMBOL_GPL(rust_helper_get_current); > + > void rust_helper_get_task_struct(struct task_struct *t) > { > get_task_struct(t); > diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs > index fcdc511d2ce8..c28587d68ebc 100644 > --- a/rust/kernel/prelude.rs > +++ b/rust/kernel/prelude.rs > @@ -36,3 +36,5 @@ pub use super::error::{code::*, Error, Result}; > pub use super::{str::CStr, ThisModule}; > > pub use super::init::{InPlaceInit, Init, PinInit}; > + > +pub use super::current; > diff --git a/rust/kernel/task.rs b/rust/kernel/task.rs > index d70cad131956..5269a562cb1b 100644 > --- a/rust/kernel/task.rs > +++ b/rust/kernel/task.rs > @@ -5,7 +5,17 @@ > //! C header: [`include/linux/sched.h`](../../../../include/linux/sched.h). > > use crate::{bindings, types::Opaque}; > -use core::ptr; > +use core::{marker::PhantomData, ops::Deref, ptr}; > + > +/// Returns the currently running task. > +#[macro_export] > +macro_rules! current { > + () => { > + // SAFETY: Deref + addr-of below create a temporary `TaskRef` that cannot outlive the > + // caller. > + unsafe { &*$crate::task::Task::current() } > + }; > +} > > /// Wraps the kernel's `struct task_struct`. > /// > @@ -15,6 +25,42 @@ use core::ptr; > /// > /// Instances of this type are always ref-counted, that is, a call to `get_task_struct` ensures > /// that the allocation remains valid at least until the matching call to `put_task_struct`. > +/// > +/// # Examples > +/// > +/// The following is an example of getting the PID of the current thread with zero additional cost > +/// when compared to the C version: > +/// > +/// ``` > +/// let pid = current!().pid(); > +/// ``` > +/// > +/// Getting the PID of the current process, also zero additional cost: > +/// > +/// ``` > +/// let pid = current!().group_leader().pid(); > +/// ``` > +/// > +/// Getting the current task and storing it in some struct. The reference count is automatically > +/// incremented when creating `State` and decremented when it is dropped: > +/// > +/// ``` > +/// use kernel::{task::Task, types::ARef}; > +/// > +/// struct State { > +/// creator: ARef, > +/// index: u32, > +/// } > +/// > +/// impl State { > +/// fn new() -> Self { > +/// Self { > +/// creator: current!().into(), > +/// index: 0, > +/// } > +/// } > +/// } > +/// ``` > #[repr(transparent)] > pub struct Task(pub(crate) Opaque); > > @@ -27,6 +73,46 @@ unsafe impl Sync for Task {} > type Pid = bindings::pid_t; > > impl Task { > + /// Returns a task reference for the currently executing task/thread. > + /// > + /// The recommended way to get the current task/thread is to use the > + /// [`current`](crate::current) macro because it is safe. > + /// > + /// # Safety > + /// > + /// Callers must ensure that the returned object doesn't outlive the current task/thread. > + pub unsafe fn current() -> impl Deref { > + pub struct TaskRef<'a> { > + task: &'a Task, > + _not_send: PhantomData<*mut ()>, > + } I'd had named this as `CurrentTaskRef`, but since this is not exposed to users then there are no problems whatsoever. > + > + impl Deref for TaskRef<'_> { > + type Target = Task; > + > + fn deref(&self) -> &Self::Target { > + self.task > + } > + } > + > + impl From> for crate::types::ARef { > + fn from(t: TaskRef<'_>) -> Self { > + t.deref().into() > + } > + } > + > + // SAFETY: Just an FFI call with no additional safety requirements. > + let ptr = unsafe { bindings::get_current() }; > + > + TaskRef { > + // SAFETY: If the current thread is still running, the current task is valid. Given > + // that `TaskRef` is not `Send`, we know it cannot be transferred to another thread > + // (where it could potentially outlive the caller). > + task: unsafe { &*ptr.cast() }, > + _not_send: PhantomData, > + } > + } > + > /// Returns the group leader of the given task. > pub fn group_leader(&self) -> &Task { > // SAFETY: By the type invariant, we know that `self.0` is a valid task. Valid tasks always Reviewed-by: Martin Rodriguez Reboredo