From patchwork Fri Jun 28 14:57:14 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13716290 Received: from mail-lj1-f202.google.com (mail-lj1-f202.google.com [209.85.208.202]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id F1F591C232A for ; Fri, 28 Jun 2024 14:57:50 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.208.202 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719586674; cv=none; b=ecp81KdhFLjzJZlCMYH3qn/3XBEiYys601zkc7yD7ZBI6MuuW/V1ejHsIoikkX/sURSParajNgBW5YdC/wohRBpzioWJgHXG6G2YTz/aQq5VlDd2mDaqmi4RcUlNARZUXaHpkmogmyL6djQVM2MPOupFCRuijFT2O+gc5CpWuB0= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719586674; c=relaxed/simple; bh=dnIlIunhctrVQa7CZuSuRAKQF6iSqLvH+8Mk0KeN8so=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=qAqUN1KJ8rcteQedvvyPmTweQWiC0Pdf0JVNLZyEEkWRPDC6CONYK3ICKvsMQsBECKwJR2RsFhiuG7S4Bb8icaIo1/N1PYCNrRnfGMKQWYfm+w83dikDw2I9l4i184gsm8xmUbbxWeyGdLJsAEyIM001R2eck6BJu3Rlpgpygqg= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=K9+FNeZ8; arc=none smtp.client-ip=209.85.208.202 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="K9+FNeZ8" Received: by mail-lj1-f202.google.com with SMTP id 38308e7fff4ca-2ee4e9b77c1so4819871fa.1 for ; Fri, 28 Jun 2024 07:57:50 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1719586669; x=1720191469; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=Q9wOjTxToM/VZGpXclh0mo0L+KKkVr7MLa7ER9ZM6qQ=; b=K9+FNeZ8Vj/aaDdAUk64KTvjiKeecv0ugBI9O3zHUZ4sGJ1ZAdawUeLTzBIEx27cyJ bxktOW77rtzZRuHOHzz0DaX5Sn0SNrPdmUiINfkHPySkJ0mNa+WKLj+KYw2j6tQYti8o GZJZe72PPyO9NiZlGPWyXLEH8P04krUqA0gtGYvYbTlMtc79QOMj6AYrullRzh7X9lg4 HGyKwkG5W1KboLC8EfFrGHJlM4u4GUYYCR6Vz9h2v3jq576j1MIDaKUd/+9epQCOrFpZ c71I46Z6I5aeN3tt8BI09jLUAqS8RXeWibXa6avoESwpO8VNT1XGOEfsdUUxb7PgXmW2 J8bw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1719586669; x=1720191469; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=Q9wOjTxToM/VZGpXclh0mo0L+KKkVr7MLa7ER9ZM6qQ=; b=eJrXRPkFaL95iURxIKKKEyqAxEmJXHXknyg5lXWKLx8AYHMvNX71J81PDB+GcWit3z 1FAWBRELinhViZBGKv02hAz5VNxaD8Do7hgNZI2FjJTsBG73UWcdjwGpzBduSxGDG/24 8a1p70cgyHhqWCDfg5oVH4xe82FzYg82NgawmxuCA5s8IKzVgFU6A9q3IITdNukK+kAL Ws6fSBE3e9Gzg4DWLcUszRQ2z0/F7hlgFuzPndI6MoEjQjFrVLCAizqtjAlYCTFZUDIY OnsceYpLqHAYz1dDmaf1tQ6If9JRnH0Rt6yTc7smUNRbVKV9dkuh9ayCUlA3W+w09CHj LdMg== X-Forwarded-Encrypted: i=1; AJvYcCWCPTtjld40/Yofk9Vr3mVDR/OBgi/iO9zhHCrsSeN9OKSvTSlKKo0xL6VYmzquAeyost/YV51lJZNuQKOqxbxr6sW0JOOfjUw0FCp24A== X-Gm-Message-State: AOJu0YycGdpJ20/ITKuhs1eAJzenQBj2GeLFK2Czhx4DX8kbgbTbSXJg InTDC9XiMc7p5+DhBa7rtczd4eEx7XLWMHdcnPVyYkmMwYhTktjSh1LuzAZu1xQoPhwWpQptvJw nq71JsiVR2KZGgA== X-Google-Smtp-Source: AGHT+IHn6945McCpht6akp9tL+P4rX2ARHjAj5ya+nObFpzWQ7TQWwUYhLBZaIG+F5ly47WhTp71006s6g7apw8= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a2e:b043:0:b0:2ec:36aa:5b6a with SMTP id 38308e7fff4ca-2ee53bed2f4mr25511fa.2.1719586668861; Fri, 28 Jun 2024 07:57:48 -0700 (PDT) Date: Fri, 28 Jun 2024 14:57:14 +0000 In-Reply-To: <20240628-alice-file-v7-0-4d701f6335f3@google.com> Precedence: bulk X-Mailing-List: linux-fsdevel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240628-alice-file-v7-0-4d701f6335f3@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=5307; i=aliceryhl@google.com; h=from:subject:message-id; bh=dnIlIunhctrVQa7CZuSuRAKQF6iSqLvH+8Mk0KeN8so=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmfs9isGDeBVdq2rGeAByjfoJAKdLZwjO61D4gz nmQSlFolFOJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZn7PYgAKCRAEWL7uWMY5 RmQOEACOvfH48MDaMM46CN+vX0WX/gIxKh8aY4N4mumRZrEY0QARDIPEBQOKc336ILSdaQq4mIn eWiKRyIuM8BXr7/X/6kk00ABRXIP88WwnvmHr28UWGh7piDhNFD0dAJCNnCYp/Tbj7s8tX8v37Q 49AbbtwYrGF6D8M5uGwUW0UCRmukQwsF83VbBVGUxz6ud67ItkeKGCNDU1JvCMI+SSi4ooyxlz0 qZQ43nTnl7Nco/C90jYipg4Bd9fRE4K1aFevAqTGYxlypCns9Zlmj/WhT1+ZPfKkgqeeitxWnjI 4dVQ3YuI7CiRslUcrVEhLbn+0sDJhofxTQM11pBP9ZtxVlyZ/0sYF2NNLPHCTCvYMyEv+GhRXAv 7uNhdJChT2CMRHe4RgaxqODq31JcqXUKA8jl5ikL8YqaZ/tNu0vmPNQWxlrXL0e1aUxSySX35Ct uwzd8M5EKj/4l0pe+buwrfqRTgHc/Pv/AdbIIozxE+nzYZ3LvkJzZ33lNdA/GMy1QFMdoIYKRGw b5oYp4GetSint6tAuDjAxnw67OLkyOe7ZNtgynPTQLGLz3UDTLEBk0tAVLrceu+SJJ3D0Evg42O yfeNMbg2oZ/9DUmlvpqKfhi6XSQ6jnzF/QCTOEnmL+VmuhRmZ0isxfRasi75ZtBKeVEiE6Srfvz 8F1B/cfgTUpfxPQ== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240628-alice-file-v7-1-4d701f6335f3@google.com> Subject: [PATCH v7 1/8] rust: types: add `NotThreadSafe` From: Alice Ryhl To: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , " =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= " , Benno Lossin , Andreas Hindborg , Peter Zijlstra , Alexander Viro , Christian Brauner , Greg Kroah-Hartman , " =?utf-8?q?Arve_Hj?= =?utf-8?q?=C3=B8nnev=C3=A5g?= " , Todd Kjos , Martijn Coenen , Joel Fernandes , Carlos Llamas , Suren Baghdasaryan Cc: Dan Williams , Kees Cook , Matthew Wilcox , Thomas Gleixner , Daniel Xu , linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-fsdevel@vger.kernel.org, Alice Ryhl , Trevor Gross , Martin Rodriguez Reboredo This introduces a new marker type for types that shouldn't be thread safe. By adding a field of this type to a struct, it becomes non-Send and non-Sync, which means that it cannot be accessed in any way from threads other than the one it was created on. This is useful for APIs that require globals such as `current` to remain constant while the value exists. We update two existing users in the Kernel to use this helper: * `Task::current()` - moving the return type of this value to a different thread would not be safe as you can no longer be guaranteed that the `current` pointer remains valid. * Lock guards. Mutexes and spinlocks should be unlocked on the same thread as where they were locked, so we enforce this using the Send trait. There are also additional users in later patches of this patchset. See [1] and [2] for the discussion that led to the introduction of this patch. Link: https://lore.kernel.org/all/nFDPJFnzE9Q5cqY7FwSMByRH2OAn_BpI4H53NQfWIlN6I2qfmAqnkp2wRqn0XjMO65OyZY4h6P4K2nAGKJpAOSzksYXaiAK_FoH_8QbgBI4=@proton.me/ [1] Link: https://lore.kernel.org/all/nFDPJFnzE9Q5cqY7FwSMByRH2OAn_BpI4H53NQfWIlN6I2qfmAqnkp2wRqn0XjMO65OyZY4h6P4K2nAGKJpAOSzksYXaiAK_FoH_8QbgBI4=@proton.me/ [2] Suggested-by: Benno Lossin Reviewed-by: Benno Lossin Reviewed-by: Trevor Gross Reviewed-by: Martin Rodriguez Reboredo Signed-off-by: Alice Ryhl --- rust/kernel/sync/lock.rs | 13 +++++++++---- rust/kernel/task.rs | 10 ++++++---- rust/kernel/types.rs | 18 ++++++++++++++++++ 3 files changed, 33 insertions(+), 8 deletions(-) diff --git a/rust/kernel/sync/lock.rs b/rust/kernel/sync/lock.rs index f6c34ca4d819..d6e9bab114b8 100644 --- a/rust/kernel/sync/lock.rs +++ b/rust/kernel/sync/lock.rs @@ -6,8 +6,13 @@ //! spinlocks, raw spinlocks) to be provided with minimal effort. use super::LockClassKey; -use crate::{init::PinInit, pin_init, str::CStr, types::Opaque, types::ScopeGuard}; -use core::{cell::UnsafeCell, marker::PhantomData, marker::PhantomPinned}; +use crate::{ + init::PinInit, + pin_init, + str::CStr, + types::{NotThreadSafe, Opaque, ScopeGuard}, +}; +use core::{cell::UnsafeCell, marker::PhantomPinned}; use macros::pin_data; pub mod mutex; @@ -139,7 +144,7 @@ pub fn lock(&self) -> Guard<'_, T, B> { pub struct Guard<'a, T: ?Sized, B: Backend> { pub(crate) lock: &'a Lock, pub(crate) state: B::GuardState, - _not_send: PhantomData<*mut ()>, + _not_send: NotThreadSafe, } // SAFETY: `Guard` is sync when the data protected by the lock is also sync. @@ -191,7 +196,7 @@ pub(crate) unsafe fn new(lock: &'a Lock, state: B::GuardState) -> Self { Self { lock, state, - _not_send: PhantomData, + _not_send: NotThreadSafe, } } } diff --git a/rust/kernel/task.rs b/rust/kernel/task.rs index 55dff7e088bf..278c623de0c6 100644 --- a/rust/kernel/task.rs +++ b/rust/kernel/task.rs @@ -4,10 +4,12 @@ //! //! C header: [`include/linux/sched.h`](srctree/include/linux/sched.h). -use crate::types::Opaque; +use crate::{ + bindings, + types::{NotThreadSafe, Opaque}, +}; use core::{ ffi::{c_int, c_long, c_uint}, - marker::PhantomData, ops::Deref, ptr, }; @@ -106,7 +108,7 @@ impl Task { pub unsafe fn current() -> impl Deref { struct TaskRef<'a> { task: &'a Task, - _not_send: PhantomData<*mut ()>, + _not_send: NotThreadSafe, } impl Deref for TaskRef<'_> { @@ -125,7 +127,7 @@ fn deref(&self) -> &Self::Target { // 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, + _not_send: NotThreadSafe, } } diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index 2e7c9008621f..93734677cfe7 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -409,3 +409,21 @@ pub enum Either { /// Constructs an instance of [`Either`] containing a value of type `R`. Right(R), } + +/// Zero-sized type to mark types not [`Send`]. +/// +/// Add this type as a field to your struct if your type should not be sent to a different task. +/// Since [`Send`] is an auto trait, adding a single field that is `!Send` will ensure that the +/// whole type is `!Send`. +/// +/// If a type is `!Send` it is impossible to give control over an instance of the type to another +/// task. This is useful to include in types that store or reference task-local information. A file +/// descriptor is an example of such task-local information. +pub type NotThreadSafe = PhantomData<*mut ()>; + +/// Used to construct instances of type [`NotThreadSafe`] similar to how `PhantomData` is +/// constructed. +/// +/// [`NotThreadSafe`]: type@NotThreadSafe +#[allow(non_upper_case_globals)] +pub const NotThreadSafe: NotThreadSafe = PhantomData; From patchwork Fri Jun 28 14:57:15 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13716291 Received: from mail-lj1-f201.google.com (mail-lj1-f201.google.com [209.85.208.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 1C76B1C688F for ; Fri, 28 Jun 2024 14:57:54 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.208.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719586675; cv=none; b=YERWFTJuUPcyoDFpwvdHxV+uOeIWn37Kt7+bxo57Yins5UuHP8/duR6C7vmCerYvKqfNAaNxoYnp7TOP3gLo61z1fSIN3p+g7gSaJSCbGvnNZbg+Sk1AodYBO6o1yrjqA+hUc/u6WpW+o7WskZYPtVid9GhTsng3b9ct7pYEwNA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719586675; c=relaxed/simple; bh=4wlabOF4qnHHRK4JrQrSunzQwpBlfLkz5DsTWMrd2qw=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=kDLrGr7JCfvJ4ZXFtjWOP53bjp82+IT0i58LHAB8a1LnHtm+Le3pDhPl72qNn29dZnsa0PdlGlbyUS38Dx6W2UTtQFbvbMsJrc3FcSpZFhWaYZP5NvFpYyEHMsVsqotulv8iMw679HZa0MiRhLXP50pTmZORj98hSJLuhYgo4QU= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=A4YToG7l; arc=none smtp.client-ip=209.85.208.201 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="A4YToG7l" Received: by mail-lj1-f201.google.com with SMTP id 38308e7fff4ca-2ec507c1b59so8941631fa.3 for ; Fri, 28 Jun 2024 07:57:53 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1719586672; x=1720191472; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=uL/9BQ4R/uRrk1opn7GDHDLDYKLgQIp+STPcPNnv19c=; b=A4YToG7lwy2fc4NgsHjG0ST23a/SuB/hdDWtFF+LKXF71Hxc7us+j0cySNz7uDdKqE Ldq3Un6NwQWdLocWzeV0aL8xGwj6pEJRVIIVpbHfbQ/fJimuJrrJsk1lbk0N0tQl23XH wcgbXka8quI9RfYofLHJoDqTxtmnI/rqXFTmQe21f6h+uzCsbpdcpFO3+XIHumavOBhN qlKuY5Jjd+gp2MUyKwqHMi51aIiny6LAYjgPkB6PdcTzOIgkyktQ8DImWzBNP2gqNAFs kmeYu3+cgWLBo97f+0Le0VJXHfT5nPl2cVIXJj6WaLd5LXPpeZOoc2YSZX4wLdROv3DK S+Iw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1719586672; x=1720191472; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=uL/9BQ4R/uRrk1opn7GDHDLDYKLgQIp+STPcPNnv19c=; b=QqY+ZoXL8pOVGzqKBkK95xfn7bcb+M6IfeFvyZsLuazG4cbYH1P+9U+e0HaaNwxmbz vlIaxunn6PSnyFRRigd8zGxmi47sdrfBC54IT0EozEoU40+0oGmziNDlzKvXmXhYyHmF iwEiweR8XG+yoQdtCLrVdO5xv6lzIT/9yKdmZVQITBYRtNYkzwGNoD82AKewctxV7MCw +WhXSebE30FadmYZaNCjW1N0vmYW5c9LTD/7QZD2icM3lYk5BF08qiB7w+VY/j/SzETm o51O2e6mZ29Y9Y0cNs+1mDkLjJSKY3D3Cx0Dv8nAFDcZXIJn1i0mS5I/IAZaJuduvKB0 Limw== X-Forwarded-Encrypted: i=1; AJvYcCU+W6PXIPhAf9kcHFBYzsl8wyA3+fIxyXawdxnLMItIdFlus/87XEI+OffHHzVVu/0y8GIh67qWy+uwd5eF/x+eRsUEnryPJNWkMrYKMA== X-Gm-Message-State: AOJu0YxZxJYYRxK9vfigb+Yjpijf/iNrvhoF25YHkGWSZXM5qgXNtPG2 irGCBtNJbmz2Nx1RVzLdO5xzOuHVhfB12jJ/+jbNRP/NJ7X6tkhST9rh5LkFrJ+aJvrNotfge8P w42/UCrlY1jf8Qg== X-Google-Smtp-Source: AGHT+IF4x8A8zxRvt0MO24DrI0ZYp3Fh+ug0LLXFI1pHBsJMoatc+FQqu4gSdGFjmz3I91QmsTd5qtePAA3XHHg= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a2e:9ecd:0:b0:2ec:50c9:a379 with SMTP id 38308e7fff4ca-2ec5b3029c5mr201621fa.1.1719586672124; Fri, 28 Jun 2024 07:57:52 -0700 (PDT) Date: Fri, 28 Jun 2024 14:57:15 +0000 In-Reply-To: <20240628-alice-file-v7-0-4d701f6335f3@google.com> Precedence: bulk X-Mailing-List: linux-fsdevel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240628-alice-file-v7-0-4d701f6335f3@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=2382; i=aliceryhl@google.com; h=from:subject:message-id; bh=4wlabOF4qnHHRK4JrQrSunzQwpBlfLkz5DsTWMrd2qw=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmfs9jeYGVfccOjNJJgD0mBPSJBqVxCXsT9A+Rf xXH8RwrXKSJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZn7PYwAKCRAEWL7uWMY5 Rk7rD/0VEce2HuPYmy5wHQ2PKiRYdvjySXoXmml+ODukz/MvKujn4F0D8Auob2a9rzz7CajFKKF 1KxmfxBBHxF0WYHZvZ3fdF6/pazjAX0sQ795ungMt+9bpI/4kYfJ7ITcSc+oTgmrdgbx4vT5UUQ q9+F2pVzeUwyvRBdI2Diykosg40NX74C1KsWjDDpEPlzKVBmUCLxixN21wh7rEw5g8eUCtb088d KktzouRVrVw9RIb7t3vUG8ZOsgeDRYC7/50Vs+scjj2HTQKzxdDADlwNdXiydbNoYABQMTAsc2X R1aHw2/bSxUVDhRI4/GA2OYddyORuZqMvkPZxiwbTSdRIvVA7KYlvvAFl4DJpEGrAoL5YLfEh9c cAEeb3xoNsy4JCAfsPP9pNUwJ4b3T3MtRUPF/85PzGB4HTssf9aatvWPH2S9TrJCeOxpCatl0eJ qhA6xtw6ussyDiN9kBmTQBz9zqdRNG8AijhUODDBowz/TAA+5Lvwq68nIxXKDTmKq8aaLnZy3n2 vEthTYJm20xQ+udE0XA3ck4wN5Xurj2qWTLjlkYGclK3M673hELdkDEL6icatFS3a1bYqweK8e4 BAJFQaW2GJImHJRXvyOWgqD4UEZQ7VT0qf1hbyus/TazFFmfoM52ITkqFnYsBy0hL9bJBdg7l4C 4Xn8Jv6eOzC6OZw== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240628-alice-file-v7-2-4d701f6335f3@google.com> Subject: [PATCH v7 2/8] rust: task: add `Task::current_raw` From: Alice Ryhl To: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , " =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= " , Benno Lossin , Andreas Hindborg , Peter Zijlstra , Alexander Viro , Christian Brauner , Greg Kroah-Hartman , " =?utf-8?q?Arve_Hj?= =?utf-8?q?=C3=B8nnev=C3=A5g?= " , Todd Kjos , Martijn Coenen , Joel Fernandes , Carlos Llamas , Suren Baghdasaryan Cc: Dan Williams , Kees Cook , Matthew Wilcox , Thomas Gleixner , Daniel Xu , linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-fsdevel@vger.kernel.org, Alice Ryhl , Martin Rodriguez Reboredo , Trevor Gross Introduces a safe function for getting a raw pointer to the current task. When writing bindings that need to access the current task, it is often more convenient to call a method that directly returns a raw pointer than to use the existing `Task::current` method. However, the only way to do that is `bindings::get_current()` which is unsafe since it calls into C. By introducing `Task::current_raw()`, it becomes possible to obtain a pointer to the current task without using unsafe. Link: https://lore.kernel.org/all/CAH5fLgjT48X-zYtidv31mox3C4_Ogoo_2cBOCmX0Ang3tAgGHA@mail.gmail.com/ Reviewed-by: Benno Lossin Reviewed-by: Martin Rodriguez Reboredo Reviewed-by: Trevor Gross Signed-off-by: Alice Ryhl --- rust/kernel/task.rs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/rust/kernel/task.rs b/rust/kernel/task.rs index 278c623de0c6..367b4bbddd9f 100644 --- a/rust/kernel/task.rs +++ b/rust/kernel/task.rs @@ -97,6 +97,15 @@ unsafe impl Sync for Task {} type Pid = bindings::pid_t; impl Task { + /// Returns a raw pointer to the current task. + /// + /// It is up to the user to use the pointer correctly. + #[inline] + pub fn current_raw() -> *mut bindings::task_struct { + // SAFETY: Getting the current pointer is always safe. + unsafe { bindings::get_current() } + } + /// Returns a task reference for the currently executing task/thread. /// /// The recommended way to get the current task/thread is to use the @@ -119,14 +128,12 @@ fn deref(&self) -> &Self::Target { } } - // SAFETY: Just an FFI call with no additional safety requirements. - let ptr = unsafe { bindings::get_current() }; - + let current = Task::current_raw(); 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() }, + task: unsafe { &*current.cast() }, _not_send: NotThreadSafe, } } From patchwork Fri Jun 28 14:57:16 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13716292 Received: from mail-yb1-f201.google.com (mail-yb1-f201.google.com [209.85.219.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 5F9771C68B7 for ; Fri, 28 Jun 2024 14:57:56 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.219.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719586679; cv=none; b=F5W/kFDKMjgML7GGI/rnUqStssUWt/nkPHycQA9zhdcaAWpkNKEkAVpSD1l1Wp1WdGLerxNxynKZwKHNh2pqMnZDqbdgV5ioHrXZlwT5s2PqcVwlQqm0MNn0IaeIbIACj2rQac3Wl8D6Urixa5b2Y2Nu3BAf/MqM1O+4+XDty1c= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719586679; c=relaxed/simple; bh=LFVEzErzqQ1q40e9Ik4zdJmABvLJ02IJ5xrzhdx+PXI=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=UrGOgZg1jt3Awm/qMuVU41aatNS0QSrAPZskV4HwrQehsLZAo/UrX1Q8gHJk6GXQkuqs5q3zYpUecYyuSpKdQYNiaivq79JrWRLDkR0YPihRddFZI3yXx5mpU96/V6rYNVIhqH06yFg3S8n01v20t6ygPvPccVxK5hYOmFeZnL8= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=XoNt/gRu; arc=none smtp.client-ip=209.85.219.201 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="XoNt/gRu" Received: by mail-yb1-f201.google.com with SMTP id 3f1490d57ef6-e036440617fso566346276.1 for ; Fri, 28 Jun 2024 07:57:56 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1719586675; x=1720191475; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=H5+zgWJ9B94kDR/O8VwZ3ua2XMRwjFAGUwG5glPRAqU=; b=XoNt/gRu5zggLPr72MWG/eJZafR2eL0lEitaJKAs4w8gs7fQi1I5aggJBXfoB7mHar +QqQd/Un1pk9CRQ88zoqOyzW49nHskrEa/laLgFSbaneIT82EovDMe9IWKlOYs2B9JU4 VUQtvwXiKc2o26NzFNO3aVjS8wVkhHojdyX03C17l/8ZJfX0smuJhbAHwfGqsxRK2BZd KYkQsWlsOZnw+S2PuXWwRauRSyEtNROsaovx9dsdj1TYELehrvJny1TDALnD/mrV+0jJ uMvjpL3ffCYYwVkEGvzS+NIgX76yxRDVzH680IaUz8RpXVgqgk7AL3szSYNE8F+4IGPs 70Dw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1719586675; x=1720191475; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=H5+zgWJ9B94kDR/O8VwZ3ua2XMRwjFAGUwG5glPRAqU=; b=iFjnnnfvSLUbNKsAEBgwogdZFbjCj8QGXfSkQDXx+/fY83WD3Vx2pZRM/ou8UhYEfK 6hR5RYvA2BJoCJbDfxg8rWTb1TnVA2zxANS5LN3R8roJkLNRF74eTwlnBLFqJrkffiPX oRud51FlrOCXSun3zAiR8y2KqfMfkVhsYVJkneKgJCEqfy7zNsaJZyzbr/0accVBgPKN wGufya9WRVNaP9dIu7FaGdS2Y/kqHfwAcQxPMoFuOscxET1uzPKr0Xpxp1Z8gRMWwShN lWAWVpqp9PAggZJNeaVSxteYf4ELMJ7/JIerM96BrgudCkotM5L1/5loLEbVbzhATwpr Y5dw== X-Forwarded-Encrypted: i=1; AJvYcCVbpotqToskGPso9woghRp0cFLlLKpoDuNAGjfbULpiyKBcJXwado+asrzwXmfO7vuGF+35CC2FCJXBKV0O59bYMvfgVmP9hylZ0HRGAw== X-Gm-Message-State: AOJu0YwjzbtWYNiolKR9zoCRmbrJ8yyx5BIAQoSuCxUvtNHAGOcwFxpE NPvcZ1UlwDMXehhqTwlDiwVXmBVCe09DsANiwmDxJ2Ov6K63qZA8/HlMD33IvgK+PV/HO5zutRo wyye3L+zqx4f8/w== X-Google-Smtp-Source: AGHT+IH1yUNkQMUavc8OS4Suuin/C8L91b71mgvTXxxkot66jc1d+CDf41sOEX3DF25EiLyonnSEPm0pUFKtKIw= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:6902:1006:b0:e03:4bf0:b21e with SMTP id 3f1490d57ef6-e034bf0b50dmr362286276.1.1719586675354; Fri, 28 Jun 2024 07:57:55 -0700 (PDT) Date: Fri, 28 Jun 2024 14:57:16 +0000 In-Reply-To: <20240628-alice-file-v7-0-4d701f6335f3@google.com> Precedence: bulk X-Mailing-List: linux-fsdevel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240628-alice-file-v7-0-4d701f6335f3@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=21643; i=aliceryhl@google.com; h=from:subject:message-id; bh=qVdBsDPrZIaWOXv+yX141pHKcTehsDvHW/vXiDQpPCk=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmfs9jW/FGnqCyVhc5lt/drZnDsdkwt8RDfX4x+ C8pG/kPzXmJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZn7PYwAKCRAEWL7uWMY5 RpWHD/4wI1b0drlSPe+yNJkP778UgiWe/8xPfoF8vWCtARJfwaICJi8m0hDx8wF5Dr4Rg+5QJkW E1QnmgJTsJKrargq577BfJgaGjsclKysPr6sM/SMlqbbMyacFsn5aIcSUWksctNoYnBqAzQAbqf S9UYTJqaAXbrjRjE9P85y95XDS+ysuph42H5eYiMebonpMJwUrfN97/twVIAU9wiXu6N1rbpwFn o1GYYVZUnCqKChlfoRwVr88ryYXdpBRjkV4A1WbRUIj9BSHfOHazPd4Vfeb1bPihR7oSWTVC/md 6dwJj7Rttw33GLKcDTgYDwUpyjQstYY0Naw88ER1sNX4bqU/j1TyAaeLj9nE4MMIeKSLJmElgOg 9YkWvlVqGoj7BQElVMeoJzYMGuAyKRixAR2V1g2VZiU8sF21lYXBhD8BoSplLyOt1HZOjlLWoHh UbT9ez6CoN4sEpuiG/tPYhU5Ri/AsLHUepEOJC6XLqGpPeBGA9+8scAAtoKLno+AzabRTxgSuPb oa/QE+WHFO1IbEvd2fB/5f1mmOjR1P0+8puf1OxLAckvscyLL29QmESxl2povTkvxwlRPxGxHBV AS+2NOTIH2QLK1PlTaOF0CbcLyFB2sskjB1kkYfmH4+UVt6aY2xJNaCPu7dVxo99VGGni3i6CRZ l+ItElUCzmbBjrg== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240628-alice-file-v7-3-4d701f6335f3@google.com> Subject: [PATCH v7 3/8] rust: file: add Rust abstraction for `struct file` From: Alice Ryhl To: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , " =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= " , Benno Lossin , Andreas Hindborg , Peter Zijlstra , Alexander Viro , Christian Brauner , Greg Kroah-Hartman , " =?utf-8?q?Arve_Hj?= =?utf-8?q?=C3=B8nnev=C3=A5g?= " , Todd Kjos , Martijn Coenen , Joel Fernandes , Carlos Llamas , Suren Baghdasaryan Cc: Dan Williams , Kees Cook , Matthew Wilcox , Thomas Gleixner , Daniel Xu , linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-fsdevel@vger.kernel.org, Alice Ryhl From: Wedson Almeida Filho This abstraction makes it possible to manipulate the open files for a process. The new `File` struct wraps the C `struct file`. When accessing it using the smart pointer `ARef`, the pointer will own a reference count to the file. When accessing it as `&File`, then the reference does not own a refcount, but the borrow checker will ensure that the reference count does not hit zero while the `&File` is live. Since this is intended to manipulate the open files of a process, we introduce an `fget` constructor that corresponds to the C `fget` method. In future patches, it will become possible to create a new fd in a process and bind it to a `File`. Rust Binder will use these to send fds from one process to another. We also provide a method for accessing the file's flags. Rust Binder will use this to access the flags of the Binder fd to check whether the non-blocking flag is set, which affects what the Binder ioctl does. This introduces a struct for the EBADF error type, rather than just using the Error type directly. This has two advantages: * `File::fget` returns a `Result, BadFdError>`, which the compiler will represent as a single pointer, with null being an error. This is possible because the compiler understands that `BadFdError` has only one possible value, and it also understands that the `ARef` smart pointer is guaranteed non-null. * Additionally, we promise to users of the method that the method can only fail with EBADF, which means that they can rely on this promise without having to inspect its implementation. That said, there are also two disadvantages: * Defining additional error types involves boilerplate. * The question mark operator will only utilize the `From` trait once, which prevents you from using the question mark operator on `BadFdError` in methods that return some third error type that the kernel `Error` is convertible into. (However, it works fine in methods that return `Error`.) Signed-off-by: Wedson Almeida Filho Co-developed-by: Daniel Xu Signed-off-by: Daniel Xu Co-developed-by: Alice Ryhl Signed-off-by: Alice Ryhl --- fs/file.c | 7 + rust/bindings/bindings_helper.h | 2 + rust/helpers.c | 7 + rust/kernel/file.rs | 373 ++++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + rust/kernel/types.rs | 8 + 6 files changed, 398 insertions(+) diff --git a/fs/file.c b/fs/file.c index 8076aef9c210..18840b5bf524 100644 --- a/fs/file.c +++ b/fs/file.c @@ -1127,6 +1127,13 @@ EXPORT_SYMBOL(task_lookup_next_fdget_rcu); * * The fput_needed flag returned by fget_light should be passed to the * corresponding fput_light. + * + * (As an exception to rule 2, you can call filp_close between fget_light and + * fput_light provided that you capture a real refcount with get_file before + * the call to filp_close, and ensure that this real refcount is fput *after* + * the fput_light call.) + * + * See also the documentation in rust/kernel/file.rs. */ static unsigned long __fget_light(unsigned int fd, fmode_t mask) { diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index ddb5644d4fd9..541afef7ddc4 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -9,6 +9,8 @@ #include #include #include +#include +#include #include #include #include diff --git a/rust/helpers.c b/rust/helpers.c index 2c37a0f5d7a8..e68025b53342 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -25,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -165,6 +166,12 @@ rust_helper_krealloc(const void *objp, size_t new_size, gfp_t flags) } EXPORT_SYMBOL_GPL(rust_helper_krealloc); +struct file *rust_helper_get_file(struct file *f) +{ + return get_file(f); +} +EXPORT_SYMBOL_GPL(rust_helper_get_file); + /* * `bindgen` binds the C `size_t` type as the Rust `usize` type, so we can * use it in contexts where Rust expects a `usize` like slice (array) indices. diff --git a/rust/kernel/file.rs b/rust/kernel/file.rs new file mode 100644 index 000000000000..08551bf5c625 --- /dev/null +++ b/rust/kernel/file.rs @@ -0,0 +1,373 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Files and file descriptors. +//! +//! C headers: [`include/linux/fs.h`](srctree/include/linux/fs.h) and +//! [`include/linux/file.h`](srctree/include/linux/file.h) + +use crate::{ + bindings, + error::{code::*, Error, Result}, + types::{ARef, AlwaysRefCounted, Opaque}, +}; +use core::ptr; + +/// Flags associated with a [`File`]. +pub mod flags { + /// File is opened in append mode. + pub const O_APPEND: u32 = bindings::O_APPEND; + + /// Signal-driven I/O is enabled. + pub const O_ASYNC: u32 = bindings::FASYNC; + + /// Close-on-exec flag is set. + pub const O_CLOEXEC: u32 = bindings::O_CLOEXEC; + + /// File was created if it didn't already exist. + pub const O_CREAT: u32 = bindings::O_CREAT; + + /// Direct I/O is enabled for this file. + pub const O_DIRECT: u32 = bindings::O_DIRECT; + + /// File must be a directory. + pub const O_DIRECTORY: u32 = bindings::O_DIRECTORY; + + /// Like [`O_SYNC`] except metadata is not synced. + pub const O_DSYNC: u32 = bindings::O_DSYNC; + + /// Ensure that this file is created with the `open(2)` call. + pub const O_EXCL: u32 = bindings::O_EXCL; + + /// Large file size enabled (`off64_t` over `off_t`). + pub const O_LARGEFILE: u32 = bindings::O_LARGEFILE; + + /// Do not update the file last access time. + pub const O_NOATIME: u32 = bindings::O_NOATIME; + + /// File should not be used as process's controlling terminal. + pub const O_NOCTTY: u32 = bindings::O_NOCTTY; + + /// If basename of path is a symbolic link, fail open. + pub const O_NOFOLLOW: u32 = bindings::O_NOFOLLOW; + + /// File is using nonblocking I/O. + pub const O_NONBLOCK: u32 = bindings::O_NONBLOCK; + + /// File is using nonblocking I/O. + /// + /// This is effectively the same flag as [`O_NONBLOCK`] on all architectures + /// except SPARC64. + pub const O_NDELAY: u32 = bindings::O_NDELAY; + + /// Used to obtain a path file descriptor. + pub const O_PATH: u32 = bindings::O_PATH; + + /// Write operations on this file will flush data and metadata. + pub const O_SYNC: u32 = bindings::O_SYNC; + + /// This file is an unnamed temporary regular file. + pub const O_TMPFILE: u32 = bindings::O_TMPFILE; + + /// File should be truncated to length 0. + pub const O_TRUNC: u32 = bindings::O_TRUNC; + + /// Bitmask for access mode flags. + /// + /// # Examples + /// + /// ``` + /// use kernel::file; + /// # fn do_something() {} + /// # let flags = 0; + /// if (flags & file::flags::O_ACCMODE) == file::flags::O_RDONLY { + /// do_something(); + /// } + /// ``` + pub const O_ACCMODE: u32 = bindings::O_ACCMODE; + + /// File is read only. + pub const O_RDONLY: u32 = bindings::O_RDONLY; + + /// File is write only. + pub const O_WRONLY: u32 = bindings::O_WRONLY; + + /// File can be both read and written. + pub const O_RDWR: u32 = bindings::O_RDWR; +} + +/// Wraps the kernel's `struct file`. Thread safe. +/// +/// This represents an open file rather than a file on a filesystem. Processes generally reference +/// open files using file descriptors. However, file descriptors are not the same as files. A file +/// descriptor is just an integer that corresponds to a file, and a single file may be referenced +/// by multiple file descriptors. +/// +/// # Refcounting +/// +/// Instances of this type are reference-counted. The reference count is incremented by the +/// `fget`/`get_file` functions and decremented by `fput`. The Rust type `ARef` represents a +/// pointer that owns a reference count on the file. +/// +/// Whenever a process opens a file descriptor (fd), it stores a pointer to the file in its fd +/// table (`struct files_struct`). This pointer owns a reference count to the file, ensuring the +/// file isn't prematurely deleted while the file descriptor is open. In Rust terminology, the +/// pointers in `struct files_struct` are `ARef` pointers. +/// +/// ## Light refcounts +/// +/// Whenever a process has an fd to a file, it may use something called a "light refcount" as a +/// performance optimization. Light refcounts are acquired by calling `fdget` and released with +/// `fdput`. The idea behind light refcounts is that if the fd is not closed between the calls to +/// `fdget` and `fdput`, then the refcount cannot hit zero during that time, as the `struct +/// files_struct` holds a reference until the fd is closed. This means that it's safe to access the +/// file even if `fdget` does not increment the refcount. +/// +/// The requirement that the fd is not closed during a light refcount applies globally across all +/// threads - not just on the thread using the light refcount. For this reason, light refcounts are +/// only used when the `struct files_struct` is not shared with other threads, since this ensures +/// that other unrelated threads cannot suddenly start using the fd and close it. Therefore, +/// calling `fdget` on a shared `struct files_struct` creates a normal refcount instead of a light +/// refcount. +/// +/// Light reference counts must be released with `fdput` before the system call returns to +/// userspace. This means that if you wait until the current system call returns to userspace, then +/// all light refcounts that existed at the time have gone away. +/// +/// ### The file position +/// +/// Each `struct file` has a position integer, which is protected by the `f_pos_lock` mutex. +/// However, if the `struct file` is not shared, then the kernel may avoid taking the lock as a +/// performance optimization. +/// +/// The condition for avoiding the `f_pos_lock` mutex is different from the condition for using +/// `fdget`. With `fdget`, you may avoid incrementing the refcount as long as the current fd table +/// is not shared; it is okay if there are other fd tables that also reference the same `struct +/// file`. However, `fdget_pos` can only avoid taking the `f_pos_lock` if the entire `struct file` +/// is not shared, as different processes with an fd to the same `struct file` share the same +/// position. +/// +/// To represent files that are not thread safe due to this optimization, the [`LocalFile`] type is +/// used. +/// +/// ## Rust references +/// +/// The reference type `&File` is similar to light refcounts: +/// +/// * `&File` references don't own a reference count. They can only exist as long as the reference +/// count stays positive, and can only be created when there is some mechanism in place to ensure +/// this. +/// +/// * The Rust borrow-checker normally ensures this by enforcing that the `ARef` from which +/// a `&File` is created outlives the `&File`. +/// +/// * Using the unsafe [`File::from_ptr`] means that it is up to the caller to ensure that the +/// `&File` only exists while the reference count is positive. +/// +/// * You can think of `fdget` as using an fd to look up an `ARef` in the `struct +/// files_struct` and create an `&File` from it. The "fd cannot be closed" rule is like the Rust +/// rule "the `ARef` must outlive the `&File`". +/// +/// # Invariants +/// +/// * All instances of this type are refcounted using the `f_count` field. +/// * There must not be any active calls to `fdget_pos` on this file that did not take the +/// `f_pos_lock` mutex. +#[repr(transparent)] +pub struct File { + inner: Opaque, +} + +/// Wraps the kernel's `struct file`. Not thread safe. +/// +/// This type represents a file that is not known to be safe to transfer across thread boundaries. +/// To obtain a thread-safe [`File`], use the [`assume_no_fdget_pos`] conversion. +/// +/// See the documentation for [`File`] for more information. +/// +/// # Invariants +/// +/// * All instances of this type are refcounted using the `f_count` field. +/// * If there is an active call to `fdget_pos` that did not take the `f_pos_lock` mutex, then it +/// must be on the same thread as this `File`. +/// +/// [`assume_no_fdget_pos`]: LocalFile::assume_no_fdget_pos +pub struct LocalFile { + inner: Opaque, +} + +// SAFETY: This file is known to not have any active `fdget_pos` calls that did not take the +// `f_pos_lock` mutex, so it is safe to transfer it between threads. +unsafe impl Send for File {} + +// SAFETY: This file is known to not have any active `fdget_pos` calls that did not take the +// `f_pos_lock` mutex, so it is safe to access its methods from several threads in parallel. +unsafe impl Sync for File {} + +impl LocalFile { + /// Constructs a new `struct file` wrapper from a file descriptor. + /// + /// The file descriptor belongs to the current process, and there might be active local calls + /// to `fdget_pos` on the same file. + /// + /// To obtain an `ARef`, use the [`assume_no_fdget_pos`] function to convert. + /// + /// [`assume_no_fdget_pos`]: LocalFile::assume_no_fdget_pos + #[inline] + pub fn fget(fd: u32) -> Result, BadFdError> { + // SAFETY: FFI call, there are no requirements on `fd`. + let ptr = ptr::NonNull::new(unsafe { bindings::fget(fd) }).ok_or(BadFdError)?; + + // SAFETY: `bindings::fget` created a refcount, and we pass ownership of it to the `ARef`. + // + // INVARIANT: This file is in the fd table on this thread, so either all `fdget_pos` calls + // are on this thread, or the file is shared, in which case `fdget_pos` calls took the + // `f_pos_lock` mutex. + Ok(unsafe { ARef::from_raw(ptr.cast()) }) + } + + /// Creates a reference to a [`LocalFile`] from a valid pointer. + /// + /// # Safety + /// + /// * The caller must ensure that `ptr` points at a valid file and that the file's refcount is + /// positive for the duration of 'a. + /// * The caller must ensure that if there is an active call to `fdget_pos` that did not take + /// the `f_pos_lock` mutex, then that call is on the current thread. + #[inline] + pub unsafe fn from_ptr<'a>(ptr: *const bindings::file) -> &'a LocalFile { + // SAFETY: The caller guarantees that the pointer is not dangling and stays valid for the + // duration of 'a. The cast is okay because `File` is `repr(transparent)`. + // + // INVARIANT: The caller guarantees that there are no problematic `fdget_pos` calls. + unsafe { &*ptr.cast() } + } + + /// Assume that there are no active `fdget_pos` calls that prevent us from sharing this file. + /// + /// This makes it safe to transfer this file to other threads. No checks are performed, and + /// using it incorrectly may lead to a data race on the file position if the file is shared + /// with another thread. + /// + /// This method is intended to be used together with [`LocalFile::fget`] when the caller knows + /// statically that there are no `fdget_pos` calls on the current thread. For example, you + /// might use it when calling `fget` from an ioctl, since ioctls usually do not touch the file + /// position. + /// + /// # Safety + /// + /// There must not be any active `fdget_pos` calls on the current thread. + #[inline] + pub unsafe fn assume_no_fdget_pos(me: ARef) -> ARef { + // INVARIANT: There are no `fdget_pos` calls on the current thread, and by the type + // invariants, if there is a `fdget_pos` call on another thread, then it took the + // `f_pos_lock` mutex. + // + // SAFETY: `LocalFile` and `File` have the same layout. + unsafe { ARef::from_raw(ARef::into_raw(me).cast()) } + } + + /// Returns a raw pointer to the inner C struct. + #[inline] + pub fn as_ptr(&self) -> *mut bindings::file { + self.inner.get() + } + + /// Returns the flags associated with the file. + /// + /// The flags are a combination of the constants in [`flags`]. + #[inline] + pub fn flags(&self) -> u32 { + // This `read_volatile` is intended to correspond to a READ_ONCE call. + // + // SAFETY: The file is valid because the shared reference guarantees a nonzero refcount. + // + // FIXME(read_once): Replace with `read_once` when available on the Rust side. + unsafe { core::ptr::addr_of!((*self.as_ptr()).f_flags).read_volatile() } + } +} + +impl File { + /// Creates a reference to a [`File`] from a valid pointer. + /// + /// # Safety + /// + /// * The caller must ensure that `ptr` points at a valid file and that the file's refcount is + /// positive for the duration of 'a. + /// * The caller must ensure that if there are active `fdget_pos` calls on this file, then they + /// took the `f_pos_lock` mutex. + #[inline] + pub unsafe fn from_ptr<'a>(ptr: *const bindings::file) -> &'a File { + // SAFETY: The caller guarantees that the pointer is not dangling and stays valid for the + // duration of 'a. The cast is okay because `File` is `repr(transparent)`. + // + // INVARIANT: The caller guarantees that there are no problematic `fdget_pos` calls. + unsafe { &*ptr.cast() } + } +} + +// Make LocalFile methods available on File. +impl core::ops::Deref for File { + type Target = LocalFile; + #[inline] + fn deref(&self) -> &LocalFile { + // SAFETY: The caller provides a `&File`, and since it is a reference, it must point at a + // valid file for the desired duration. + // + // By the type invariants, there are no `fdget_pos` calls that did not take the + // `f_pos_lock` mutex. + unsafe { LocalFile::from_ptr(self as *const File as *const bindings::file) } + } +} + +// SAFETY: The type invariants guarantee that `LocalFile` is always ref-counted. This implementation +// makes `ARef` own a normal refcount. +unsafe impl AlwaysRefCounted for LocalFile { + #[inline] + fn inc_ref(&self) { + // SAFETY: The existence of a shared reference means that the refcount is nonzero. + unsafe { bindings::get_file(self.as_ptr()) }; + } + + #[inline] + unsafe fn dec_ref(obj: ptr::NonNull) { + // SAFETY: To call this method, the caller passes us ownership of a normal refcount, so we + // may drop it. The cast is okay since `File` has the same representation as `struct file`. + unsafe { bindings::fput(obj.cast().as_ptr()) } + } +} + +// SAFETY: The type invariants guarantee that `File` is always ref-counted. This implementation +// makes `ARef` own a normal refcount. +unsafe impl AlwaysRefCounted for File { + #[inline] + fn inc_ref(&self) { + // SAFETY: The existence of a shared reference means that the refcount is nonzero. + unsafe { bindings::get_file(self.as_ptr()) }; + } + + #[inline] + unsafe fn dec_ref(obj: ptr::NonNull) { + // SAFETY: To call this method, the caller passes us ownership of a normal refcount, so we + // may drop it. The cast is okay since `File` has the same representation as `struct file`. + unsafe { bindings::fput(obj.cast().as_ptr()) } + } +} + +/// Represents the `EBADF` error code. +/// +/// Used for methods that can only fail with `EBADF`. +#[derive(Copy, Clone, Eq, PartialEq)] +pub struct BadFdError; + +impl From for Error { + #[inline] + fn from(_: BadFdError) -> Error { + EBADF + } +} + +impl core::fmt::Debug for BadFdError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.pad("EBADF") + } +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index fbd91a48ff8b..dba3415c1cee 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -29,6 +29,7 @@ pub mod alloc; mod build_assert; pub mod error; +pub mod file; pub mod init; pub mod ioctl; #[cfg(CONFIG_KUNIT)] diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index 93734677cfe7..3ec2b12afbee 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -366,6 +366,14 @@ pub unsafe fn from_raw(ptr: NonNull) -> Self { _p: PhantomData, } } + + /// Convert this [`ARef`] into a raw pointer. + /// + /// The caller retains ownership of the refcount that this `ARef` used to own. + pub fn into_raw(me: Self) -> NonNull { + let me = core::mem::ManuallyDrop::new(me); + me.ptr + } } impl Clone for ARef { From patchwork Fri Jun 28 14:57:17 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13716293 Received: from mail-lf1-f74.google.com (mail-lf1-f74.google.com [209.85.167.74]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 0E8401C8FC9 for ; Fri, 28 Jun 2024 14:57:59 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.167.74 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719586681; cv=none; b=boj0lHj7Gnjj1u6JQRvOyiMdxnC23n/Da7cM5VX83UVTPBVKzscDMr7wzj1KREk3XKWLMo0pPr3I8NDDxfNain9GwgvUOO8VDbECnQqb7Lqh1VhAcMq7o+dlUPzpfS0oDqwHhIxytzwId1uBFYfa0h4ZcySywSVmJUOx9GC6LhU= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719586681; c=relaxed/simple; bh=ga/i0Ls35fCY8YV78KUSoH70UwUyGmCIIMOEY6Y8GEY=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=B6cnpi3/+kr4D89dejtDfe1xPQ+wSvUlK5AXw2yQvCRT8vF3tF4s8AVDUUqhSNu5qPG0+1FycNMWOwVQ464KsashFREo3FbbfP0qr8OXZ9uwhiChwUnU0yaH0pFyLqXt1G0aDD1/t0iAPeE8G5oongRhP+bhA3pq+9GwG8nip9E= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=RdSgsu42; arc=none smtp.client-ip=209.85.167.74 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="RdSgsu42" Received: by mail-lf1-f74.google.com with SMTP id 2adb3069b0e04-52cdb097139so831070e87.2 for ; Fri, 28 Jun 2024 07:57:59 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1719586678; x=1720191478; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=OKNhAShYl2ft6CJ5KlQf/Btl3Xr+pMe1lD7fxUEeZXA=; b=RdSgsu42slNB051+uT2W1sssKaT0dBua3wdhjo12dqRv2I8prYtVNS9yzRJLhpu5BM QPb08x0lSlBdoZCVj612UnXjWinHw0pLvsZj2TsXLLNR2+IMbH47c4GGvPX8iL2AWlr4 1r2BxJ49ODedaXOVKlL8ZXxYZpAcugxg3ZafhSo7COsMQKAwj6TtwgUey3JMvyiXjeCT 0ijHwL76dAWC1M108rSEgdkNTz4WCopzpOUlveTgkWirfyDMbRdsuoa0CUHQb08T3PiV NrXDRTAmBDkFk4GGRNlI8EwD5y4Kxj/yHuyGdrusR1pJuRnUNtdwXRrsqYVnaiFTou0k vZWQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1719586678; x=1720191478; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=OKNhAShYl2ft6CJ5KlQf/Btl3Xr+pMe1lD7fxUEeZXA=; b=SFcEpV88dBpqNup+5MyAa89FOG07R7fX97qYIMipw4r7lg4TI2X5EN9/kPFofkcwJ/ 8jpw9ctEFBngm7SfQ1Vg2HvQRNsJKzkKlkoGtT6ZsP6WnLbQ8F4EclJvBzs7QniwBpdm 5KYoLuQ0GqdG55nCyXARiIJ9Rj/DOUqptSHRtXzPNNQOhxHPviqUCS8d+iT1Z6X9pK+z yBTans2IpmvSdmOm/qC3XXb2gFXHguR0jbrT+3FWMBsSME04kFj7tEqd5rDOdpvGuZC6 miLejRwGPWuK+3ApoB6S/zaM3mpjFfwF41+M6aQ+esh9yP1+sLJpbwJs22sKSPxcMF/W 5UgQ== X-Forwarded-Encrypted: i=1; AJvYcCWlOfdPptF4s/qVjT8nccZP6teUvxsbpotyTrV/1Z+JeEl3lbd9HhMo/Z7CEOziRwHIfaoJSCSSckk8CWPyvrOmf7lVhFDJHhStDdV5cA== X-Gm-Message-State: AOJu0Yxa1EpFmoYJX7ZKn6s5cW7cQmOuo6ZQLTNgco7cHCssGNEyAU1Q 8WybknBZGbvSk7WAtjaqT+6UOePrgRpqKcJ0NM3lBZQBm82K99O/CeixMijbK15e6RYR0RhiKDf ZO9aK5MglQLemAA== X-Google-Smtp-Source: AGHT+IHJC6o+lUlIFO7TinLD84hZqcPdCGTwHSu/cNBNaG382CRlS8Qcn3syKx6kEDE1pwh70GYf8EQFI780xsc= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:ac2:58cb:0:b0:52c:97a8:63db with SMTP id 2adb3069b0e04-52ce183adecmr19220e87.7.1719586678195; Fri, 28 Jun 2024 07:57:58 -0700 (PDT) Date: Fri, 28 Jun 2024 14:57:17 +0000 In-Reply-To: <20240628-alice-file-v7-0-4d701f6335f3@google.com> Precedence: bulk X-Mailing-List: linux-fsdevel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240628-alice-file-v7-0-4d701f6335f3@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=7101; i=aliceryhl@google.com; h=from:subject:message-id; bh=RLxJnIFmmThp3fETtbijGb8ieDu222aEk+QMIYVNKMM=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmfs9kLchzWCZxKvmZirniEjMYg6x6IpyWbkVDt Gc2J6HlVjGJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZn7PZAAKCRAEWL7uWMY5 RrdbEACmlKuKhZnKfdtJeHmMsHCFUz/SVUYD6sxWsLjXbGQpriNwGnqQkUUT/IJxr0Csp4XBCLr VKcZ09jPKO73ykP5uPfbsOn7E2qu2anYkFBpcCDpsqMJXMOIE+b2ZKV3tGw4Upkw2lnur2qn08N iV2MAA8nGD7rna2bsf8DyM0re2MCU1Ux4jhT8Vz7blpwi60ezAUBJ4t7XIUXSesWjbrgbLzjdBq eNOV5op4NjcpKqenS5oEsbOUhq53e3y0l25ic1cWBHEOwDggXrlA4ZmPwwSTfitrsv1uGm6abO2 NqYzjx/lzcBTUFSMCdNaba7iddy0dqwWFbpTuPgPPKcTkHuvovpiwimGJWjPLM9Mu/PwABhmtwT R6qEsjgPK0Cui3794fLBnPNfltSrNY9AnM19rtYqvgd5/PSArwKR0zLB2D+mDoX1e0sTC9QW52/ wkS6IUiGXF44qkJ9n5kzY4hUjz0HQmLw7ldgVSKjhFnPniJTfOJs8Pq70RGB66kTbLCRgaOIxW2 x/RSaJqhOneYL3vWG/yJT0SF+ZZYw4bbaN8mmg6+e8A43/6CiR2Xgh31UCTcjrxS26s8CxEms0r zBpJqZcPItoUM15UGH+1/onjUR+W2Qj/dts/+8yS7rkFbpDz7mtfYlcBz0u5v0TAlTHQkcbyAOm DUHj8DuGOhYQGQg== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240628-alice-file-v7-4-4d701f6335f3@google.com> Subject: [PATCH v7 4/8] rust: cred: add Rust abstraction for `struct cred` From: Alice Ryhl To: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , " =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= " , Benno Lossin , Andreas Hindborg , Peter Zijlstra , Alexander Viro , Christian Brauner , Greg Kroah-Hartman , " =?utf-8?q?Arve_Hj?= =?utf-8?q?=C3=B8nnev=C3=A5g?= " , Todd Kjos , Martijn Coenen , Joel Fernandes , Carlos Llamas , Suren Baghdasaryan Cc: Dan Williams , Kees Cook , Matthew Wilcox , Thomas Gleixner , Daniel Xu , linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-fsdevel@vger.kernel.org, Alice Ryhl , Trevor Gross , Martin Rodriguez Reboredo From: Wedson Almeida Filho Add a wrapper around `struct cred` called `Credential`, and provide functionality to get the `Credential` associated with a `File`. Rust Binder must check the credentials of processes when they attempt to perform various operations, and these checks usually take a `&Credential` as parameter. The security_binder_set_context_mgr function would be one example. This patch is necessary to access these security_* methods from Rust. Signed-off-by: Wedson Almeida Filho Co-developed-by: Alice Ryhl Reviewed-by: Trevor Gross Reviewed-by: Benno Lossin Reviewed-by: Martin Rodriguez Reboredo Signed-off-by: Alice Ryhl --- rust/bindings/bindings_helper.h | 1 + rust/helpers.c | 13 ++++++++ rust/kernel/cred.rs | 74 +++++++++++++++++++++++++++++++++++++++++ rust/kernel/file.rs | 13 ++++++++ rust/kernel/lib.rs | 1 + 5 files changed, 102 insertions(+) diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index 541afef7ddc4..94091cb337e9 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -7,6 +7,7 @@ */ #include +#include #include #include #include diff --git a/rust/helpers.c b/rust/helpers.c index e68025b53342..9cf25e5324a4 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -172,6 +173,18 @@ struct file *rust_helper_get_file(struct file *f) } EXPORT_SYMBOL_GPL(rust_helper_get_file); +const struct cred *rust_helper_get_cred(const struct cred *cred) +{ + return get_cred(cred); +} +EXPORT_SYMBOL_GPL(rust_helper_get_cred); + +void rust_helper_put_cred(const struct cred *cred) +{ + put_cred(cred); +} +EXPORT_SYMBOL_GPL(rust_helper_put_cred); + /* * `bindgen` binds the C `size_t` type as the Rust `usize` type, so we can * use it in contexts where Rust expects a `usize` like slice (array) indices. diff --git a/rust/kernel/cred.rs b/rust/kernel/cred.rs new file mode 100644 index 000000000000..360d6fdbe5e7 --- /dev/null +++ b/rust/kernel/cred.rs @@ -0,0 +1,74 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Credentials management. +//! +//! C header: [`include/linux/cred.h`](srctree/include/linux/cred.h). +//! +//! Reference: + +use crate::{ + bindings, + types::{AlwaysRefCounted, Opaque}, +}; + +/// Wraps the kernel's `struct cred`. +/// +/// Credentials are used for various security checks in the kernel. +/// +/// Most fields of credentials are immutable. When things have their credentials changed, that +/// happens by replacing the credential instead of changing an existing credential. See the [kernel +/// documentation][ref] for more info on this. +/// +/// # Invariants +/// +/// Instances of this type are always ref-counted, that is, a call to `get_cred` ensures that the +/// allocation remains valid at least until the matching call to `put_cred`. +/// +/// [ref]: https://www.kernel.org/doc/html/latest/security/credentials.html +#[repr(transparent)] +pub struct Credential(Opaque); + +// SAFETY: +// - `Credential::dec_ref` can be called from any thread. +// - It is okay to send ownership of `Credential` across thread boundaries. +unsafe impl Send for Credential {} + +// SAFETY: It's OK to access `Credential` through shared references from other threads because +// we're either accessing properties that don't change or that are properly synchronised by C code. +unsafe impl Sync for Credential {} + +impl Credential { + /// Creates a reference to a [`Credential`] from a valid pointer. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is valid and remains valid for the lifetime of the + /// returned [`Credential`] reference. + pub unsafe fn from_ptr<'a>(ptr: *const bindings::cred) -> &'a Credential { + // SAFETY: The safety requirements guarantee the validity of the dereference, while the + // `Credential` type being transparent makes the cast ok. + unsafe { &*ptr.cast() } + } + + /// Returns the effective UID of the given credential. + pub fn euid(&self) -> bindings::kuid_t { + // SAFETY: By the type invariant, we know that `self.0` is valid. Furthermore, the `euid` + // field of a credential is never changed after initialization, so there is no potential + // for data races. + unsafe { (*self.0.get()).euid } + } +} + +// SAFETY: The type invariants guarantee that `Credential` is always ref-counted. +unsafe impl AlwaysRefCounted for Credential { + fn inc_ref(&self) { + // SAFETY: The existence of a shared reference means that the refcount is nonzero. + unsafe { bindings::get_cred(self.0.get()) }; + } + + unsafe fn dec_ref(obj: core::ptr::NonNull) { + // SAFETY: The safety requirements guarantee that the refcount is nonzero. The cast is okay + // because `Credential` has the same representation as `struct cred`. + unsafe { bindings::put_cred(obj.cast().as_ptr()) }; + } +} diff --git a/rust/kernel/file.rs b/rust/kernel/file.rs index 08551bf5c625..91113f844981 100644 --- a/rust/kernel/file.rs +++ b/rust/kernel/file.rs @@ -7,6 +7,7 @@ use crate::{ bindings, + cred::Credential, error::{code::*, Error, Result}, types::{ARef, AlwaysRefCounted, Opaque}, }; @@ -272,6 +273,18 @@ pub fn as_ptr(&self) -> *mut bindings::file { self.inner.get() } + /// Returns the credentials of the task that originally opened the file. + pub fn cred(&self) -> &Credential { + // SAFETY: It's okay to read the `f_cred` field without synchronization because `f_cred` is + // never changed after initialization of the file. + let ptr = unsafe { (*self.as_ptr()).f_cred }; + + // SAFETY: The signature of this function ensures that the caller will only access the + // returned credential while the file is still valid, and the C side ensures that the + // credential stays valid at least as long as the file. + unsafe { Credential::from_ptr(ptr) } + } + /// Returns the flags associated with the file. /// /// The flags are a combination of the constants in [`flags`]. diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index dba3415c1cee..ea7d07f0e83d 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -28,6 +28,7 @@ pub mod alloc; mod build_assert; +pub mod cred; pub mod error; pub mod file; pub mod init; From patchwork Fri Jun 28 14:57:18 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13716294 Received: from mail-yb1-f201.google.com (mail-yb1-f201.google.com [209.85.219.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id ED0771C8FD3 for ; Fri, 28 Jun 2024 14:58:01 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.219.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719586683; cv=none; b=N9XaI/qg7rGTJq+cAwwkYloXofctVjj61KFJSI1ENMm0FUcspB3KgrPAWDV3vl04ul3SipCD4LrFh1SA380NZk/jFeIMRFzCr4Wt4KlKSBUHh1aFfwv2y0EbIAjBF12LWgz6YZq0odjZB15fwKsQagsJ92UZ7CwD+50PA7COL80= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719586683; c=relaxed/simple; bh=SlqFSzKTXlCLM45RuGs1D6n4w52ysnBrvxDdEN5nqf0=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=ZKUXNsmoMpiebBDO0L+r4ZSk68ELOq70AUhBWNB3JHFjpN2Yur5N+Jm1s8JVQpauBaCNwi+Rw78hIA2x/mjVxHNXkOjZpC6EQ3shKLKbAAir8Ogr3dEun2b18Lr2QM02puCkRDnEz3ij42POrlrWLv+4SzafSkj7byaQ5L0C8IE= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=nsHVRy40; arc=none smtp.client-ip=209.85.219.201 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="nsHVRy40" Received: by mail-yb1-f201.google.com with SMTP id 3f1490d57ef6-dfdff0a9f26so1301459276.1 for ; Fri, 28 Jun 2024 07:58:01 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1719586681; x=1720191481; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=SINMfHecFZOdGH/mJM+WIc9fBNelCPSpkZcr54GiFHk=; b=nsHVRy40lyq02cVTaPt3mtBmJJbuc8W7IltZmrr5COZjhsIlpx95eNUitFjsB4d5S+ W1sbRMBWuz9d+lYVmU5A3IbaOFyc4VT0WJxxaE4ppP2FHPCXCi3h5RnIfsiKRznWCQKx +IFWZZgIQQG7ixDAXFO/x1JLxUAsWHxszk8+Y0CdeAvvRSNCzSwVHuRxTDLiSKVc/1g8 kRsJCWBoi4UXbeQlNsPTqxGz/qol9G+WXp4J9Xg1MrQ/A1fopQgCzMct2tUk/YIcpjKg 5pGVtRRrGfJTAd0b5oLn+EveIpwqKhvWoZz3fLoGwqfDS77XHN3S89p6EERUz0nonogJ RXXg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1719586681; x=1720191481; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=SINMfHecFZOdGH/mJM+WIc9fBNelCPSpkZcr54GiFHk=; b=Zp+DlTxkOySSb6kGujR/UqQ2Xpg9s5v70E6IOmZOLcF+Z98CHKmiy4qU1OO6reR+aD xlo+r+eeEhvIKZowvr/FPLu0BZJiTY8HkmtrcFtoCg/Kj868Q7m95vWZxQ6wYVcBrdBV FES0PbQ50WXIQQl++gEAbomo+tsIcUdNkU4VGTWD9aXGNj+YoqVsodSlM+Frnr6ffSy1 tikSOBrNbBBQGEGEm/Jtgpqw3lITI/VCwT0S2bJchB4dwX2V2AbPuzru6+zkFkFE86WI uaCAaBuDqsL7IbvkGmvEk5S7oTD7Po0bHijVIkqfwBbreseA/T50Bg352AphhfhVFiJj zHgQ== X-Forwarded-Encrypted: i=1; AJvYcCU9GDjT4CVIuZCWPH9o100imLg/EO7zGJEmAse0/FBHNoIiXmPOGxUIBDP7ithO0yjKlh/FN4zAe/beZ4c0FMV3A6d5gb0r5aHfFrEJ6w== X-Gm-Message-State: AOJu0Yzb2XTItRzolycvizxyN55U06JG2u/j15T+BTA5u3P6qFNKYpED isdnZPLVBgH5NY4uDOQgWmxseDNIhqGcClKnUEU3qXh3XvuOWCJ1K3aCafyS1pFTu6ivmasm+De rrPocSPPvCKaBtg== X-Google-Smtp-Source: AGHT+IG+viwqvXgSUt+FssvIzHj7/WggEatwMQjYCGulrBuqUMFYPHMjqAKPBzF/8zxtfjTW6dmdz6QTkqKrZGU= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:6902:c05:b0:e03:2f8e:9d81 with SMTP id 3f1490d57ef6-e032f8ea024mr18312276.0.1719586680992; Fri, 28 Jun 2024 07:58:00 -0700 (PDT) Date: Fri, 28 Jun 2024 14:57:18 +0000 In-Reply-To: <20240628-alice-file-v7-0-4d701f6335f3@google.com> Precedence: bulk X-Mailing-List: linux-fsdevel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240628-alice-file-v7-0-4d701f6335f3@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=6442; i=aliceryhl@google.com; h=from:subject:message-id; bh=SlqFSzKTXlCLM45RuGs1D6n4w52ysnBrvxDdEN5nqf0=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmfs9lqtDNb30DUajglMzWAG1mWxG06cE1X4H13 p9Lb0dhc/qJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZn7PZQAKCRAEWL7uWMY5 RnuZD/48E542L6X6hKdqsfcNV0bFqiV99n+9ZpxONN2UcoPlAQhtWTLvwM2Sc2w96ZQ7wvzoNzs ZABVdIaC8mpa1l+kdZznU7U35bafOW6ojwbgQXAs8i6+kuQXLshf8c7GOiXTUZp4f0hyNBCthSC zbhWLECDIFWR4pB5NGUUsbCiKEwWXRp5Jy+IOA2wZCJ2o7HOKkIx/gH3cGRgXbeponkQIOA7iYZ v/EAUKoJF4xd9hP7rZtK8mn94GW2/W1ULv9zfPqUjOCb7U1NMjM60g081lg2FaAoXqo5NTFDJtX N7MOJbUJtR5fTdb/qFLGfoE6rcClCYohr9YetTHb4hWdwm0LcMbjT/MkmU2sCB5BJPf7KTyDTJl g88BJVZciec9AWX+fIsr4d2K4dUvC5A2TGDFiPtP6QIRRqxAABvSQ2f4jOj1Vpl1wi+DC25vx20 YSl7h5zywXyestJth966QWwi1UyPLwnfxAt/9PVUvyFIgQTGp2bsq/7uwqZtIFQXNACOFWaMC1h ZTHLbkQ6zXWTAelAyIcoAA2tdKdk+CcORDIDtMBnfnetP/LxpXKUKPgrwI50rm/RQnxkCe3EeaJ oBUNBC87QTBMGSYXYkSYO0TnpVLEyY42D7jqPWaWAhWoWRN/Q0mmB8XabZ1yVkH3Ipj8LC8MkqH 2X+R0aj3fT50t0w== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240628-alice-file-v7-5-4d701f6335f3@google.com> Subject: [PATCH v7 5/8] rust: security: add abstraction for secctx From: Alice Ryhl To: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , " =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= " , Benno Lossin , Andreas Hindborg , Peter Zijlstra , Alexander Viro , Christian Brauner , Greg Kroah-Hartman , " =?utf-8?q?Arve_Hj?= =?utf-8?q?=C3=B8nnev=C3=A5g?= " , Todd Kjos , Martijn Coenen , Joel Fernandes , Carlos Llamas , Suren Baghdasaryan Cc: Dan Williams , Kees Cook , Matthew Wilcox , Thomas Gleixner , Daniel Xu , linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-fsdevel@vger.kernel.org, Alice Ryhl , Martin Rodriguez Reboredo , Trevor Gross Add an abstraction for viewing the string representation of a security context. This is needed by Rust Binder because it has a feature where a process can view the string representation of the security context for incoming transactions. The process can use that to authenticate incoming transactions, and since the feature is provided by the kernel, the process can trust that the security context is legitimate. Reviewed-by: Benno Lossin Reviewed-by: Martin Rodriguez Reboredo Reviewed-by: Trevor Gross Signed-off-by: Alice Ryhl --- rust/bindings/bindings_helper.h | 1 + rust/helpers.c | 21 ++++++++++++ rust/kernel/cred.rs | 8 +++++ rust/kernel/lib.rs | 1 + rust/kernel/security.rs | 72 +++++++++++++++++++++++++++++++++++++++++ 5 files changed, 103 insertions(+) diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index 94091cb337e9..cd2aaaaf9214 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include diff --git a/rust/helpers.c b/rust/helpers.c index 9cf25e5324a4..bd540a14c16a 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -30,6 +30,7 @@ #include #include #include +#include #include #include #include @@ -185,6 +186,26 @@ void rust_helper_put_cred(const struct cred *cred) } EXPORT_SYMBOL_GPL(rust_helper_put_cred); +#ifndef CONFIG_SECURITY +void rust_helper_security_cred_getsecid(const struct cred *c, u32 *secid) +{ + security_cred_getsecid(c, secid); +} +EXPORT_SYMBOL_GPL(rust_helper_security_cred_getsecid); + +int rust_helper_security_secid_to_secctx(u32 secid, char **secdata, u32 *seclen) +{ + return security_secid_to_secctx(secid, secdata, seclen); +} +EXPORT_SYMBOL_GPL(rust_helper_security_secid_to_secctx); + +void rust_helper_security_release_secctx(char *secdata, u32 seclen) +{ + security_release_secctx(secdata, seclen); +} +EXPORT_SYMBOL_GPL(rust_helper_security_release_secctx); +#endif + /* * `bindgen` binds the C `size_t` type as the Rust `usize` type, so we can * use it in contexts where Rust expects a `usize` like slice (array) indices. diff --git a/rust/kernel/cred.rs b/rust/kernel/cred.rs index 360d6fdbe5e7..fdd899040098 100644 --- a/rust/kernel/cred.rs +++ b/rust/kernel/cred.rs @@ -50,6 +50,14 @@ pub unsafe fn from_ptr<'a>(ptr: *const bindings::cred) -> &'a Credential { unsafe { &*ptr.cast() } } + /// Get the id for this security context. + pub fn get_secid(&self) -> u32 { + let mut secid = 0; + // SAFETY: The invariants of this type ensures that the pointer is valid. + unsafe { bindings::security_cred_getsecid(self.0.get(), &mut secid) }; + secid + } + /// Returns the effective UID of the given credential. pub fn euid(&self) -> bindings::kuid_t { // SAFETY: By the type invariant, we know that `self.0` is valid. Furthermore, the `euid` diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index ea7d07f0e83d..d331ab8a65a1 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -39,6 +39,7 @@ pub mod net; pub mod prelude; pub mod print; +pub mod security; mod static_assert; #[doc(hidden)] pub mod std_vendor; diff --git a/rust/kernel/security.rs b/rust/kernel/security.rs new file mode 100644 index 000000000000..ee2ef0385bae --- /dev/null +++ b/rust/kernel/security.rs @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Linux Security Modules (LSM). +//! +//! C header: [`include/linux/security.h`](srctree/include/linux/security.h). + +use crate::{ + bindings, + error::{to_result, Result}, +}; + +/// A security context string. +/// +/// # Invariants +/// +/// The `secdata` and `seclen` fields correspond to a valid security context as returned by a +/// successful call to `security_secid_to_secctx`, that has not yet been destroyed by calling +/// `security_release_secctx`. +pub struct SecurityCtx { + secdata: *mut core::ffi::c_char, + seclen: usize, +} + +impl SecurityCtx { + /// Get the security context given its id. + pub fn from_secid(secid: u32) -> Result { + let mut secdata = core::ptr::null_mut(); + let mut seclen = 0u32; + // SAFETY: Just a C FFI call. The pointers are valid for writes. + to_result(unsafe { bindings::security_secid_to_secctx(secid, &mut secdata, &mut seclen) })?; + + // INVARIANT: If the above call did not fail, then we have a valid security context. + Ok(Self { + secdata, + seclen: seclen as usize, + }) + } + + /// Returns whether the security context is empty. + pub fn is_empty(&self) -> bool { + self.seclen == 0 + } + + /// Returns the length of this security context. + pub fn len(&self) -> usize { + self.seclen + } + + /// Returns the bytes for this security context. + pub fn as_bytes(&self) -> &[u8] { + let ptr = self.secdata; + if ptr.is_null() { + debug_assert_eq!(self.seclen, 0); + // We can't pass a null pointer to `slice::from_raw_parts` even if the length is zero. + return &[]; + } + + // SAFETY: The call to `security_secid_to_secctx` guarantees that the pointer is valid for + // `seclen` bytes. Furthermore, if the length is zero, then we have ensured that the + // pointer is not null. + unsafe { core::slice::from_raw_parts(ptr.cast(), self.seclen) } + } +} + +impl Drop for SecurityCtx { + fn drop(&mut self) { + // SAFETY: By the invariant of `Self`, this frees a pointer that came from a successful + // call to `security_secid_to_secctx` and has not yet been destroyed by + // `security_release_secctx`. + unsafe { bindings::security_release_secctx(self.secdata, self.seclen as u32) }; + } +} From patchwork Fri Jun 28 14:57:19 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13716295 Received: from mail-yb1-f201.google.com (mail-yb1-f201.google.com [209.85.219.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id C21531C9EBE for ; Fri, 28 Jun 2024 14:58:04 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.219.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719586687; cv=none; b=Jlc93MHSgRcCjOK0LAX9M6MhImNcbvvDEFstn3A4u8IIx6Yd1NxCxplhJIBXfkQiR2FThyuiHlPFatF8QpQy8eEVJGSbjGgh3+qFpl57QSIWRTBkxvaadwfJPA/5d3vee2x+Psq4dHnUqXB2saIFA4PGvy7Y2H/F6Jf1KqWefcA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719586687; c=relaxed/simple; bh=RpuLWvo82s8TWdt4dzVRvAC2nWpD5vwuzxyl0uUxMAY=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=aIJbUROtqRlCBcOPIHhPqv6lBr8hFlEfoW5h9hXdMD11G1/S5NLwNSFvmkiDiiXoEgDsj8SNjq6c4H1H4/Rg4gMeaMD4XqFRa+ajYoAXtA4KaOGLFXhp6u7tq0w6DpxfMyXkOOCmcgyE3WyuWz5/1MfikByNMwSp9Cakgjpl0sg= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=EaZ0pUsP; arc=none smtp.client-ip=209.85.219.201 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="EaZ0pUsP" Received: by mail-yb1-f201.google.com with SMTP id 3f1490d57ef6-e02fff66a83so1285498276.0 for ; Fri, 28 Jun 2024 07:58:04 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1719586684; x=1720191484; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=3hYI08GA2i4xEDZ8Hp5EFD5V+jUYcMnVH1W8tB5qQts=; b=EaZ0pUsP/Xu67xbVz3OISrdXO0j8/qcDi5XJ2fX3i0qe/6OZInVudimheXwN2f6Pt+ Xka9pVGi+AZms9Fm9JvoSGK/1p7ci/JCLlg/bWa+S4AwZfs4nQWnLWygTDH/C+nkXBVm MkKpAPT3CmRhr4E3jCOGcUU4dxLg/jXlHq8r2culZDDCjn4zthWm7QT7BmZryh9YaDGw oIs7z+hLV27LQVNeVQAEkoIqJT6au8Oep4A5aX2ZibhqhXz/6n2WRhr1iIZHbrBYC7vS j796/Sm/dE2v2LWMdnzfIIIYYrOypHOq4Jk+dVtd1EzEN3ro81PMpybTOS0gSLdACliD HQVw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1719586684; x=1720191484; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=3hYI08GA2i4xEDZ8Hp5EFD5V+jUYcMnVH1W8tB5qQts=; b=mZh0sQTrbik7Oj9SuwKY+nQEaebMS8iQ7VJwvbfK8xcYJLlHzPdGeVc1x3L9/2Dezf CrtGUC6ZISWX5nMq9jFjwVsyT/r2b/6E6bFzWhRQ/SrIkwjxwBsEIV7LoD+Px1TBXdCJ tXDwxCuAOXyd+qus1SY7VY7ebmBo+BxLZ1gP4Kj5oBZewm5StJKCLz3e3BJ71ONUZhlT 7YPF+vxyuMKOeMl/zEQaQR3iXTDkXzLdfcLo4HEGLtp52SKOGVWDNd0v89yYc1EGmcEp /a2js9mDTRJcLZugfk4JJR4ICsueGDDQtDqqG06wBKUecU6BzKnaMEMcSx0PkpbJcWY5 YOvA== X-Forwarded-Encrypted: i=1; AJvYcCWE2jHl52tm2XC15J80QDvLwvzDf4pY1PGSmpaOt+/ixjVm/daSdsHXDuCxWVyLS+twiXEO0stYB5dMpggSNB1/Ks16fCUAcjz3cJMk2g== X-Gm-Message-State: AOJu0YxpD+cmxVHXMufUYMLGnDmuCub4QI2+pRp6Tsk3qOS7aD023GYw NoXvzbuwYwG+Q+EvypvUcCR8CMkJddltPMv1v40kHgY2stXmcSx/XrnUayWGvrZxCvEKkJpKIY0 Stti03dxyU8vz8w== X-Google-Smtp-Source: AGHT+IHKyYoOe4AxidxDSigY6PwMoldRCCF4iGFJ6lCu10o8NsAZ8cwGmDKRzVWg/f5P0ZNs4+HzbvdFsBTjaqo= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:6902:20c1:b0:de5:3003:4b64 with SMTP id 3f1490d57ef6-e0300ee84cbmr86203276.1.1719586683732; Fri, 28 Jun 2024 07:58:03 -0700 (PDT) Date: Fri, 28 Jun 2024 14:57:19 +0000 In-Reply-To: <20240628-alice-file-v7-0-4d701f6335f3@google.com> Precedence: bulk X-Mailing-List: linux-fsdevel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240628-alice-file-v7-0-4d701f6335f3@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=5369; i=aliceryhl@google.com; h=from:subject:message-id; bh=V6+J74sGMyRyUt7D0+Pd9EiFg1YsZr9BwywFGD0FbrA=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmfs9lBwKNl5aXUzjcdzlqpya4fAu6NujlHAcZx SkUZWqRZmiJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZn7PZQAKCRAEWL7uWMY5 RmcID/9J1eSntnwsntAYaxMpEigxFlfai6K0hjgitTT9homAa6oIKpntGZwSTG5zXZvEN/qd6ie Qc7XPfWKF/xCKwr9V+2ctjou7OAzOEetINuDE2GDQ14LdpFKKtYATRsL7UOhTIi0uC03lnYOTnm F5aKTmXlBQZ4u6aoajAzFDr+oDAYJEexg9XiE4S6JI7HMNF0dsu68/QpmvfjbO7tf1Zvyn/dpTr 8wnNRKNWv16QxCZfySpe0WeN3Edetbq1WMy7jAhW31AXO+hxgM/dMKh0kpvjw8AXu44S2EtGAUM faAbi2sjLZwrGT0O1jTsnnuWEAfgOCHD/eu6eyGx7OjZW9D67osPG5xGa9ce2NTsy+eUycTyWuB Mg7Wnyfkv8CPAu4csWFuhDqDuLEqOHHZnHfBpJguQPCwsd5rPnvgi2IWUGX8zM1cAJqEwakK8VF PnJMKbvlSIS/LaqhnMcHUfu+nRlqLDp9gRYcnTOwlaVWFfknEp8ROx2N3xtUiy3w2kOhqEyBTwk olR25WGneGYpt02mDPY3CtLNK14QSz8FsbDJ1VwATdmn8ZS6D0VdRKejNURgwajjdDmJ6Ac58Aw HRWZGCxp5SK+s4mEld60kvidIC5UUM9g06SlyIyBP4/H4NtWgoVgWY69OH4XRy5h2tFFIps4wGH sbp8eR2B4Zvokpw== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240628-alice-file-v7-6-4d701f6335f3@google.com> Subject: [PATCH v7 6/8] rust: file: add `FileDescriptorReservation` From: Alice Ryhl To: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , " =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= " , Benno Lossin , Andreas Hindborg , Peter Zijlstra , Alexander Viro , Christian Brauner , Greg Kroah-Hartman , " =?utf-8?q?Arve_Hj?= =?utf-8?q?=C3=B8nnev=C3=A5g?= " , Todd Kjos , Martijn Coenen , Joel Fernandes , Carlos Llamas , Suren Baghdasaryan Cc: Dan Williams , Kees Cook , Matthew Wilcox , Thomas Gleixner , Daniel Xu , linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-fsdevel@vger.kernel.org, Alice Ryhl , Martin Rodriguez Reboredo , Trevor Gross From: Wedson Almeida Filho Allow for the creation of a file descriptor in two steps: first, we reserve a slot for it, then we commit or drop the reservation. The first step may fail (e.g., the current process ran out of available slots), but commit and drop never fail (and are mutually exclusive). This is needed by Rust Binder when fds are sent from one process to another. It has to be a two-step process to properly handle the case where multiple fds are sent: The operation must fail or succeed atomically, which we achieve by first reserving the fds we need, and only installing the files once we have reserved enough fds to send the files. Fd reservations assume that the value of `current` does not change between the call to get_unused_fd_flags and the call to fd_install (or put_unused_fd). By not implementing the Send trait, this abstraction ensures that the `FileDescriptorReservation` cannot be moved into a different process. Signed-off-by: Wedson Almeida Filho Co-developed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Martin Rodriguez Reboredo Reviewed-by: Trevor Gross Signed-off-by: Alice Ryhl --- rust/kernel/file.rs | 75 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 74 insertions(+), 1 deletion(-) diff --git a/rust/kernel/file.rs b/rust/kernel/file.rs index 91113f844981..1b2645d36e36 100644 --- a/rust/kernel/file.rs +++ b/rust/kernel/file.rs @@ -9,7 +9,7 @@ bindings, cred::Credential, error::{code::*, Error, Result}, - types::{ARef, AlwaysRefCounted, Opaque}, + types::{ARef, AlwaysRefCounted, NotThreadSafe, Opaque}, }; use core::ptr; @@ -366,6 +366,79 @@ unsafe fn dec_ref(obj: ptr::NonNull) { } } +/// A file descriptor reservation. +/// +/// This allows the creation of a file descriptor in two steps: first, we reserve a slot for it, +/// then we commit or drop the reservation. The first step may fail (e.g., the current process ran +/// out of available slots), but commit and drop never fail (and are mutually exclusive). +/// +/// Dropping the reservation happens in the destructor of this type. +/// +/// # Invariants +/// +/// The fd stored in this struct must correspond to a reserved file descriptor of the current task. +pub struct FileDescriptorReservation { + fd: u32, + /// Prevent values of this type from being moved to a different task. + /// + /// The `fd_install` and `put_unused_fd` functions assume that the value of `current` is + /// unchanged since the call to `get_unused_fd_flags`. By adding this marker to this type, we + /// prevent it from being moved across task boundaries, which ensures that `current` does not + /// change while this value exists. + _not_send: NotThreadSafe, +} + +impl FileDescriptorReservation { + /// Creates a new file descriptor reservation. + pub fn get_unused_fd_flags(flags: u32) -> Result { + // SAFETY: FFI call, there are no safety requirements on `flags`. + let fd: i32 = unsafe { bindings::get_unused_fd_flags(flags) }; + if fd < 0 { + return Err(Error::from_errno(fd)); + } + Ok(Self { + fd: fd as u32, + _not_send: NotThreadSafe, + }) + } + + /// Returns the file descriptor number that was reserved. + pub fn reserved_fd(&self) -> u32 { + self.fd + } + + /// Commits the reservation. + /// + /// The previously reserved file descriptor is bound to `file`. This method consumes the + /// [`FileDescriptorReservation`], so it will not be usable after this call. + pub fn fd_install(self, file: ARef) { + // SAFETY: `self.fd` was previously returned by `get_unused_fd_flags`. We have not yet used + // the fd, so it is still valid, and `current` still refers to the same task, as this type + // cannot be moved across task boundaries. + // + // Furthermore, the file pointer is guaranteed to own a refcount by its type invariants, + // and we take ownership of that refcount by not running the destructor below. + // Additionally, the file is known to not have any non-shared `fdget_pos` calls, so even if + // this process starts using the file position, this will not result in a data race on the + // file position. + unsafe { bindings::fd_install(self.fd, file.as_ptr()) }; + + // `fd_install` consumes both the file descriptor and the file reference, so we cannot run + // the destructors. + core::mem::forget(self); + core::mem::forget(file); + } +} + +impl Drop for FileDescriptorReservation { + fn drop(&mut self) { + // SAFETY: By the type invariants of this type, `self.fd` was previously returned by + // `get_unused_fd_flags`. We have not yet used the fd, so it is still valid, and `current` + // still refers to the same task, as this type cannot be moved across task boundaries. + unsafe { bindings::put_unused_fd(self.fd) }; + } +} + /// Represents the `EBADF` error code. /// /// Used for methods that can only fail with `EBADF`. From patchwork Fri Jun 28 14:57:20 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13716296 Received: from mail-lj1-f202.google.com (mail-lj1-f202.google.com [209.85.208.202]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 9F1281C2335 for ; Fri, 28 Jun 2024 14:58:08 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.208.202 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719586690; cv=none; b=XtKAH41eI3+fPJEUOdE/6pGlQ33MjmRLYw8RjBCogzLnpAlzJZSm0ZnKM38QAkkuqvGJWq/B99Jj3u1eGzsBPSi8GVf10w/jUTGJu/pzdk6dwHgpHd4uROAfJHC0SZ41EkT7ZNgsAd10A9FkYp23zbyZrSYyO8KtRR4KMlGT6NI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719586690; c=relaxed/simple; bh=4tR1Tb2PZrUq+fv9lruTNhnntanNRjg+gXhQBblAAjk=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=UKJ+DS75Y6YgpFqV2vWRKzyFwNBljH0kluBXRK70EW3bmdEPbEaibyx0FQvGKTzLzGcwxxvI7BUu3ESkE0stSzYtllubsPqc8t3kfgyxVjc2QJpRvYMDDr41vTEtp1uPsoHjAw2FZ60RcxEN/a7QMg79vz9aWGrkPdK9uQ0Jcxc= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=GjCHXVPX; arc=none smtp.client-ip=209.85.208.202 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="GjCHXVPX" Received: by mail-lj1-f202.google.com with SMTP id 38308e7fff4ca-2ec62945d79so5658091fa.0 for ; Fri, 28 Jun 2024 07:58:08 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1719586687; x=1720191487; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=O5PJlOq7HcFoFVe0LT6WNAuvIuna6RAcnvVT9tdXfGM=; b=GjCHXVPXd9DDV2tcueBl42w+mjL1DbIy8QHKDfAtIsrH3rFlCBl17ga+rEwYguJZir MCDw9neZ0G65fQ/hnPhFRUm7bWtbatyGd6TJhV57T1/IDrCpWOVz/Zr0oqCluHdeuYwH giIYgTES3V8SD6PN1n1Nsx6LtYnL1AXxFYxPV36bZ3FoQehaOSgBCz8HJQ8+kp9onnWA A06M/bAmuHb1gYr+blutM+rM4PeROFElLsdsRpvGRcmtSV1DWfFB/+LzFUkr0Q7moSDq dFYtVbMJyoAurTfzB3Uii+FEPehe/dR1YqZUNvohR9gPF0YgT+CZ4XiKVBTV0E8vT1gn x40g== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1719586687; x=1720191487; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=O5PJlOq7HcFoFVe0LT6WNAuvIuna6RAcnvVT9tdXfGM=; b=wEi1JpkUBABovoUxKQt/l7oR1JZ32oD4FprXsxbFbMWEcamxvbkhk82sukwMiDYlQy oQ2Z61pA0Q+NX1D4UGj2JS5OrqTkHYYCE6Ul7SL3Afr5S5Vs+YL/kEd42W6H0kGKKZKw ZxI0AlKaHeGVJeOG4xivMCIUuzh+aP+ZEJNpbj0riLJoSk1JnGSy5xLGynmvXhc+JrTP 4wlQqDsHXGev/PcHT7LlAuVFycr7Hq13XMmXji62pRcix0yJZaPFXqbKIcUpT/DEHic+ azgFhkG+p0n+2vadpEIS2EokTSzcPETLJrj47dihyaK1mBeDGXG4kVSBbCq1iLJe+sQD Mmqg== X-Forwarded-Encrypted: i=1; AJvYcCUrwWSpqpZeN21sbuFFbpfK+kL8dFCFZ5Vg85uB8Y9SH6uFsm/G5O8kZoZR97Y/twaG9Md604f5LnapaSlpt9d9mcqVDo01fpSTGs8lvQ== X-Gm-Message-State: AOJu0YwYCXd3vQve+RH5J5y3/QdpqkZaZxtMTEJe3mtYxkH9QHpUwhK/ cCSRhxBSJAu3jWTAwfV3WJo30jZNGZ4+DCioA709SUuXMlKsjAfVWgzrhl3YZoixB83Ojn1mH+x bXQ2LQHryssikEQ== X-Google-Smtp-Source: AGHT+IEoXEOqi3W+oD8p+3vtCms7RuonarfRac6u23iUARnH5OtZxnXL9a/5qWMf2SNC/+l3FJrQ/hucYK4uOZY= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a2e:a4b3:0:b0:2ee:4c66:8df5 with SMTP id 38308e7fff4ca-2ee53cb0ff8mr22921fa.5.1719586686610; Fri, 28 Jun 2024 07:58:06 -0700 (PDT) Date: Fri, 28 Jun 2024 14:57:20 +0000 In-Reply-To: <20240628-alice-file-v7-0-4d701f6335f3@google.com> Precedence: bulk X-Mailing-List: linux-fsdevel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240628-alice-file-v7-0-4d701f6335f3@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=7798; i=aliceryhl@google.com; h=from:subject:message-id; bh=4tR1Tb2PZrUq+fv9lruTNhnntanNRjg+gXhQBblAAjk=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmfs9mgEoruPgE2YOjt1LFeFD+rh8aqrqNATeFO 7IhNosJ8qWJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZn7PZgAKCRAEWL7uWMY5 RmMUD/0ZhGTWkccBgZsIhFkclejW0gVD2qpGREocRrPaRln/w+IXeTumBjfoYVZQ0zsdQoD7CTP Rm1/2+rntB7gwXpi7zvBFekZIf0YBxoY0o5qBOeN2+HtexLJboaihK4CYIadeCQhuLCYqYYf+Qy g8qYkRwRXv+Uf3nr+21YoyIktO0/hBS220mPTFM+/p+S4FynAHcM5dQML0UnTH/Bv92JAtZwrMu 4FuBQySuxAqXArlChejFvc9yit3/gOCIV7sNDwvL/LKMOFMBBh7oqQK6lZfciqtk4dZXGrxa2oX oFhtVY0ybIupVgJrbveRP18g3Gp+0HoINY8YZ9Gg+M/hakt4sev3Pnu2UOozdt4wy7080WrpTn7 Eq/7Kx2m9JmTA7Wse0js5S/fKpYZHRwibIQAK99P4XLX5MyboIN9FxEjnW8LNOxYBZBMVbtqtRr l21rIZ5wzJiofRvhwJFuwY4MNm6YvPZp9skHDbK8QBe417Sh6U6BXzOxRoPCEWAZi1NKQSiz9vR WaDyIHtkK4SxPNUqaer6bPC3K90BVbgzzJZscXNM/r7TcUQWD8ndbHgO+mccOLyaQQXnibgAX42 tvCBstkU0T0tTRq3VONWjDDzHNmg/9RQhGBko1OP4ORveg0od0js+lwRzaSGZfN6xpHfXNEKiKW 6Uw/8/Dx+IxSPaQ== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240628-alice-file-v7-7-4d701f6335f3@google.com> Subject: [PATCH v7 7/8] rust: file: add `Kuid` wrapper From: Alice Ryhl To: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , " =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= " , Benno Lossin , Andreas Hindborg , Peter Zijlstra , Alexander Viro , Christian Brauner , Greg Kroah-Hartman , " =?utf-8?q?Arve_Hj?= =?utf-8?q?=C3=B8nnev=C3=A5g?= " , Todd Kjos , Martijn Coenen , Joel Fernandes , Carlos Llamas , Suren Baghdasaryan Cc: Dan Williams , Kees Cook , Matthew Wilcox , Thomas Gleixner , Daniel Xu , linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-fsdevel@vger.kernel.org, Alice Ryhl , Martin Rodriguez Reboredo , Trevor Gross Adds a wrapper around `kuid_t` called `Kuid`. This allows us to define various operations on kuids such as equality and current_euid. It also lets us provide conversions from kuid into userspace values. Rust Binder needs these operations because it needs to compare kuids for equality, and it needs to tell userspace about the pid and uid of incoming transactions. To read kuids from a `struct task_struct`, you must currently use various #defines that perform the appropriate field access under an RCU read lock. Currently, we do not have a Rust wrapper for rcu_read_lock, which means that for this patch, there are two ways forward: 1. Inline the methods into Rust code, and use __rcu_read_lock directly rather than the rcu_read_lock wrapper. This gives up lockdep for these usages of RCU. 2. Wrap the various #defines in helpers and call the helpers from Rust. This patch uses the second option. One possible disadvantage of the second option is the possible introduction of speculation gadgets, but as discussed in [1], the risk appears to be acceptable. Of course, once a wrapper for rcu_read_lock is available, it is preferable to use that over either of the two above approaches. Link: https://lore.kernel.org/all/202312080947.674CD2DC7@keescook/ [1] Reviewed-by: Benno Lossin Reviewed-by: Martin Rodriguez Reboredo Reviewed-by: Trevor Gross Signed-off-by: Alice Ryhl --- rust/bindings/bindings_helper.h | 1 + rust/helpers.c | 45 ++++++++++++++++++++++++++++ rust/kernel/cred.rs | 5 ++-- rust/kernel/task.rs | 66 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 115 insertions(+), 2 deletions(-) diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index cd2aaaaf9214..2a758930fc74 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include diff --git a/rust/helpers.c b/rust/helpers.c index bd540a14c16a..60b4e2adbcd9 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -143,6 +143,51 @@ void rust_helper_put_task_struct(struct task_struct *t) } EXPORT_SYMBOL_GPL(rust_helper_put_task_struct); +kuid_t rust_helper_task_uid(struct task_struct *task) +{ + return task_uid(task); +} +EXPORT_SYMBOL_GPL(rust_helper_task_uid); + +kuid_t rust_helper_task_euid(struct task_struct *task) +{ + return task_euid(task); +} +EXPORT_SYMBOL_GPL(rust_helper_task_euid); + +#ifndef CONFIG_USER_NS +uid_t rust_helper_from_kuid(struct user_namespace *to, kuid_t uid) +{ + return from_kuid(to, uid); +} +EXPORT_SYMBOL_GPL(rust_helper_from_kuid); +#endif /* CONFIG_USER_NS */ + +bool rust_helper_uid_eq(kuid_t left, kuid_t right) +{ + return uid_eq(left, right); +} +EXPORT_SYMBOL_GPL(rust_helper_uid_eq); + +kuid_t rust_helper_current_euid(void) +{ + return current_euid(); +} +EXPORT_SYMBOL_GPL(rust_helper_current_euid); + +struct user_namespace *rust_helper_current_user_ns(void) +{ + return current_user_ns(); +} +EXPORT_SYMBOL_GPL(rust_helper_current_user_ns); + +pid_t rust_helper_task_tgid_nr_ns(struct task_struct *tsk, + struct pid_namespace *ns) +{ + return task_tgid_nr_ns(tsk, ns); +} +EXPORT_SYMBOL_GPL(rust_helper_task_tgid_nr_ns); + struct kunit *rust_helper_kunit_get_current_test(void) { return kunit_get_current_test(); diff --git a/rust/kernel/cred.rs b/rust/kernel/cred.rs index fdd899040098..961e94b6a657 100644 --- a/rust/kernel/cred.rs +++ b/rust/kernel/cred.rs @@ -8,6 +8,7 @@ use crate::{ bindings, + task::Kuid, types::{AlwaysRefCounted, Opaque}, }; @@ -59,11 +60,11 @@ pub fn get_secid(&self) -> u32 { } /// Returns the effective UID of the given credential. - pub fn euid(&self) -> bindings::kuid_t { + pub fn euid(&self) -> Kuid { // SAFETY: By the type invariant, we know that `self.0` is valid. Furthermore, the `euid` // field of a credential is never changed after initialization, so there is no potential // for data races. - unsafe { (*self.0.get()).euid } + Kuid::from_raw(unsafe { (*self.0.get()).euid }) } } diff --git a/rust/kernel/task.rs b/rust/kernel/task.rs index 367b4bbddd9f..1a36a9f19368 100644 --- a/rust/kernel/task.rs +++ b/rust/kernel/task.rs @@ -9,6 +9,7 @@ types::{NotThreadSafe, Opaque}, }; use core::{ + cmp::{Eq, PartialEq}, ffi::{c_int, c_long, c_uint}, ops::Deref, ptr, @@ -96,6 +97,12 @@ unsafe impl Sync for Task {} /// The type of process identifiers (PIDs). type Pid = bindings::pid_t; +/// The type of user identifiers (UIDs). +#[derive(Copy, Clone)] +pub struct Kuid { + kuid: bindings::kuid_t, +} + impl Task { /// Returns a raw pointer to the current task. /// @@ -157,12 +164,31 @@ pub fn pid(&self) -> Pid { unsafe { *ptr::addr_of!((*self.0.get()).pid) } } + /// Returns the UID of the given task. + pub fn uid(&self) -> Kuid { + // SAFETY: By the type invariant, we know that `self.0` is valid. + Kuid::from_raw(unsafe { bindings::task_uid(self.0.get()) }) + } + + /// Returns the effective UID of the given task. + pub fn euid(&self) -> Kuid { + // SAFETY: By the type invariant, we know that `self.0` is valid. + Kuid::from_raw(unsafe { bindings::task_euid(self.0.get()) }) + } + /// Determines whether the given task has pending signals. pub fn signal_pending(&self) -> bool { // SAFETY: By the type invariant, we know that `self.0` is valid. unsafe { bindings::signal_pending(self.0.get()) != 0 } } + /// Returns the given task's pid in the current pid namespace. + pub fn pid_in_current_ns(&self) -> Pid { + // SAFETY: We know that `self.0.get()` is valid by the type invariant, and passing a null + // pointer as the namespace is correct for using the current namespace. + unsafe { bindings::task_tgid_nr_ns(self.0.get(), ptr::null_mut()) } + } + /// Wakes up the task. pub fn wake_up(&self) { // SAFETY: By the type invariant, we know that `self.0.get()` is non-null and valid. @@ -184,3 +210,43 @@ unsafe fn dec_ref(obj: ptr::NonNull) { unsafe { bindings::put_task_struct(obj.cast().as_ptr()) } } } + +impl Kuid { + /// Get the current euid. + #[inline] + pub fn current_euid() -> Kuid { + // SAFETY: Just an FFI call. + Self::from_raw(unsafe { bindings::current_euid() }) + } + + /// Create a `Kuid` given the raw C type. + #[inline] + pub fn from_raw(kuid: bindings::kuid_t) -> Self { + Self { kuid } + } + + /// Turn this kuid into the raw C type. + #[inline] + pub fn into_raw(self) -> bindings::kuid_t { + self.kuid + } + + /// Converts this kernel UID into a userspace UID. + /// + /// Uses the namespace of the current task. + #[inline] + pub fn into_uid_in_current_ns(self) -> bindings::uid_t { + // SAFETY: Just an FFI call. + unsafe { bindings::from_kuid(bindings::current_user_ns(), self.kuid) } + } +} + +impl PartialEq for Kuid { + #[inline] + fn eq(&self, other: &Kuid) -> bool { + // SAFETY: Just an FFI call. + unsafe { bindings::uid_eq(self.kuid, other.kuid) } + } +} + +impl Eq for Kuid {} From patchwork Fri Jun 28 14:57:21 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13716297 Received: from mail-lj1-f202.google.com (mail-lj1-f202.google.com [209.85.208.202]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E44371CCCA6 for ; Fri, 28 Jun 2024 14:58:11 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.208.202 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719586693; cv=none; b=rVkFfGexB7ZyNqUyDToeUd9uBNWMWRbkvV+3IItuEW7cFqpN1H5SneOcaobOb9K9Tsci13hPhgzX0jzuGqkohZyPY1DE0b51oIeh43guoFjQDID4Aatx63IJyEAguXHP8ehX5mjgOP4irs5DHRVbZeuwHIPWYZ1bBmOTnzjiBH8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719586693; c=relaxed/simple; bh=oKaGHDnrqupViuRXMtll5RU9jzG83pkROJGpqrjmWrM=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=uPOSNVQW0qpUa1XMsOwMFqbudDUG13rMpprPpFkl2YxM3SoU33s11Gt3tXVY75jCN7RSIoz2KzPp9n9maFjJXp0GWeW1Yh/hUwxP57ImHFMvfq3Fxvz/+pxg0IaAkaVNPkKezoZb1YHPrB7sjCV/JP1xFtn7brZ/lg/4DrT+Phk= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=qvcPvfRS; arc=none smtp.client-ip=209.85.208.202 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="qvcPvfRS" Received: by mail-lj1-f202.google.com with SMTP id 38308e7fff4ca-2ee4ab40417so11709781fa.0 for ; Fri, 28 Jun 2024 07:58:11 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1719586690; x=1720191490; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=Wv4X5HCz0mHAJhrblLEwF6K15PPfNYph9fKqj4QrWqA=; b=qvcPvfRSMZHMGaVMxxkj69X+yuoqeJWAI+mGkTPa3zjMYnJRvUQiy9Yx0x2i/ZfUp7 fmKpQKOLTFkBvDlJhcYqPWyHpaSEvA7vVOb1y31t9m9eghhvzz0neL2jBKIxG1vBouMS iTLZndCRzUUSs5cJtXqaE1myx/Qx+J4sWvcJ+XPiz08TIi7H84PMT1hYy7Y9sv7pPNTE /UYMSdx0gRz7hfydHi8E6UiReNWcIC3sf+0XnG6WCxCdqLYJ9YQX1/E8BI0z+eAEic5X OnBd2lcVETf+M03naRgbHods9uuCUJomUwmhlc33z8p2RUFE7ifEdKXxiJgefQs1rJ7j 6wdA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1719586690; x=1720191490; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=Wv4X5HCz0mHAJhrblLEwF6K15PPfNYph9fKqj4QrWqA=; b=F58ZezXvtGIBdSHJMhx3OstKADCv724ijREPEL//e4/6Lr9jQLc8w6D8qOBaDQ2YgQ OPSY8g4kztPGloPWlY/+jmYta+4+1EgXqdV7VYoyb8RWoqT3i/QeVR3me3asysLNZWOE 45WCQGwSl03EARCCKAu2edVlj2aondO6WvzD2cMaGERWN4Gs9CBBTuztj7aFtidLDTcH 2mA4HFMRexIQkIXvQHADA49F6J2ZmvFihtMfRaKxGj3dUIfNsetJRNgBz1SRi0ocwhIV /kAl+ulXPMd6v78ZK8QAVfp/SN0X1h2lmoZ/buz8dQzoxQZu7dieRHkfQ13qC0CuWyLX p81A== X-Forwarded-Encrypted: i=1; AJvYcCUWWAwIxNCKC4zicg/0yQ+zcf0SP02BpI9UyDj5ikbG7vulastW2CB63UzH7cLxszk3r7e3eTKaFtFflfyl6dbv3a1VSuLlv8hWraDctw== X-Gm-Message-State: AOJu0YzTw2IyG45WhvUXlJfB3/tfzRExeSWg1sdyDunItOpXw9f9UwtN Jp1eX+tdsQ3s2dLwZjVOl9KC/EKHyYXBYVC3lAAKXxBy0L2SRb2DDjBvfMG3NoajzDpOYp35jUd jf/1DN9DGDSBoeQ== X-Google-Smtp-Source: AGHT+IHrh51dp+IDMj1N+uGSI5q7qASDiH0RqVC1DTBBvwhd4ZRgb9b4M4bqJYgnfjp9iyg4L7GoysM5bKSqcvc= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:6512:3b98:b0:52c:c4c0:bb99 with SMTP id 2adb3069b0e04-52e7b92f044mr2478e87.3.1719586689755; Fri, 28 Jun 2024 07:58:09 -0700 (PDT) Date: Fri, 28 Jun 2024 14:57:21 +0000 In-Reply-To: <20240628-alice-file-v7-0-4d701f6335f3@google.com> Precedence: bulk X-Mailing-List: linux-fsdevel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240628-alice-file-v7-0-4d701f6335f3@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=7243; i=aliceryhl@google.com; h=from:subject:message-id; bh=oKaGHDnrqupViuRXMtll5RU9jzG83pkROJGpqrjmWrM=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmfs9nSDHlXxRQ4/wfPEvlXip4lzgzsEBJhWdPu I457Q+oqseJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZn7PZwAKCRAEWL7uWMY5 Rs82EAC6UrQk8yKkBP4loWFJW8n8xcTs0iouXEAwED5SSNuYAZPD0P/xfHYvog8Gw+HFYS/8Ssy PKwUZSWLkGTJnkAkrZ7O3VgE/OAJiTBQaq1fMvPuIVv6vg+gV5p1uVI/RqTPcisr+FtLnV9G2hJ yin7IJ6dMMzeqFJ56N9fLYCKimvZx1mLyeIhXcc3Gd+sXzWJTOFMWYupGqSt110uG21aMgH7Hn8 6iEw+VN8un2ZIjo74zP7P67/2oXQzVd1h+6E2HgSouiwkX6o/M2EKxrjdgwdo/RQdEaXDSHiAtn 5VleuVyu2hC/wWVdtMY93gO7u+SY05l6vCstDmYfNZ5IV4wVgcdTz+F0xJv7lv6NCrdBLed3r5i hexPfASokTaNw8SeC0Q7SPoOAOr+2Qb6q9KC9M6JSSpn7HzsMLjFtkt/WVk4kzdqmvX8FkJq3z3 BQWrJ/+tohrkTRpKfsdQzLw9q/JGDtmsFuPPblrDZ9bH9oiUQoRLQviiIEKWfQO5lz8J4iPx9fs nZKl/RDpCKd2TwPD6+DwKL0FaXol07Yj4vydFGgJRreW84V2a/TKitOR4cUMBtLKV9pHmm7Tj8y x5+aAJgQleouvmKhsPMoFz39T8/Wqrow6PyXJGAz7WY022CT70KrpZIzk66XjAhtDPkc3K9DYrh BxqaLe1CO6m3Xlw== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240628-alice-file-v7-8-4d701f6335f3@google.com> Subject: [PATCH v7 8/8] rust: file: add abstraction for `poll_table` From: Alice Ryhl To: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , " =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= " , Benno Lossin , Andreas Hindborg , Peter Zijlstra , Alexander Viro , Christian Brauner , Greg Kroah-Hartman , " =?utf-8?q?Arve_Hj?= =?utf-8?q?=C3=B8nnev=C3=A5g?= " , Todd Kjos , Martijn Coenen , Joel Fernandes , Carlos Llamas , Suren Baghdasaryan Cc: Dan Williams , Kees Cook , Matthew Wilcox , Thomas Gleixner , Daniel Xu , linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-fsdevel@vger.kernel.org, Alice Ryhl , Martin Rodriguez Reboredo , Trevor Gross The existing `CondVar` abstraction is a wrapper around `wait_queue_head`, but it does not support all use-cases of the C `wait_queue_head` type. To be specific, a `CondVar` cannot be registered with a `struct poll_table`. This limitation has the advantage that you do not need to call `synchronize_rcu` when destroying a `CondVar`. However, we need the ability to register a `poll_table` with a `wait_queue_head` in Rust Binder. To enable this, introduce a type called `PollCondVar`, which is like `CondVar` except that you can register a `poll_table`. We also introduce `PollTable`, which is a safe wrapper around `poll_table` that is intended to be used with `PollCondVar`. The destructor of `PollCondVar` unconditionally calls `synchronize_rcu` to ensure that the removal of epoll waiters has fully completed before the `wait_queue_head` is destroyed. That said, `synchronize_rcu` is rather expensive and is not needed in all cases: If we have never registered a `poll_table` with the `wait_queue_head`, then we don't need to call `synchronize_rcu`. (And this is a common case in Binder - not all processes use Binder with epoll.) The current implementation does not account for this, but if we find that it is necessary to improve this, a future patch could store a boolean next to the `wait_queue_head` to keep track of whether a `poll_table` has ever been registered. Reviewed-by: Benno Lossin Reviewed-by: Martin Rodriguez Reboredo Reviewed-by: Trevor Gross Signed-off-by: Alice Ryhl --- rust/bindings/bindings_helper.h | 1 + rust/kernel/sync.rs | 1 + rust/kernel/sync/poll.rs | 119 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 121 insertions(+) diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index 2a758930fc74..b423d5cb6826 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include diff --git a/rust/kernel/sync.rs b/rust/kernel/sync.rs index 0ab20975a3b5..bae4a5179c72 100644 --- a/rust/kernel/sync.rs +++ b/rust/kernel/sync.rs @@ -11,6 +11,7 @@ mod condvar; pub mod lock; mod locked_by; +pub mod poll; pub use arc::{Arc, ArcBorrow, UniqueArc}; pub use condvar::{new_condvar, CondVar, CondVarTimeoutResult}; diff --git a/rust/kernel/sync/poll.rs b/rust/kernel/sync/poll.rs new file mode 100644 index 000000000000..586b660df423 --- /dev/null +++ b/rust/kernel/sync/poll.rs @@ -0,0 +1,119 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Utilities for working with `struct poll_table`. + +use crate::{ + bindings, + file::File, + prelude::*, + sync::{CondVar, LockClassKey}, + types::Opaque, +}; +use core::ops::Deref; + +/// Creates a [`PollCondVar`] initialiser with the given name and a newly-created lock class. +#[macro_export] +macro_rules! new_poll_condvar { + ($($name:literal)?) => { + $crate::sync::poll::PollCondVar::new( + $crate::optional_name!($($name)?), $crate::static_lock_class!() + ) + }; +} + +/// Wraps the kernel's `struct poll_table`. +/// +/// # Invariants +/// +/// This struct contains a valid `struct poll_table`. +/// +/// For a `struct poll_table` to be valid, its `_qproc` function must follow the safety +/// requirements of `_qproc` functions: +/// +/// * The `_qproc` function is given permission to enqueue a waiter to the provided `poll_table` +/// during the call. Once the waiter is removed and an rcu grace period has passed, it must no +/// longer access the `wait_queue_head`. +#[repr(transparent)] +pub struct PollTable(Opaque); + +impl PollTable { + /// Creates a reference to a [`PollTable`] from a valid pointer. + /// + /// # Safety + /// + /// The caller must ensure that for the duration of 'a, the pointer will point at a valid poll + /// table (as defined in the type invariants). + /// + /// The caller must also ensure that the `poll_table` is only accessed via the returned + /// reference for the duration of 'a. + pub unsafe fn from_ptr<'a>(ptr: *mut bindings::poll_table) -> &'a mut PollTable { + // SAFETY: The safety requirements guarantee the validity of the dereference, while the + // `PollTable` type being transparent makes the cast ok. + unsafe { &mut *ptr.cast() } + } + + fn get_qproc(&self) -> bindings::poll_queue_proc { + let ptr = self.0.get(); + // SAFETY: The `ptr` is valid because it originates from a reference, and the `_qproc` + // field is not modified concurrently with this call since we have an immutable reference. + unsafe { (*ptr)._qproc } + } + + /// Register this [`PollTable`] with the provided [`PollCondVar`], so that it can be notified + /// using the condition variable. + pub fn register_wait(&mut self, file: &File, cv: &PollCondVar) { + if let Some(qproc) = self.get_qproc() { + // SAFETY: The pointers to `file` and `self` need to be valid for the duration of this + // call to `qproc`, which they are because they are references. + // + // The `cv.wait_queue_head` pointer must be valid until an rcu grace period after the + // waiter is removed. The `PollCondVar` is pinned, so before `cv.wait_queue_head` can + // be destroyed, the destructor must run. That destructor first removes all waiters, + // and then waits for an rcu grace period. Therefore, `cv.wait_queue_head` is valid for + // long enough. + unsafe { qproc(file.as_ptr() as _, cv.wait_queue_head.get(), self.0.get()) }; + } + } +} + +/// A wrapper around [`CondVar`] that makes it usable with [`PollTable`]. +/// +/// [`CondVar`]: crate::sync::CondVar +#[pin_data(PinnedDrop)] +pub struct PollCondVar { + #[pin] + inner: CondVar, +} + +impl PollCondVar { + /// Constructs a new condvar initialiser. + pub fn new(name: &'static CStr, key: &'static LockClassKey) -> impl PinInit { + pin_init!(Self { + inner <- CondVar::new(name, key), + }) + } +} + +// Make the `CondVar` methods callable on `PollCondVar`. +impl Deref for PollCondVar { + type Target = CondVar; + + fn deref(&self) -> &CondVar { + &self.inner + } +} + +#[pinned_drop] +impl PinnedDrop for PollCondVar { + fn drop(self: Pin<&mut Self>) { + // Clear anything registered using `register_wait`. + // + // SAFETY: The pointer points at a valid `wait_queue_head`. + unsafe { bindings::__wake_up_pollfree(self.inner.wait_queue_head.get()) }; + + // Wait for epoll items to be properly removed. + // + // SAFETY: Just an FFI call. + unsafe { bindings::synchronize_rcu() }; + } +}