From nobody Mon Feb 9 02:42:38 2026 Received: from mail-pg1-f170.google.com (mail-pg1-f170.google.com [209.85.215.170]) (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 399701624E9; Sun, 4 May 2025 04:24:48 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.215.170 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746332691; cv=none; b=aIMeYHQWyLhuAm0SKe9jQeX7y06S3Skx8Ig/iTFXx99Fz3vCkO3kJe5KZdhba16Uk2GPApHa6cU12qgN5I/xkIf2ijtP/Sm3QNf3l0GRMvT+n9WTxxxbWcRIofJY+bf688eobQ9emFrqvxYA93YnqCVXm75f+Q4F4sAjFlDaUwo= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746332691; c=relaxed/simple; bh=6SiFMa5mM++NGOjLEokCQPQrGCkyUORvFikHbWGnUqE=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version:Content-Type; b=unE3rsXsHHrAGkGm73zPBMDQ4APWruDWzfiZoX1g8WgyK61vvFOLeeymMwjmE/5I2/w/lM+wx7xttt1llA5tBdyT2gewKNoTO+XZaGcGDJOOA1mhq4kO1PCIn8qOP4dIFLFrY7IV+ftLSxmLXdijGj2FrWnQw2xp1y1lobXWDLA= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=X+fGeUqC; arc=none smtp.client-ip=209.85.215.170 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="X+fGeUqC" Received: by mail-pg1-f170.google.com with SMTP id 41be03b00d2f7-b1f7357b5b6so2215180a12.0; Sat, 03 May 2025 21:24:48 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1746332688; x=1746937488; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=LE30wOms6oGnNGtfcrQE9Pg8OoY+5+nNc+vYh1EjOjg=; b=X+fGeUqC5DYlD3OBpUYwtz76FIw67v+/B+yx3+Qo7k9nsxU4t1fthd7s3kwXGFPM4F SyOrheVOfKzUDxTtyo3c/Y/yfj48vt32hXJuyQ+O7jQnUzDpD+AemBJkjZC0XcoWjNKy An4+x/C/hcLEcbCSEmEKJjTbVw8REXW0NM8trg7Wb8zlCYQUoh56Rd/1x+TyMfUn7iM0 g/OFf8mHkFrq4iZS8CHKZ2Kw+2WN/MBm2SG95RZ5b+z4B0sUp+Jab5a6G/njT8OuYZj8 EHOxVS4u7QnH4LyuKxagqlZ583Q9MYPk6nSBb+cFTjilNtjLksIdJ/E2oSso/YifHqx9 yOzA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1746332688; x=1746937488; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=LE30wOms6oGnNGtfcrQE9Pg8OoY+5+nNc+vYh1EjOjg=; b=bUvrsR95UzWWWa9RC1qp1tGu6aS533IvRfDleqZv/eMJdGv31+EKE1ARquTd6THzyk hzsEH+svjduDgxOKZHNzslaWgWoEm0mJuhGcyrfSlOVpzUS83n/rt1GxVLNLEmffuTNV WhXM5NbvxsF2AhtGfl+j+R64XW7xBiR2mAoCdlHYxz17aa96FKPWnFOaKT9wU9OE0DbI AQ1zmYRbrcRaDBC7o6dPPTlNmEvKW7Z29eRqm7xUMWOR9OC8wrll7Dr4F54WqXrA75sl gDA4S7zQHTTnrMPPaltgjIpMYqLdIjh4oGIPXr2t5ngQFMHTyQYA5v4olkIaZM5uGZGH vCiw== X-Forwarded-Encrypted: i=1; AJvYcCUG7rNQCvJCCtABe2crj7/4FzY7vtQcJ+PhkCMoj5aBGVIgRkln6vsWAytpbYMUmne6GVOsAOP7046XNbs=@vger.kernel.org X-Gm-Message-State: AOJu0YxqKL8cInCSl7O+n1x3i19U9OiLRUoCzut/rY8JBLma6QRpj85R EpryXqcL8TAbn2foygKDVZSEUKgWWnlQUnWDrlpeTxg+uxoK6qfkoBbiPFp0 X-Gm-Gg: ASbGncvyTGP7c3iBDaEBXjGHoyL6p0kWdQv+ocV01DLEzumKgMMOlkOBXtTXK5+OITb 0qTQyY5jsFbCuMZ5CqryIfEaTZH6WfgRRYYu/JVegm3h2ccj2qLRDkOyEqBTqEn+/Sgu8C6mtZX t2FCfAPtoxZHI/mbHZz5yk6UYBLgI4gMUKltV+dQAkQax1iJKQ6AYd5EEEUZJ10Rq5RgjCRY+oE 6ikYgs85VzX3TaHp2sst2LlEY/HxmAC2E+mMdrT1s0m5FVJD2hAA4cYuoahPO3ju5LSEpq711Pa PYkLqkesLaRwjGRsgpF+xZzbfhvj9TSPbo1fd0fbNaMyLc03Eu28fz6LX4eIdihoz2syXgIcJXn HJtGrh/6QwBqYUezKfA== X-Google-Smtp-Source: AGHT+IGJ9ve5oG93kK5P5S0kJNEmhpuPHr+yhxtbuXqK2qObmN8tkjl8E8rHn9hQ6Hjtp7TaFvrh3A== X-Received: by 2002:a17:902:ea01:b0:223:42ca:10ef with SMTP id d9443c01a7336-22e18c4f091mr63817225ad.43.1746332688084; Sat, 03 May 2025 21:24:48 -0700 (PDT) Received: from mew.. (p4138183-ipxg22701hodogaya.kanagawa.ocn.ne.jp. [153.129.206.183]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-22e1521fbc8sm31482185ad.142.2025.05.03.21.24.44 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sat, 03 May 2025 21:24:47 -0700 (PDT) From: FUJITA Tomonori To: rust-for-linux@vger.kernel.org Cc: Andreas Hindborg , boqun.feng@gmail.com, frederic@kernel.org, lyude@redhat.com, tglx@linutronix.de, anna-maria@linutronix.de, jstultz@google.com, sboyd@kernel.org, ojeda@kernel.org, alex.gaynor@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, aliceryhl@google.com, tmgross@umich.edu, dakr@kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH v2 1/3] rust: time: Replace ClockId enum with ClockSource trait Date: Sun, 4 May 2025 13:24:33 +0900 Message-ID: <20250504042436.237756-2-fujita.tomonori@gmail.com> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20250504042436.237756-1-fujita.tomonori@gmail.com> References: <20250504042436.237756-1-fujita.tomonori@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Replace the ClockId enum with a trait-based abstraction called ClockSource. This change enables expressing clock sources as types and leveraging the Rust type system to enforce clock correctness at compile time. This also sets the stage for future generic abstractions over Instant types such as Instant. Reviewed-by: Andreas Hindborg Signed-off-by: FUJITA Tomonori --- rust/kernel/time.rs | 147 ++++++++++++++++++++---------------- rust/kernel/time/hrtimer.rs | 6 +- 2 files changed, 84 insertions(+), 69 deletions(-) diff --git a/rust/kernel/time.rs b/rust/kernel/time.rs index b0a8f3c0ba49..1d2600288ed1 100644 --- a/rust/kernel/time.rs +++ b/rust/kernel/time.rs @@ -49,6 +49,87 @@ pub fn msecs_to_jiffies(msecs: Msecs) -> Jiffies { unsafe { bindings::__msecs_to_jiffies(msecs) } } =20 +/// Trait for clock sources. +/// +/// Selection of the clock source depends on the use case. In some cases t= he usage of a +/// particular clock is mandatory, e.g. in network protocols, filesystems.= In other +/// cases the user of the clock has to decide which clock is best suited f= or the +/// purpose. In most scenarios clock [`Monotonic`] is the best choice as it +/// provides a accurate monotonic notion of time (leap second smearing ign= ored). +pub trait ClockSource { + /// The kernel clock ID associated with this clock source. + /// + /// This constant corresponds to the C side `clockid_t` value. + const ID: bindings::clockid_t; +} + +/// A monotonically increasing clock. +/// +/// A nonsettable system-wide clock that represents monotonic time since as +/// described by POSIX, "some unspecified point in the past". On Linux, th= at +/// point corresponds to the number of seconds that the system has been +/// running since it was booted. +/// +/// The CLOCK_MONOTONIC clock is not affected by discontinuous jumps in the +/// CLOCK_REAL (e.g., if the system administrator manually changes the +/// clock), but is affected by frequency adjustments. This clock does not +/// count time that the system is suspended. +pub struct Monotonic; + +impl ClockSource for Monotonic { + const ID: bindings::clockid_t =3D bindings::CLOCK_MONOTONIC as binding= s::clockid_t; +} + +/// A settable system-wide clock that measures real (i.e., wall-clock) tim= e. +/// +/// Setting this clock requires appropriate privileges. This clock is +/// affected by discontinuous jumps in the system time (e.g., if the system +/// administrator manually changes the clock), and by frequency adjustments +/// performed by NTP and similar applications via adjtime(3), adjtimex(2), +/// clock_adjtime(2), and ntp_adjtime(3). This clock normally counts the +/// number of seconds since 1970-01-01 00:00:00 Coordinated Universal Time +/// (UTC) except that it ignores leap seconds; near a leap second it may be +/// adjusted by leap second smearing to stay roughly in sync with UTC. Leap +/// second smearing applies frequency adjustments to the clock to speed up +/// or slow down the clock to account for the leap second without +/// discontinuities in the clock. If leap second smearing is not applied, +/// the clock will experience discontinuity around leap second adjustment. +pub struct RealTime; + +impl ClockSource for RealTime { + const ID: bindings::clockid_t =3D bindings::CLOCK_REALTIME as bindings= ::clockid_t; +} + +/// A monotonic that ticks while system is suspended. +/// +/// A nonsettable system-wide clock that is identical to CLOCK_MONOTONIC, +/// except that it also includes any time that the system is suspended. Th= is +/// allows applications to get a suspend-aware monotonic clock without +/// having to deal with the complications of CLOCK_REALTIME, which may have +/// discontinuities if the time is changed using settimeofday(2) or simila= r. +pub struct BootTime; + +impl ClockSource for BootTime { + const ID: bindings::clockid_t =3D bindings::CLOCK_BOOTTIME as bindings= ::clockid_t; +} + +/// International Atomic Time. +/// +/// A system-wide clock derived from wall-clock time but counting leap sec= onds. +/// +/// This clock is coupled to CLOCK_REALTIME and will be set when CLOCK_REA= LTIME is +/// set, or when the offset to CLOCK_REALTIME is changed via adjtimex(2). = This +/// usually happens during boot and **should** not happen during normal op= erations. +/// However, if NTP or another application adjusts CLOCK_REALTIME by leap = second +/// smearing, this clock will not be precise during leap second smearing. +/// +/// The acronym TAI refers to International Atomic Time. +pub struct Tai; + +impl ClockSource for Tai { + const ID: bindings::clockid_t =3D bindings::CLOCK_TAI as bindings::clo= ckid_t; +} + /// A specific point in time. /// /// # Invariants @@ -91,72 +172,6 @@ fn sub(self, other: Instant) -> Delta { } } =20 -/// An identifier for a clock. Used when specifying clock sources. -/// -/// -/// Selection of the clock depends on the use case. In some cases the usag= e of a -/// particular clock is mandatory, e.g. in network protocols, filesystems.= In other -/// cases the user of the clock has to decide which clock is best suited f= or the -/// purpose. In most scenarios clock [`ClockId::Monotonic`] is the best ch= oice as it -/// provides a accurate monotonic notion of time (leap second smearing ign= ored). -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -#[repr(u32)] -pub enum ClockId { - /// A settable system-wide clock that measures real (i.e., wall-clock)= time. - /// - /// Setting this clock requires appropriate privileges. This clock is - /// affected by discontinuous jumps in the system time (e.g., if the s= ystem - /// administrator manually changes the clock), and by frequency adjust= ments - /// performed by NTP and similar applications via adjtime(3), adjtimex= (2), - /// clock_adjtime(2), and ntp_adjtime(3). This clock normally counts t= he - /// number of seconds since 1970-01-01 00:00:00 Coordinated Universal = Time - /// (UTC) except that it ignores leap seconds; near a leap second it m= ay be - /// adjusted by leap second smearing to stay roughly in sync with UTC.= Leap - /// second smearing applies frequency adjustments to the clock to spee= d up - /// or slow down the clock to account for the leap second without - /// discontinuities in the clock. If leap second smearing is not appli= ed, - /// the clock will experience discontinuity around leap second adjustm= ent. - RealTime =3D bindings::CLOCK_REALTIME, - /// A monotonically increasing clock. - /// - /// A nonsettable system-wide clock that represents monotonic time sin= ce=E2=80=94as - /// described by POSIX=E2=80=94"some unspecified point in the past". O= n Linux, that - /// point corresponds to the number of seconds that the system has been - /// running since it was booted. - /// - /// The CLOCK_MONOTONIC clock is not affected by discontinuous jumps i= n the - /// CLOCK_REAL (e.g., if the system administrator manually changes the - /// clock), but is affected by frequency adjustments. This clock does = not - /// count time that the system is suspended. - Monotonic =3D bindings::CLOCK_MONOTONIC, - /// A monotonic that ticks while system is suspended. - /// - /// A nonsettable system-wide clock that is identical to CLOCK_MONOTON= IC, - /// except that it also includes any time that the system is suspended= . This - /// allows applications to get a suspend-aware monotonic clock without - /// having to deal with the complications of CLOCK_REALTIME, which may= have - /// discontinuities if the time is changed using settimeofday(2) or si= milar. - BootTime =3D bindings::CLOCK_BOOTTIME, - /// International Atomic Time. - /// - /// A system-wide clock derived from wall-clock time but counting leap= seconds. - /// - /// This clock is coupled to CLOCK_REALTIME and will be set when CLOCK= _REALTIME is - /// set, or when the offset to CLOCK_REALTIME is changed via adjtimex(= 2). This - /// usually happens during boot and **should** not happen during norma= l operations. - /// However, if NTP or another application adjusts CLOCK_REALTIME by l= eap second - /// smearing, this clock will not be precise during leap second smeari= ng. - /// - /// The acronym TAI refers to International Atomic Time. - TAI =3D bindings::CLOCK_TAI, -} - -impl ClockId { - fn into_c(self) -> bindings::clockid_t { - self as bindings::clockid_t - } -} - /// A span of time. /// /// This struct represents a span of time, with its value stored as nanose= conds. diff --git a/rust/kernel/time/hrtimer.rs b/rust/kernel/time/hrtimer.rs index 17824aa0c0f3..380712d4302a 100644 --- a/rust/kernel/time/hrtimer.rs +++ b/rust/kernel/time/hrtimer.rs @@ -67,7 +67,7 @@ //! A `restart` operation on a timer in the **stopped** state is equivalen= t to a //! `start` operation. =20 -use super::ClockId; +use super::ClockSource; use crate::{prelude::*, types::Opaque}; use core::marker::PhantomData; use pin_init::PinInit; @@ -112,7 +112,7 @@ unsafe impl Sync for HrTimer {} =20 impl HrTimer { /// Return an initializer for a new timer instance. - pub fn new(mode: HrTimerMode, clock: ClockId) -> impl PinInit + pub fn new(mode: HrTimerMode) -> impl PinInit where T: HrTimerCallback, { @@ -126,7 +126,7 @@ pub fn new(mode: HrTimerMode, clock: ClockId) -> impl P= inInit bindings::hrtimer_setup( place, Some(T::Pointer::run), - clock.into_c(), + U::ID, mode.into_c(), ); } --=20 2.43.0 From nobody Mon Feb 9 02:42:38 2026 Received: from mail-pl1-f171.google.com (mail-pl1-f171.google.com [209.85.214.171]) (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 541371714C0; Sun, 4 May 2025 04:24:53 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.171 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746332694; cv=none; b=mHqQPQL+LlfK4wW2RK43jjVW7iMaYH0eFC8VuRWFUuEtNcaMOcYVun+cs28KA5vXDdtcexAekt8tOuqmQEmRLaT3i2f8FmGcq0ONZJz9KAb0K3Kyp8MaQ5Pu75W1AtkFejRLKHIXTWpWuQSFVZFjlGfZudt4IEu9Af9YKekDsZI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746332694; c=relaxed/simple; bh=oa6L53FFyHjLEZAlHfEnmPEYcnJH3sI9BHEO7dJXZSU=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=VBqXtoYdfGmRSqQFPoea8LNVRpbad4jxJsQ0aJjNR07Y4Yf3ZD+dRR4ldzbw/H445EEujugAZub+W6UsEZ5DRxA55cozYI0PGJXY2W3OOQCsRr0ILxWQEVT8t+fYmoFFNjfpPVnBDHElupF7NqrmxDeJs4ZsFGuuY+NnrLpLIL4= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=CtsxrU1x; arc=none smtp.client-ip=209.85.214.171 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="CtsxrU1x" Received: by mail-pl1-f171.google.com with SMTP id d9443c01a7336-227d6b530d8so30952095ad.3; Sat, 03 May 2025 21:24:53 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1746332692; x=1746937492; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=NJKFHuvmYYPlzU68ekIyAcFUGAd6JaW2Eyl11HXIMNU=; b=CtsxrU1xEip5QKOIgbHZIa8+FY7COqTdEIgFFdcmTjLPuhPqb69elmvlUZo2y8A8eo xbEzYDHx1LHvpbM9b9wx0XRPrwk9y1gpEaC0SN7imuPpIbsLIo4Mgzkz8POxq2bGzQUl W+xGQ4+HOwzH6ngvnoF+D7JPCgluMAfUb8xlW5EneSvfYz5JDWSdB3xhkhKAIQfFbHbS 7FYpdEN2DawfZnB22Y/XJltfFy3dbeOWCEsXP9bNd6oE5+Y+ttQeaYyfMqSDvPsOVaQv y4zEEyjiDzSY5YhKuMVDFmRoFQx+cTHJKXyNwvlwzKiHdyZN4XYmGa6jF0Eq1TKiXnhl 31Zg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1746332692; x=1746937492; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=NJKFHuvmYYPlzU68ekIyAcFUGAd6JaW2Eyl11HXIMNU=; b=qBvBj2U9SDTIL8NCuXDIQQcLhzInrfQ34GbxaOu5zu+CPRYhg++lNCiUVHO96g+8v1 NOOdWTJX3UtxCUfn2FPsSWmeePRyprm0QcRrvR/J6w3dyXwCjL9dEvaewEgI1eY66CLY e05uy7mQIRbSnd67WyuE6DlwnYxN3wULejz26d5da66zOLxXVwbKynScxFqDsvEz5lR5 PoRflOg7RRu0RV+rnddH5p1rcYLTGo4b3NnvJKGOD/tJNMCICwwplxRltmXub7UjVw+r FoOTgig3llDdx5TfB9InNJAGHU6T1mjCkPQ0mh6Nhk0YCbpm9aTwgGX0DxvPWMGbnTVP LQNg== X-Forwarded-Encrypted: i=1; AJvYcCVP1Vz2OhCkWhOyDufzNtDXs+z6KGcH4OcpwZYw/vmJkaYDH8Br4GoFV2STpKXsyE1mT40PCvsAEHEipFo=@vger.kernel.org X-Gm-Message-State: AOJu0Yyb75kHMgqT2qSI3C2bRB/PsN8Fznyu/C/SanXAeHrhChHzM0BN d5CIUfXeRQ8P01rCyT0sCP6gyCIDmMrMsifK1Vmb72VWWxVzHdT1lp40+H3u X-Gm-Gg: ASbGncsSDUqmpaUqvqjnlJ4kL9M7z+CqZdud+4Z6cZpMzdxay5uG1pP5iTq4FVpCzox dIKJK/+ia8/B/CT3+0PGJw02jEneRxz5ROUBlTtpzxDbAclxf0K+VPPF1v1iGpZYi4svlCHEk3S /NZGe8DMwkQkBXPgVUtGbb+RCigWSTEt+7jAHXE+6HvLwm3Zdz/9VChSEZgLKX3mlsZKxyaAX0g 3ME5y7Q6tWgwRoIsD/ui9HtCAFUWTOEoGyEl8/QSi6Vu+l0AanpcehRi9YgTECxus4eDsNZ1PXS tZ+3l8YWhjyKt+lGmKp5vvdmlHdDrlR3z1YqwQy5Pl050NWuUvx3/tBRo1NKQSjbTAHTDDmoG5s ZFSbbGVQNUiXpjKODcQ== X-Google-Smtp-Source: AGHT+IFm4o0vsx2oajksjk0Vmz17njjhcZdWtw89HpA4PWNpdbhjuHvTegefbphRqRkOTO6df50AMw== X-Received: by 2002:a17:902:ef43:b0:221:7eae:163b with SMTP id d9443c01a7336-22e1037ecb5mr129100125ad.46.1746332692189; Sat, 03 May 2025 21:24:52 -0700 (PDT) Received: from mew.. (p4138183-ipxg22701hodogaya.kanagawa.ocn.ne.jp. [153.129.206.183]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-22e1521fbc8sm31482185ad.142.2025.05.03.21.24.48 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sat, 03 May 2025 21:24:51 -0700 (PDT) From: FUJITA Tomonori To: rust-for-linux@vger.kernel.org Cc: a.hindborg@kernel.org, boqun.feng@gmail.com, frederic@kernel.org, lyude@redhat.com, tglx@linutronix.de, anna-maria@linutronix.de, jstultz@google.com, sboyd@kernel.org, ojeda@kernel.org, alex.gaynor@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, aliceryhl@google.com, tmgross@umich.edu, dakr@kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH v2 2/3] rust: time: Make Instant generic over ClockSource Date: Sun, 4 May 2025 13:24:34 +0900 Message-ID: <20250504042436.237756-3-fujita.tomonori@gmail.com> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20250504042436.237756-1-fujita.tomonori@gmail.com> References: <20250504042436.237756-1-fujita.tomonori@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Refactor the Instant type to be generic over a ClockSource type parameter, enabling static enforcement of clock correctness across APIs that deal with time. Previously, the clock source was implicitly fixed (typically CLOCK_MONOTONIC), and developers had to ensure compatibility manually. This design eliminates runtime mismatches between clock sources, and enables stronger type-level guarantees throughout the timer subsystem. Signed-off-by: FUJITA Tomonori Reviewed-by: Andreas Hindborg --- rust/kernel/time.rs | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/rust/kernel/time.rs b/rust/kernel/time.rs index 1d2600288ed1..3bc76f75bfd0 100644 --- a/rust/kernel/time.rs +++ b/rust/kernel/time.rs @@ -24,6 +24,8 @@ //! C header: [`include/linux/jiffies.h`](srctree/include/linux/jiffies.h). //! C header: [`include/linux/ktime.h`](srctree/include/linux/ktime.h). =20 +use core::marker::PhantomData; + pub mod hrtimer; =20 /// The number of nanoseconds per microsecond. @@ -136,12 +138,21 @@ impl ClockSource for Tai { /// /// The `inner` value is in the range from 0 to `KTIME_MAX`. #[repr(transparent)] -#[derive(Copy, Clone, PartialEq, PartialOrd, Eq, Ord)] -pub struct Instant { +#[derive(PartialEq, PartialOrd, Eq, Ord)] +pub struct Instant { inner: bindings::ktime_t, + _c: PhantomData, } =20 -impl Instant { +impl Clone for Instant { + fn clone(&self) -> Self { + *self + } +} + +impl Copy for Instant {} + +impl Instant { /// Get the current time using `CLOCK_MONOTONIC`. #[inline] pub fn now() -> Self { @@ -150,6 +161,7 @@ pub fn now() -> Self { Self { // SAFETY: It is always safe to call `ktime_get()` outside of = NMI context. inner: unsafe { bindings::ktime_get() }, + _c: PhantomData, } } =20 @@ -160,12 +172,12 @@ pub fn elapsed(&self) -> Delta { } } =20 -impl core::ops::Sub for Instant { +impl core::ops::Sub for Instant { type Output =3D Delta; =20 // By the type invariant, it never overflows. #[inline] - fn sub(self, other: Instant) -> Delta { + fn sub(self, other: Instant) -> Delta { Delta { nanos: self.inner - other.inner, } --=20 2.43.0 From nobody Mon Feb 9 02:42:38 2026 Received: from mail-pg1-f169.google.com (mail-pg1-f169.google.com [209.85.215.169]) (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 44FB317BB35; Sun, 4 May 2025 04:24:57 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.215.169 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746332698; cv=none; b=ES94kEpKecHSTyf2Srho9696t/0N1hWqC39EsrWZ4wxWAm+X4Pc7JEdhFoR1BhOMBDMKf6t1funfnQ441bLMRdNvnKzgGa2OEWOvg68P3ox5hgHBPVKGqC0mjcHVL5KOv+Y72e6ly7tBQDAyD1DU+cdNqDBMtaqI50UjDxN/ZgQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746332698; c=relaxed/simple; bh=1sBK2RO1fUXRegO3hXO+fTjEo09ojRhQfVGN29ukGZ4=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=GMcTDDZaOgpCdfiY+IeNrOG23aMisQf79SVkLF897QrLw2NvGsezwl/s4y7fsnq/m2e37Ted/Jp7r+0UF3h53T5XLjPrFQXwCcM+ASZt3TIPRo/my+mXehorNmh+DhB2F3q3Q+KATNIvvk09YPloRqQdtiv14ThkbilGgTptWOM= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=F/KpjrK6; arc=none smtp.client-ip=209.85.215.169 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="F/KpjrK6" Received: by mail-pg1-f169.google.com with SMTP id 41be03b00d2f7-af908bb32fdso2978252a12.1; Sat, 03 May 2025 21:24:57 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1746332696; x=1746937496; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=+7Tna5veepmGz/9U/3f4p7MVzaMNOPpGUU1xoKU1Tno=; b=F/KpjrK6VE4OxP258JuSk0TCqZckLmhOP3A66faIg6DPrCkbK69WHKx0M/wYFblE5a HXUEMEE8Y5uPEy8MGanfZuxVeQgs9sTkqjsvtMqJMHlY8DSsLrqr8ERmaRWLrG91yfw1 fQAj/ke/eXlNq4MpU+QghSIQX/ogTen5PXcLVLfrUlJt01afI9qamh6PjSeyaWSGxJUi jjxVvOP7E4iDY7lMAzdxKdAoViZQVaFI01E7O2ZWpiZTg/dR7ImwVRRAh78yc83YrWJk WZSo6lifL8ibA2Eks0/yU6fIMUjUmWo8b4KgW5WMa6nKWR7G6TAiOzbQD0dM/XbYX2KK uxlQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1746332696; x=1746937496; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=+7Tna5veepmGz/9U/3f4p7MVzaMNOPpGUU1xoKU1Tno=; b=RrmWzIJdzoAvmTQk1pMoL+NwFYfimufJxzzIx0e92VLsM0Yv4+We+uycCM2ycLdaGa a3CZs8AHzoE+5PXWH6lgrMAxyT44B84vLr0x0Qy7UpgTr2RHXMBnLZgOjPCFs/RvBiu6 C16Vifb8IhFKvXppyA8+HA3xAshUpmG73ypzwHKYjW2JDwT2lMgzW8SwEJx1cZciTcrK yTvhlQvdPw+4c0GBOx/NxgWogRYuLI3DfN8lRsdtPWt2eA6Qgzj1DYvdsqNVmEf4RfLN /i3R2KoLcMeLfem0YRAlgEuH3mkm71mz5I7d3RO/dYcj93Kg9dCsQPiZ5ke4xb4MjVmO mhWw== X-Forwarded-Encrypted: i=1; AJvYcCX3PMxMX/9N5iuGBOdAOZM+5C2mlSG6i8KKlebB8FGVmmtsFKP/twMrY+OX7o4gtnD0sr682340cGqE3zc=@vger.kernel.org X-Gm-Message-State: AOJu0YxUxnEv9fDeO2kwHohnSAi8Qh2WppvI/kSy2dTMHtRuvrFL/yEO e0Su3cfnrO6O7XxW2AeGsxHqp0kYAGw6mOe9qbrZHO6xzfYQW6ht0HVVxR7e X-Gm-Gg: ASbGnctFGvLOMlRPmwXr9c0JDetf7RGnmyVR8ha3ac8267Da2MnQ3mdZQn/00Mj91bO 1V+UoCl8x9YMNte2Tj8CHOAxWl8yhxlPV3nYhk0M/UA8NoH5MupE5G3oK8G/kSuLCBS2CEoG3s/ /oS1LhMpMGZUMMScEgGnJBWkCxCjfYptrMiuvHwW/Hwyo1yLrFeUBTtd/i7l7bYiSZtZxYv9TgW noNvA3DvuX5HNHKCqjzqHIvtOu5MnjHyuK3R/5kBclmBk2RvGBsCruHEaTwW/MKs2boH7QZ4FNL upprwrutk7zyLj7vqv9EXexKVAY+bYHkwNAU767kMf35c0Gz2kwphBg1RHOeyFB6NUcT2fBrtpG j+9np9/nXsUeVkEpSuQ== X-Google-Smtp-Source: AGHT+IF+q32viBchNhIVP0ATOeLTCT175civYMi9xVnpHibFJtK/AnWe4JHRr6QKeFO/i3Yjiv/CXw== X-Received: by 2002:a17:902:f607:b0:221:751f:cfbe with SMTP id d9443c01a7336-22e100a19d8mr144016635ad.19.1746332696282; Sat, 03 May 2025 21:24:56 -0700 (PDT) Received: from mew.. (p4138183-ipxg22701hodogaya.kanagawa.ocn.ne.jp. [153.129.206.183]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-22e1521fbc8sm31482185ad.142.2025.05.03.21.24.52 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sat, 03 May 2025 21:24:55 -0700 (PDT) From: FUJITA Tomonori To: rust-for-linux@vger.kernel.org Cc: Andreas Hindborg , boqun.feng@gmail.com, frederic@kernel.org, lyude@redhat.com, tglx@linutronix.de, anna-maria@linutronix.de, jstultz@google.com, sboyd@kernel.org, ojeda@kernel.org, alex.gaynor@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, aliceryhl@google.com, tmgross@umich.edu, dakr@kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH v2 3/3] rust: time: Add ktime_get() to ClockSource trait Date: Sun, 4 May 2025 13:24:35 +0900 Message-ID: <20250504042436.237756-4-fujita.tomonori@gmail.com> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20250504042436.237756-1-fujita.tomonori@gmail.com> References: <20250504042436.237756-1-fujita.tomonori@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Introduce the ktime_get() associated function to the ClockSource trait, allowing each clock source to specify how it retrieves the current time. This enables Instant::now() to be implemented generically using the type-level ClockSource abstraction. This change enhances the type safety and extensibility of timekeeping by statically associating time retrieval mechanisms with their respective clock types. It also reduces the reliance on hardcoded clock logic within Instant. Reviewed-by: Andreas Hindborg Signed-off-by: FUJITA Tomonori --- rust/helpers/time.c | 16 ++++++++++++++++ rust/kernel/time.rs | 32 ++++++++++++++++++++++++++++---- 2 files changed, 44 insertions(+), 4 deletions(-) diff --git a/rust/helpers/time.c b/rust/helpers/time.c index 3d31473bce08..31208f1042a1 100644 --- a/rust/helpers/time.c +++ b/rust/helpers/time.c @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-2.0 =20 #include +#include =20 s64 rust_helper_ktime_to_us(const ktime_t kt) { @@ -11,3 +12,18 @@ s64 rust_helper_ktime_to_ms(const ktime_t kt) { return ktime_to_ms(kt); } + +ktime_t rust_helper_ktime_get_real(void) +{ + return ktime_get_with_offset(TK_OFFS_REAL); +} + +ktime_t rust_helper_ktime_get_boottime(void) +{ + return ktime_get_with_offset(TK_OFFS_BOOT); +} + +ktime_t rust_helper_ktime_get_clocktai(void) +{ + return ktime_get_with_offset(TK_OFFS_TAI); +} diff --git a/rust/kernel/time.rs b/rust/kernel/time.rs index 3bc76f75bfd0..1be5ecd814d3 100644 --- a/rust/kernel/time.rs +++ b/rust/kernel/time.rs @@ -63,6 +63,11 @@ pub trait ClockSource { /// /// This constant corresponds to the C side `clockid_t` value. const ID: bindings::clockid_t; + + /// Get the current time from the clock source. + /// + /// The function must return a value in the range from 0 to `KTIME_MAX= `. + fn ktime_get() -> bindings::ktime_t; } =20 /// A monotonically increasing clock. @@ -80,6 +85,11 @@ pub trait ClockSource { =20 impl ClockSource for Monotonic { const ID: bindings::clockid_t =3D bindings::CLOCK_MONOTONIC as binding= s::clockid_t; + + fn ktime_get() -> bindings::ktime_t { + // SAFETY: It is always safe to call `ktime_get()` outside of NMI = context. + unsafe { bindings::ktime_get() } + } } =20 /// A settable system-wide clock that measures real (i.e., wall-clock) tim= e. @@ -100,6 +110,11 @@ impl ClockSource for Monotonic { =20 impl ClockSource for RealTime { const ID: bindings::clockid_t =3D bindings::CLOCK_REALTIME as bindings= ::clockid_t; + + fn ktime_get() -> bindings::ktime_t { + // SAFETY: It is always safe to call `ktime_get_real()` outside of= NMI context. + unsafe { bindings::ktime_get_real() } + } } =20 /// A monotonic that ticks while system is suspended. @@ -113,6 +128,11 @@ impl ClockSource for RealTime { =20 impl ClockSource for BootTime { const ID: bindings::clockid_t =3D bindings::CLOCK_BOOTTIME as bindings= ::clockid_t; + + fn ktime_get() -> bindings::ktime_t { + // SAFETY: It is always safe to call `ktime_get_boottime()` outsid= e of NMI context. + unsafe { bindings::ktime_get_boottime() } + } } =20 /// International Atomic Time. @@ -130,6 +150,11 @@ impl ClockSource for BootTime { =20 impl ClockSource for Tai { const ID: bindings::clockid_t =3D bindings::CLOCK_TAI as bindings::clo= ckid_t; + + fn ktime_get() -> bindings::ktime_t { + // SAFETY: It is always safe to call `ktime_get_tai()` outside of = NMI context. + unsafe { bindings::ktime_get_clocktai() } + } } =20 /// A specific point in time. @@ -153,14 +178,13 @@ fn clone(&self) -> Self { impl Copy for Instant {} =20 impl Instant { - /// Get the current time using `CLOCK_MONOTONIC`. + /// Get the current time from the clock source. #[inline] pub fn now() -> Self { - // INVARIANT: The `ktime_get()` function returns a value in the ra= nge + // INVARIANT: The `ClockSource::ktime_get()` function returns a va= lue in the range // from 0 to `KTIME_MAX`. Self { - // SAFETY: It is always safe to call `ktime_get()` outside of = NMI context. - inner: unsafe { bindings::ktime_get() }, + inner: C::ktime_get(), _c: PhantomData, } } --=20 2.43.0