From nobody Sat Feb 7 22:07:55 2026 Received: from galois.linutronix.de (Galois.linutronix.de [193.142.43.55]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id CBDEF1F4289 for ; Mon, 24 Feb 2025 10:15:25 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=193.142.43.55 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740392127; cv=none; b=hC4eMLf/apyGPxYnkRXewxInlGE3VOHsSWalVOv5V8A8H6mMb9hdS00wE0OvD/5ElTjr86QuOg9JnqtgFJDJs4D/7Es0cc65R6PdE/EvomAqk70ADACg5j0OfuaGSXF5gdSSLO/V7gfGHrA4UhQQ2ha7qive8idELRiAkY+pY0E= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740392127; c=relaxed/simple; bh=Q9H5c4d2GSWvO0XsE5rchm4JPqe7txtl4JIBmyINDsE=; h=Message-ID:From:To:Cc:Subject:References:MIME-Version: Content-Type:Date; b=lGSwF/FTAVzvYhQt4Sa+Roat5LRzjfrkyRSPSUx3a4/QkzQZ06Fso+5ZJF+/dce+T8q0HwPHroZK1u0+0IZu2NSUyp3MqG7C7xVFHgWT/famtQEl7T9KRMSNja70rVWgEIxy4p9VP3PvB6m9XftP3GjebhhfEc5WINqGF6jznzg= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linutronix.de; spf=pass smtp.mailfrom=linutronix.de; dkim=pass (2048-bit key) header.d=linutronix.de header.i=@linutronix.de header.b=q0MKpOAi; dkim=permerror (0-bit key) header.d=linutronix.de header.i=@linutronix.de header.b=3mPCPBJx; arc=none smtp.client-ip=193.142.43.55 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linutronix.de Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linutronix.de Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linutronix.de header.i=@linutronix.de header.b="q0MKpOAi"; dkim=permerror (0-bit key) header.d=linutronix.de header.i=@linutronix.de header.b="3mPCPBJx" Message-ID: <20250224101343.011835342@linutronix.de> DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linutronix.de; s=2020; t=1740392124; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: references:references; bh=aICCvsBZar4WrHQa6TttvV8MzfJyFFmhB1WgVQ9rg9c=; b=q0MKpOAiU9VivPW08RKoYc3H5lGU5jCdcdsQ+DG3RsNE7nDCQhbT+SF5hczjR0Txtd/6iK 0t55bcfwPTVEJ+APZ+5FssqjsS7o4SfcSzJ+q9rv+tfiuYhgP6olFXKiOJUF39myGxJI61 swF3f5+jfIxfVeJW4Sl4QR+7qLhqENAvu0B6MeUoJs1lckWumLcEJdlOt2fDQ2r/izD7vV IPxsOfDeb2zhmPMFHxERrpBwV0o70iTMh0hK3V/1Eb3e1igze5hhlp5bjl8G7rzmfKw5pb DhSOkX3uQNVDs1aX5HMiUa0dJdmxXpeRYBRbeb4rzP3spUZmk0V8umV6FAAZHA== DKIM-Signature: v=1; a=ed25519-sha256; c=relaxed/relaxed; d=linutronix.de; s=2020e; t=1740392124; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: references:references; bh=aICCvsBZar4WrHQa6TttvV8MzfJyFFmhB1WgVQ9rg9c=; b=3mPCPBJxxVDcrfHjFSbKtoF3+sfj+jKC0vrHUFh6Q/rY44mk2c3nnPHp1T0Xjh+F71XX0I jQMSQw6IdlwFZwCg== From: Thomas Gleixner To: LKML Cc: Anna-Maria Behnsen , Frederic Weisbecker , Benjamin Segall , Eric Dumazet , Andrey Vagin , Pavel Tikhomirov , Peter Zijlstra Subject: [patch 01/11] posix-timers: Initialise timer before adding it to the hash table References: <20250224095736.145530367@linutronix.de> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Date: Mon, 24 Feb 2025 11:15:23 +0100 (CET) Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" From: Eric Dumazet A timer is only valid in the hashtable when both timer::it_signal and timer::it_id are set to their final values, but timers are added without those values being set. The timer ID is allocated when the timer is added to the hash in invalid state. The ID is taken from a monotonically increasing per process counter which wraps around after reaching INT_MAX. The hash insertion validates that there is no timer with the allocated ID in the hash table which belongs to the same process. That opens a mostly theoretical race condition: If other threads of the same process manage to create/delete timers in rapid succession before the newly created timer is fully initialized and wrap around to the timer ID which was handed out, then a duplicate timer ID will be inserted into the hash table. Prevent this by: 1) Setting timer::it_id before inserting the timer into the hashtable. =20 2) Storing the signal pointer in timer::it_signal with bit 0 set before inserting it into the hashtable. Bit 0 acts as a invalid bit, which means that the regular lookup for sys_timer_*() will fail the comparison with the signal pointer. But the lookup on insertion masks out bit 0 and can therefore detect a timer which is not yet valid, but allocated in the hash table. Bit 0 in the pointer is cleared once the initialization of the timer completed. [ tglx: Fold ID and signal iniitializaion into one patch and massage change log and comments. ] Signed-off-by: Eric Dumazet Signed-off-by: Thomas Gleixner Link: https://lore.kernel.org/all/20250219125522.2535263-3-edumazet@google.= com --- kernel/time/posix-timers.c | 56 +++++++++++++++++++++++++++++++++-------= ----- 1 file changed, 42 insertions(+), 14 deletions(-) --- a/kernel/time/posix-timers.c +++ b/kernel/time/posix-timers.c @@ -72,13 +72,13 @@ static int hash(struct signal_struct *si return hash_32(hash32_ptr(sig) ^ nr, HASH_BITS(posix_timers_hashtable)); } =20 -static struct k_itimer *__posix_timers_find(struct hlist_head *head, - struct signal_struct *sig, - timer_t id) +static struct k_itimer *posix_timer_by_id(timer_t id) { + struct signal_struct *sig =3D current->signal; + struct hlist_head *head =3D &posix_timers_hashtable[hash(sig, id)]; struct k_itimer *timer; =20 - hlist_for_each_entry_rcu(timer, head, t_hash, lockdep_is_held(&hash_lock)= ) { + hlist_for_each_entry_rcu(timer, head, t_hash) { /* timer->it_signal can be set concurrently */ if ((READ_ONCE(timer->it_signal) =3D=3D sig) && (timer->it_id =3D=3D id)) return timer; @@ -86,12 +86,26 @@ static struct k_itimer *__posix_timers_f return NULL; } =20 -static struct k_itimer *posix_timer_by_id(timer_t id) +static inline struct signal_struct *posix_sig_owner(const struct k_itimer = *timer) { - struct signal_struct *sig =3D current->signal; - struct hlist_head *head =3D &posix_timers_hashtable[hash(sig, id)]; + unsigned long val =3D (unsigned long)timer->it_signal; + + /* + * Mask out bit 0, which acts as invalid marker to prevent + * posix_timer_by_id() detecting it as valid. + */ + return (struct signal_struct *)(val & ~1UL); +} + +static bool posix_timer_hashed(struct hlist_head *head, struct signal_stru= ct *sig, timer_t id) +{ + struct k_itimer *timer; =20 - return __posix_timers_find(head, sig, id); + hlist_for_each_entry_rcu(timer, head, t_hash, lockdep_is_held(&hash_lock)= ) { + if ((posix_sig_owner(timer) =3D=3D sig) && (timer->it_id =3D=3D id)) + return true; + } + return false; } =20 static int posix_timer_add(struct k_itimer *timer) @@ -112,7 +126,19 @@ static int posix_timer_add(struct k_itim sig->next_posix_timer_id =3D (id + 1) & INT_MAX; =20 head =3D &posix_timers_hashtable[hash(sig, id)]; - if (!__posix_timers_find(head, sig, id)) { + if (!posix_timer_hashed(head, sig, id)) { + /* + * Set the timer ID and the signal pointer to make + * it identifiable in the hash table. The signal + * pointer has bit 0 set to indicate that it is not + * yet fully initialized. posix_timer_hashed() + * masks this bit out, but the syscall lookup fails + * to match due to it being set. This guarantees + * that there can't be duplicate timer IDs handed + * out. + */ + timer->it_id =3D (timer_t)id; + timer->it_signal =3D (struct signal_struct *)((unsigned long)sig | 1UL); hlist_add_head_rcu(&timer->t_hash, head); spin_unlock(&hash_lock); return id; @@ -406,8 +432,7 @@ static int do_timer_create(clockid_t whi =20 /* * Add the timer to the hash table. The timer is not yet valid - * because new_timer::it_signal is still NULL. The timer id is also - * not yet visible to user space. + * after insertion, but has a unique ID allocated. */ new_timer_id =3D posix_timer_add(new_timer); if (new_timer_id < 0) { @@ -415,7 +440,6 @@ static int do_timer_create(clockid_t whi return new_timer_id; } =20 - new_timer->it_id =3D (timer_t) new_timer_id; new_timer->it_clock =3D which_clock; new_timer->kclock =3D kc; new_timer->it_overrun =3D -1LL; @@ -453,7 +477,7 @@ static int do_timer_create(clockid_t whi } /* * After succesful copy out, the timer ID is visible to user space - * now but not yet valid because new_timer::signal is still NULL. + * now but not yet valid because new_timer::signal low order bit is 1. * * Complete the initialization with the clock specific create * callback. @@ -463,7 +487,11 @@ static int do_timer_create(clockid_t whi goto out; =20 spin_lock_irq(¤t->sighand->siglock); - /* This makes the timer valid in the hash table */ + /* + * new_timer::it_signal contains the signal pointer with bit 0 set, + * which makes it invalid for syscall operations. Store the + * unmodified signal pointer to make it valid. + */ WRITE_ONCE(new_timer->it_signal, current->signal); hlist_add_head(&new_timer->list, ¤t->signal->posix_timers); spin_unlock_irq(¤t->sighand->siglock); From nobody Sat Feb 7 22:07:55 2026 Received: from galois.linutronix.de (Galois.linutronix.de [193.142.43.55]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 61DA424A075 for ; Mon, 24 Feb 2025 10:15:27 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=193.142.43.55 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740392128; cv=none; b=VZJTwXVQAsFYMfoYFQnf9jRWjFJinALuf48uNzh6DnfJCQs8zq5Whi7VNy/Gwbrvv9lOY4V/QuHKYT0GR8XQil5Zqve+GkP+nDorVTFYyLMBl8V+UnHps2nE0r4Byg+5onySQ6tboP8kdLovhOjQzmQ/aUDhpt2UKAmtKA0U1J0= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740392128; c=relaxed/simple; bh=oQlvzcCQFZGNU6jYrXc8Ejg3LVjNXwVuwT4rrg25Vc4=; h=Message-ID:From:To:Cc:Subject:References:MIME-Version: Content-Type:Date; b=F4yuzhiArl46aj9MFm4jlVCVdMHQR3q38ERLGV1J8wFIwyfoN3XDmZ6tHLvOL4vS/NWK8aY3rWFUnKp6evSOleImFN2kwj5myRH/T+CIYQ8/EBW8sbsYPyq6RPoF0zTntYHK5zaL/fDO2rcaEY/zGuVRqqjNgL2fdoZIzII6ptM= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linutronix.de; spf=pass smtp.mailfrom=linutronix.de; dkim=pass (2048-bit key) header.d=linutronix.de header.i=@linutronix.de header.b=n7Vc0Tvu; dkim=permerror (0-bit key) header.d=linutronix.de header.i=@linutronix.de header.b=vul37pfq; arc=none smtp.client-ip=193.142.43.55 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linutronix.de Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linutronix.de Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linutronix.de header.i=@linutronix.de header.b="n7Vc0Tvu"; dkim=permerror (0-bit key) header.d=linutronix.de header.i=@linutronix.de header.b="vul37pfq" Message-ID: <20250224101343.078382991@linutronix.de> DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linutronix.de; s=2020; t=1740392125; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: references:references; bh=01lH/N7MkBCPfiP/7juACA911yRh9opjqKqKmt1gXEs=; b=n7Vc0TvuPivoUf80HcFzQyk5nsEFGqS9IK44m+qEf41VjU6kimR+V7lIRuzl3q4H1eGcYz x8PzR89TYE6PiEdWHAaBJHwgai9pDNDu2lX1QnlMM1LlMDM1dcA5LfA99+y1ImBE4cIBYk vO85ddwkYQJvrM7KTCgeDGki7x00uJ47Doc5M214+dWJFjv1sH3tkhzJBLPm0BiIcHSKOe kpBvjnUalDzjXNcUUsDg9oazQq3UDN7dUBs6nKS3zKzw9TXdkK4Dt1xUfCFmdd0W0eGf1d 5NsVsG/OlmZj/pdXdpBEY2QJ7p/Gr4ydRl44QtRtriQ5f9QGnGIaklZbyitwfA== DKIM-Signature: v=1; a=ed25519-sha256; c=relaxed/relaxed; d=linutronix.de; s=2020e; t=1740392125; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: references:references; bh=01lH/N7MkBCPfiP/7juACA911yRh9opjqKqKmt1gXEs=; b=vul37pfqSTKI+ljhHrHN355oM3Zq+CRZhLL9+RWlg4MYyEq/dYJhQsGX01cscRpnPxpsCX 69TqKNz+/cYB11AQ== From: Thomas Gleixner To: LKML Cc: Anna-Maria Behnsen , Frederic Weisbecker , Benjamin Segall , Eric Dumazet , Andrey Vagin , Pavel Tikhomirov , Peter Zijlstra Subject: [patch 02/11] posix-timers: Add cond_resched() to posix_timer_add() search loop References: <20250224095736.145530367@linutronix.de> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Date: Mon, 24 Feb 2025 11:15:25 +0100 (CET) Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" From: Eric Dumazet With a large number of POSIX timers the search for a valid ID might cause a soft lockup on PREEMPT_NONE/VOLUNTARY kernels. Add cond_resched() to the loop to prevent that. [ tglx: Split out from Eric's series ] Signed-off-by: Eric Dumazet Signed-off-by: Thomas Gleixner Link: https://lore.kernel.org/all/20250214135911.2037402-2-edumazet@google.= com --- kernel/time/posix-timers.c | 1 + 1 file changed, 1 insertion(+) --- a/kernel/time/posix-timers.c +++ b/kernel/time/posix-timers.c @@ -144,6 +144,7 @@ static int posix_timer_add(struct k_itim return id; } spin_unlock(&hash_lock); + cond_resched(); } /* POSIX return code when no timer ID could be allocated */ return -EAGAIN; From nobody Sat Feb 7 22:07:55 2026 Received: from galois.linutronix.de (Galois.linutronix.de [193.142.43.55]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 6B56224F5A4 for ; Mon, 24 Feb 2025 10:15:29 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=193.142.43.55 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740392130; cv=none; b=uiL+c6kzRf+Z6yJwZQPtVY+Vu+N3EqFQQXetG4D8OZEqL9TXfRVgwA80JMQutIwl7S6dkIRaGMGrvZROh/wuULXRlt8czBs1cdW8G17HOC91k3x3NFV1NW9ibKpvWR4BX8C2cbP8yA9r8THHzzmL9AlWzABv8Se+D1NqQRlzBz0= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740392130; c=relaxed/simple; bh=YuCCqu2WJyvGIMJolIDYCOzTiBIB7QWQZ3Kkw08rbs0=; h=Message-ID:From:To:Cc:Subject:References:MIME-Version: Content-Type:Date; b=XGS0wJVGccy8MlXsdUCP+3E5MJhF4Yl4H1zPt3ZKu1WYXXlkNH07NsIJTANTleDiS/TZpY42zksGCyZ6DoSFEODxOIXyjjCOuIirrDAi/4Vl/l9j/SXtcjH/HXEvOHTCjiujclmF/AB98tw/nNa20Ply1tUONsVeTGnhTqhpDew= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linutronix.de; spf=pass smtp.mailfrom=linutronix.de; dkim=pass (2048-bit key) header.d=linutronix.de header.i=@linutronix.de header.b=qf/VzE6g; dkim=permerror (0-bit key) header.d=linutronix.de header.i=@linutronix.de header.b=zBT+udGT; arc=none smtp.client-ip=193.142.43.55 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linutronix.de Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linutronix.de Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linutronix.de header.i=@linutronix.de header.b="qf/VzE6g"; dkim=permerror (0-bit key) header.d=linutronix.de header.i=@linutronix.de header.b="zBT+udGT" Message-ID: <20250224101343.145414888@linutronix.de> DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linutronix.de; s=2020; t=1740392127; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: references:references; bh=06e/nLkYRQzPGWTt39F2KrcgBwQj9ajKa6Dm+qJCWzw=; b=qf/VzE6goSJCERBuFz1Y/5vwJX9qrf09SzHBhUOJF+ZmgTYg7tLnXGdGg3wOX5ii5lcpft A7cQMw5DBDukhHXHXZgxE9u67xDIdc3SWBmIYlkckzJjVmOJ87w8/FqspqDfmLZuvJZuUI CmXWrDdjRTzQ7UlVMMUnzsTRifQ/FDS3zbWee+OHtWhuGjSfxtAkWwANF5OYKcXrLV6bFP 5Rntb4AshqL1DPy2pwXLqjpfd7nw9w+HzPIBmceg502RU6hRU/tPz/A2MeckJfhG60VFpG PAnGhPIWSJeHjFa5N9DyZFwVhonFA8zBWhzAkZ7sr8OpYpEL5bmSvpaY8rJRoQ== DKIM-Signature: v=1; a=ed25519-sha256; c=relaxed/relaxed; d=linutronix.de; s=2020e; t=1740392127; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: references:references; bh=06e/nLkYRQzPGWTt39F2KrcgBwQj9ajKa6Dm+qJCWzw=; b=zBT+udGTCIOKpU92GttOixVsjED9IeuN4yqvOITytL3SjA7jVlePLCaCPFVA1vIe1jdiO/ /R9ZcU4dcc3IxoBA== From: Thomas Gleixner To: LKML Cc: Anna-Maria Behnsen , Frederic Weisbecker , Benjamin Segall , Eric Dumazet , Andrey Vagin , Pavel Tikhomirov , Peter Zijlstra Subject: [patch 03/11] posix-timers: Cleanup includes References: <20250224095736.145530367@linutronix.de> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Date: Mon, 24 Feb 2025 11:15:26 +0100 (CET) Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Remove pointless includes and sort the remaining ones alphabetically. Signed-off-by: Thomas Gleixner --- kernel/time/posix-timers.c | 26 ++++++++++---------------- 1 file changed, 10 insertions(+), 16 deletions(-) --- a/kernel/time/posix-timers.c +++ b/kernel/time/posix-timers.c @@ -9,28 +9,22 @@ * * These are all the functions necessary to implement POSIX clocks & timers */ -#include -#include -#include -#include -#include -#include - -#include -#include -#include +#include #include #include +#include +#include +#include +#include +#include #include #include +#include +#include #include -#include -#include -#include -#include -#include -#include +#include #include +#include =20 #include "timekeeping.h" #include "posix-timers.h" From nobody Sat Feb 7 22:07:55 2026 Received: from galois.linutronix.de (Galois.linutronix.de [193.142.43.55]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E185D250BFF for ; Mon, 24 Feb 2025 10:15:30 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=193.142.43.55 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740392132; cv=none; b=ealJhRtWs39+OYGgLprvKDHHOpr6yIZ52puyFU514aBrVNUxhEulVO6x3G34MIGC27/Evtll6loB//OE3N+dHL98i8oPKQuy5bREPRrLyuB7Kvx8OjcFBTI//vJTGAzf+aUFjpsI4nS5TH6mNh0p3oe+k2SrEO7epPk5xKz63nI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740392132; c=relaxed/simple; bh=DHbJrH7Wy2Qgrxrm10ExE1EJqyog3aCCmza3aa8M7VE=; h=Message-ID:From:To:Cc:Subject:References:MIME-Version: Content-Type:Date; b=RXRbqKGb5kZyqdsX0V32T/49v8g3lxW8sMAlY1pyI5/nBXTNGyHknlVYaB5/FptLmuIy3lxrfA/m1mROXzjN1+eOCVBXVHg+PjVoknwHAuSZaYPbPwxBPaTeTBcku0UQ56MxAGNVdgqWHtXb+yjZ88hsIazrq1j6ToXSOjcSrQw= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linutronix.de; spf=pass smtp.mailfrom=linutronix.de; dkim=pass (2048-bit key) header.d=linutronix.de header.i=@linutronix.de header.b=BdUqDahJ; dkim=permerror (0-bit key) header.d=linutronix.de header.i=@linutronix.de header.b=hN4rsXSQ; arc=none smtp.client-ip=193.142.43.55 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linutronix.de Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linutronix.de Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linutronix.de header.i=@linutronix.de header.b="BdUqDahJ"; dkim=permerror (0-bit key) header.d=linutronix.de header.i=@linutronix.de header.b="hN4rsXSQ" Message-ID: <20250224101343.211872476@linutronix.de> DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linutronix.de; s=2020; t=1740392129; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: references:references; bh=IeocMCfWumPqvW9Qhzgc4ByoA3vEdEKIXpzY+ZUrsp0=; b=BdUqDahJXBOiiAllt17mDdMQ4pN22rY1boweAmQ5J84PVJJtWgkNSqBIBSkcB6c6hysDZZ 6GK6gccKpR0swzzC1Zun22HtLy6fVKssoMLcxfxbQeOX9Ias5n61CCpjAEgwoN+ojzXgto FKHm77/EdnrgIN0DOPHrDxvm76biwxa8fCC1LrFJqfK/kgG+WZRETOVlJ4e1hAJGujdE2k 3eqH6lEqMvQtv7yUbree++OG+1bUMIHO/9UVZsFhoCkAeYIsNk1c9Y3H9FNdm+AkOMBlam nKWBIvj4wpgknGTemlaWnn9aY+W005vTH8jUhrrBa9RtDmfjwf7jrr4uUp90ZA== DKIM-Signature: v=1; a=ed25519-sha256; c=relaxed/relaxed; d=linutronix.de; s=2020e; t=1740392129; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: references:references; bh=IeocMCfWumPqvW9Qhzgc4ByoA3vEdEKIXpzY+ZUrsp0=; b=hN4rsXSQ6khTEIY5r6M5sXcA62YLo0JmJKJav4tcl4JGVEIDnX2/pSWZuQ9LyeyDCRbIDj ybZSGp9zpMgPQmAw== From: Thomas Gleixner To: LKML Cc: Anna-Maria Behnsen , Frederic Weisbecker , Benjamin Segall , Eric Dumazet , Andrey Vagin , Pavel Tikhomirov , Peter Zijlstra Subject: [patch 04/11] posix-timers: Remove pointless unlock_timer() wrapper References: <20250224095736.145530367@linutronix.de> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Date: Mon, 24 Feb 2025 11:15:28 +0100 (CET) Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" It's just a wrapper around spin_unlock_irqrestore() with zero value. Signed-off-by: Thomas Gleixner --- kernel/time/posix-timers.c | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) --- a/kernel/time/posix-timers.c +++ b/kernel/time/posix-timers.c @@ -144,11 +144,6 @@ static int posix_timer_add(struct k_itim return -EAGAIN; } =20 -static inline void unlock_timer(struct k_itimer *timr, unsigned long flags) -{ - spin_unlock_irqrestore(&timr->it_lock, flags); -} - static int posix_get_realtime_timespec(clockid_t which_clock, struct times= pec64 *tp) { ktime_get_real_ts64(tp); @@ -691,7 +686,7 @@ static int do_timer_gettime(timer_t time else kc->timer_get(timr, setting); =20 - unlock_timer(timr, flags); + spin_unlock_irqrestore(&timr->it_lock, flags); return ret; } =20 @@ -755,7 +750,7 @@ SYSCALL_DEFINE1(timer_getoverrun, timer_ return -EINVAL; =20 overrun =3D timer_overrun_to_int(timr); - unlock_timer(timr, flags); + spin_unlock_irqrestore(&timr->it_lock, flags); =20 return overrun; } @@ -822,7 +817,7 @@ static struct k_itimer *timer_wait_runni =20 /* Prevent kfree(timer) after dropping the lock */ rcu_read_lock(); - unlock_timer(timer, *flags); + spin_unlock_irqrestore(&timer->it_lock, *flags); =20 /* * kc->timer_wait_running() might drop RCU lock. So @timer @@ -928,7 +923,7 @@ static int do_timer_settime(timer_t time timr =3D timer_wait_running(timr, &flags); goto retry; } - unlock_timer(timr, flags); + spin_unlock_irqrestore(&timr->it_lock, flags); =20 return error; } @@ -1046,7 +1041,7 @@ SYSCALL_DEFINE1(timer_delete, timer_t, t WRITE_ONCE(timer->it_signal, NULL); spin_unlock(¤t->sighand->siglock); =20 - unlock_timer(timer, flags); + spin_unlock_irqrestore(&timer->it_lock, flags); posix_timer_unhash_and_free(timer); return 0; } From nobody Sat Feb 7 22:07:55 2026 Received: from galois.linutronix.de (Galois.linutronix.de [193.142.43.55]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id AB8892528FB for ; Mon, 24 Feb 2025 10:15:32 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=193.142.43.55 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740392134; cv=none; b=Gq8N9bQ/5mo4mwGPi61A4RhStPJXqHwxm+9uXXp723hBuhNplyJJdYhSzlWIFrzxUyySxeyb8Ph0FVUwVU//VsXrRAYZj5OmMPrOAErKLHU/ocLfpt9xdNnPo42QY1xM2esixAUSYNSVHpXZYc9HHYBN54rL0+puMCgdaS+HvGA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740392134; c=relaxed/simple; bh=us16OfR37IveHWlWb26AIbWGv/bx0F5NNiaqZiX9su0=; h=Message-ID:From:To:Cc:Subject:References:MIME-Version: Content-Type:Date; b=iSa77R7+hSfF/bLHn8sNGDyzs1DNZLOox25kO/zHyXL0cCKtLIQgOTRpEWgJ6jAvc9GpqAX5JgHumyPlm0Z4xla9X0ZHZKXo1d/HYrWAikQv4ncMR32lYNIOUVoYfev3Sm2KkIikQB3sjgcc7nd6eeoVF5v74aTN8Ujl/8maLow= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linutronix.de; spf=pass smtp.mailfrom=linutronix.de; dkim=pass (2048-bit key) header.d=linutronix.de header.i=@linutronix.de header.b=MMmHGDl/; dkim=permerror (0-bit key) header.d=linutronix.de header.i=@linutronix.de header.b=Qmd9X/hC; arc=none smtp.client-ip=193.142.43.55 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linutronix.de Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linutronix.de Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linutronix.de header.i=@linutronix.de header.b="MMmHGDl/"; dkim=permerror (0-bit key) header.d=linutronix.de header.i=@linutronix.de header.b="Qmd9X/hC" Message-ID: <20250224101343.277679848@linutronix.de> DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linutronix.de; s=2020; t=1740392131; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: references:references; bh=1NcwSQHUYGMReXSkzTA7ZP6MuBB2dzTz3GVp7qZIRZw=; b=MMmHGDl/hKHbyBojjyOJ7IJDXEjcDXRynblyBid8hnw82717uQFBVI1cN5Pv3xr2TktM8I Ul778Qpw/IYg+HmInLdrAk0tKVXyef7EC+kP5Wu3NV7ql+w4PWGkmj7ca1YwI1w+oiI9tb n6hgqEfZWCMWOhPUlXHJFiiNg45H6K4XBZqWDP/7vSwvkavvxx/Ql0tsRnN2ZD41xSu7SA Hp3vhG8OYehfHOqHAfNmLBpDsn0zelHHRhpqlFaMPoBtHCbm5MDIvAXUpXaM36ci2MQhSd LPrx8A231gN+TptJwol8N1oN7HDfolkv+nsnsrJOQVkCg0JlkxwkvvV/1RKHyg== DKIM-Signature: v=1; a=ed25519-sha256; c=relaxed/relaxed; d=linutronix.de; s=2020e; t=1740392131; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: references:references; bh=1NcwSQHUYGMReXSkzTA7ZP6MuBB2dzTz3GVp7qZIRZw=; b=Qmd9X/hC34kiEk69DiPfhmMKkcQE5Uo3IDXoaaZCUD9xJHcOFkc6IgXxLebYO6Mx+Swm6S jfvYMfhYPvRCO4Cg== From: Thomas Gleixner To: LKML Cc: Anna-Maria Behnsen , Frederic Weisbecker , Benjamin Segall , Eric Dumazet , Andrey Vagin , Pavel Tikhomirov , Peter Zijlstra Subject: [patch 05/11] posix-timers: Rework timer removal References: <20250224095736.145530367@linutronix.de> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Date: Mon, 24 Feb 2025 11:15:30 +0100 (CET) Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" sys_timer_delete() and the do_exit() cleanup function itimer_delete() are doing the same thing, but have needlessly different implementations instead of sharing the code. The other oddity of timer deletion is the fact that the timer is not invalidated before the actual deletion happens, which allows concurrent lookups to succeed. That's wrong because a timer which is in the process of being deleted should not be visible and any actions like signal queueing, delivery and rearming should not happen once the task, which invoked timer_delete(), has the timer locked. Rework the code so that: 1) The signal queueing and delivery code ignore timers which are marked invalid 2) The deletion implementation between sys_timer_delete() and itimer_delete() is shared 3) The timer is invalidated and removed from the linked lists before the deletion callback of the relevant clock is invoked. That requires to rework timer_wait_running() as it does a lookup of the timer when relocking it at the end. In case of deletion this lookup would fail due to the preceding invalidation and the wait loop would terminate prematurely. But due to the preceding invalidation the timer cannot be accessed by other tasks anymore, so there is no way that the timer has been freed after the timer lock has been dropped. Signed-off-by: Thomas Gleixner --- include/linux/posix-timers.h | 7 + kernel/signal.c | 2=20 kernel/time/posix-timers.c | 156 +++++++++++++++++++-------------------= ----- 3 files changed, 80 insertions(+), 85 deletions(-) --- a/include/linux/posix-timers.h +++ b/include/linux/posix-timers.h @@ -240,6 +240,13 @@ static inline void posixtimer_sigqueue_p =20 posixtimer_putref(tmr); } + +static inline bool posixtimer_valid(const struct k_itimer *timer) +{ + unsigned long val =3D (unsigned long)timer->it_signal; + + return !(val & 0x1UL); +} #else /* CONFIG_POSIX_TIMERS */ static inline void posixtimer_sigqueue_getref(struct sigqueue *q) { } static inline void posixtimer_sigqueue_putref(struct sigqueue *q) { } --- a/kernel/signal.c +++ b/kernel/signal.c @@ -2092,7 +2092,7 @@ static inline void posixtimer_sig_ignore * from a non-periodic timer, then just drop the reference * count. Otherwise queue it on the ignored list. */ - if (tmr->it_signal && tmr->it_sig_periodic) + if (posixtimer_valid(tmr) && tmr->it_sig_periodic) hlist_add_head(&tmr->ignored_list, &tsk->signal->ignored_posix_timers); else posixtimer_putref(tmr); --- a/kernel/time/posix-timers.c +++ b/kernel/time/posix-timers.c @@ -275,7 +275,7 @@ static bool __posixtimer_deliver_signal( * since the signal was queued. In either case, don't rearm and * drop the signal. */ - if (timr->it_signal_seq !=3D timr->it_sigqueue_seq || WARN_ON_ONCE(!timr-= >it_signal)) + if (timr->it_signal_seq !=3D timr->it_sigqueue_seq || !posixtimer_valid(t= imr)) return false; =20 if (!timr->it_interval || WARN_ON_ONCE(timr->it_status !=3D POSIX_TIMER_R= EQUEUE_PENDING)) @@ -320,6 +320,9 @@ void posix_timer_queue_signal(struct k_i { lockdep_assert_held(&timr->it_lock); =20 + if (!posixtimer_valid(timr)) + return; + timr->it_status =3D timr->it_interval ? POSIX_TIMER_REQUEUE_PENDING : POS= IX_TIMER_DISARMED; posixtimer_send_sigqueue(timr); } @@ -540,11 +543,11 @@ static struct k_itimer *__lock_timer(tim * The hash lookup and the timers are RCU protected. * * Timers are added to the hash in invalid state where - * timr::it_signal =3D=3D NULL. timer::it_signal is only set after the - * rest of the initialization succeeded. + * timr::it_signal is marked invalid. timer::it_signal is only set + * after the rest of the initialization succeeded. * * Timer destruction happens in steps: - * 1) Set timr::it_signal to NULL with timr::it_lock held + * 1) Set timr::it_signal marked invalid with timr::it_lock held * 2) Release timr::it_lock * 3) Remove from the hash under hash_lock * 4) Put the reference count. @@ -561,8 +564,8 @@ static struct k_itimer *__lock_timer(tim * * The lookup validates locklessly that timr::it_signal =3D=3D * current::it_signal and timr::it_id =3D=3D @timer_id. timr::it_id - * can't change, but timr::it_signal becomes NULL during - * destruction. + * can't change, but timr::it_signal can become invalid during + * destruction, which makes the locked check fail. */ rcu_read_lock(); timr =3D posix_timer_by_id(timer_id); @@ -809,8 +812,8 @@ static void common_timer_wait_running(st * when the task which tries to delete or disarm the timer has preempted * the task which runs the expiry in task work context. */ -static struct k_itimer *timer_wait_running(struct k_itimer *timer, - unsigned long *flags) +static struct k_itimer *timer_wait_running(struct k_itimer *timer, unsigne= d long *flags, + bool delete) { const struct k_clock *kc =3D READ_ONCE(timer->kclock); timer_t timer_id =3D READ_ONCE(timer->it_id); @@ -820,14 +823,32 @@ static struct k_itimer *timer_wait_runni spin_unlock_irqrestore(&timer->it_lock, *flags); =20 /* - * kc->timer_wait_running() might drop RCU lock. So @timer - * cannot be touched anymore after the function returns! + * kc->timer_wait_running() might drop RCU lock. So @timer cannot + * be touched anymore after the function returns, except when + * @delete is true! */ if (!WARN_ON_ONCE(!kc->timer_wait_running)) kc->timer_wait_running(timer); =20 rcu_read_unlock(); - /* Relock the timer. It might be not longer hashed. */ + + /* + * On deletion the timer has been marked invalid before + * timer_delete_hook() has been invoked. That means that the + * current task is the only one which has access to the timer and + * even after dropping timer::it_lock above, no other thread can + * have accessed the timer. + */ + if (delete) { + spin_lock_irqsave(&timer->it_lock, *flags); + return timer; + } + + /* + * If invoked from timer_set() the timer could have been deleted + * after dropping the lock. So in that case the timer needs to be + * looked up and validated. + */ return lock_timer(timer_id, flags); } =20 @@ -920,7 +941,7 @@ static int do_timer_settime(timer_t time // We already got the old time... old_spec64 =3D NULL; /* Unlocks and relocks the timer if it still exists */ - timr =3D timer_wait_running(timr, &flags); + timr =3D timer_wait_running(timr, &flags, false); goto retry; } spin_unlock_irqrestore(&timr->it_lock, flags); @@ -1008,95 +1029,62 @@ static inline int timer_delete_hook(stru return kc->timer_del(timer); } =20 -/* Delete a POSIX.1b interval timer. */ -SYSCALL_DEFINE1(timer_delete, timer_t, timer_id) +static int posix_timer_delete(struct k_itimer *timer, timer_t id) { - struct k_itimer *timer; unsigned long flags; =20 - timer =3D lock_timer(timer_id, &flags); - -retry_delete: - if (!timer) - return -EINVAL; - - if (unlikely(timer_delete_hook(timer) =3D=3D TIMER_RETRY)) { - /* Unlocks and relocks the timer if it still exists */ - timer =3D timer_wait_running(timer, &flags); - goto retry_delete; + if (!timer) { + timer =3D lock_timer(id, &flags); + if (!timer) + return -EINVAL; + } else { + spin_lock_irqsave(&timer->it_lock, flags); } =20 - spin_lock(¤t->sighand->siglock); - hlist_del(&timer->list); - posix_timer_cleanup_ignored(timer); /* - * A concurrent lookup could check timer::it_signal lockless. It - * will reevaluate with timer::it_lock held and observe the NULL. + * Invalidate the timer, remove it from the linked list and remove + * it from the ignored list if pending. * - * It must be written with siglock held so that the signal code - * observes timer->it_signal =3D=3D NULL in do_sigaction(SIG_IGN), + * The invalidation must be written with siglock held so that the + * signal code observes timer->it_valid =3D=3D false in do_sigaction(), * which prevents it from moving a pending signal of a deleted * timer to the ignore list. + * + * The invalidation also prevents signal queueing, signal delivery + * and therefore rearming from the signal delivery path. + * + * A concurrent lookup can still find the timer in the hash, but it + * will check timer::it_signal with timer::it_lock held and observe + * bit 0 set, which invalidates it. That also prevents the timer ID + * from being handed out before this timer is completely gone. */ - WRITE_ONCE(timer->it_signal, NULL); - spin_unlock(¤t->sighand->siglock); - - spin_unlock_irqrestore(&timer->it_lock, flags); - posix_timer_unhash_and_free(timer); - return 0; -} + scoped_guard(spinlock, ¤t->sighand->siglock) { + unsigned long sig =3D (unsigned long)timer->it_signal | 1UL; =20 -/* - * Delete a timer if it is armed, remove it from the hash and schedule it - * for RCU freeing. - */ -static void itimer_delete(struct k_itimer *timer) -{ - unsigned long flags; - - /* - * irqsave is required to make timer_wait_running() work. - */ - spin_lock_irqsave(&timer->it_lock, flags); + WRITE_ONCE(timer->it_signal, (struct signal_struct *)sig); + hlist_del(&timer->list); + posix_timer_cleanup_ignored(timer); + } =20 -retry_delete: - /* - * Even if the timer is not longer accessible from other tasks - * it still might be armed and queued in the underlying timer - * mechanism. Worse, that timer mechanism might run the expiry - * function concurrently. - */ - if (timer_delete_hook(timer) =3D=3D TIMER_RETRY) { + while (timer_delete_hook(timer) =3D=3D TIMER_RETRY) { /* - * Timer is expired concurrently, prevent livelocks - * and pointless spinning on RT. - * - * timer_wait_running() drops timer::it_lock, which opens - * the possibility for another task to delete the timer. - * - * That's not possible here because this is invoked from - * do_exit() only for the last thread of the thread group. - * So no other task can access and delete that timer. + * Unlocks and relocks the timer. There is no concurrent + * delete possible after unlocking the timer as the timer + * has been marked invalid above. */ - if (WARN_ON_ONCE(timer_wait_running(timer, &flags) !=3D timer)) - return; - - goto retry_delete; + timer_wait_running(timer, &flags, true); } - hlist_del(&timer->list); - - posix_timer_cleanup_ignored(timer); - - /* - * Setting timer::it_signal to NULL is technically not required - * here as nothing can access the timer anymore legitimately via - * the hash table. Set it to NULL nevertheless so that all deletion - * paths are consistent. - */ - WRITE_ONCE(timer->it_signal, NULL); =20 spin_unlock_irqrestore(&timer->it_lock, flags); + /* Remove it from the hash, which frees up the timer ID */ posix_timer_unhash_and_free(timer); + return 0; +} + +/* Delete a POSIX.1b interval timer. */ +SYSCALL_DEFINE1(timer_delete, timer_t, timer_id) +{ + return posix_timer_delete(NULL, timer_id); } =20 /* @@ -1118,7 +1106,7 @@ void exit_itimers(struct task_struct *ts =20 /* The timers are not longer accessible via tsk::signal */ while (!hlist_empty(&timers)) { - itimer_delete(hlist_entry(timers.first, struct k_itimer, list)); + posix_timer_delete(hlist_entry(timers.first, struct k_itimer, list), 0); cond_resched(); } From nobody Sat Feb 7 22:07:55 2026 Received: from galois.linutronix.de (Galois.linutronix.de [193.142.43.55]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 2DCEA253B57 for ; Mon, 24 Feb 2025 10:15:34 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=193.142.43.55 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740392135; cv=none; b=kz8qFEf1N4FOJ6peBgt6OgMlbsrAdxtUNevcAXLgdxchEqe4OHU0wBOoHQTubaG+72wP7VvHC94Q0EBAc5PCjFW3Wwp74N5dre+niEp7ggflHIVuu9MVHprayk955k+iJRReW6UHuCDKtC0Czle4/U4sK+35Rn8HDtbCy7s7p8Y= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740392135; c=relaxed/simple; bh=2XGHKppiI14EJmvbu8OZVXUe2XVlMI1v2uj+6/Gxu3w=; h=Message-ID:From:To:Cc:Subject:References:MIME-Version: Content-Type:Date; b=iqnyzBxuoEzYfnJprNXs0wAvrsufW+Kk/Nk1okPQHWE8Xo5tkfRRZGfQba8HZCflgXdfBvfQwA+C2R7/JeVT6RyjcGZQq/8FImoJhfe3zAyTE0zUFVK5CgYijtGuC7uuRjctA3xr71X/Q9OrAWLSQHCZd/K5zuJ9joLRWMlwy5A= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linutronix.de; spf=pass smtp.mailfrom=linutronix.de; dkim=pass (2048-bit key) header.d=linutronix.de header.i=@linutronix.de header.b=0oFNtqPi; dkim=permerror (0-bit key) header.d=linutronix.de header.i=@linutronix.de header.b=l9qoHdHP; arc=none smtp.client-ip=193.142.43.55 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linutronix.de Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linutronix.de Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linutronix.de header.i=@linutronix.de header.b="0oFNtqPi"; dkim=permerror (0-bit key) header.d=linutronix.de header.i=@linutronix.de header.b="l9qoHdHP" Message-ID: <20250224101343.344168498@linutronix.de> DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linutronix.de; s=2020; t=1740392132; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: references:references; bh=5b26gUKwIOtDz/nxYP1M5mOx9KSbpQ2cUpKA7MwXFdw=; b=0oFNtqPiWrJfXkzLzFer+vNpG7QHObJPkbCnu22EwHJDX+tQ04huuoynuPkKIVRHh7mHjH ZRCFC9DU6YJO7NsjtPggE8sVRSyjOBPWhfIYMsDE3kUz2nF3l6F5bDUAF4oQhrCgJXjOgH 8M6vwbWGYmVH+lYCSz+UC19Hv8ULon/L3GUY79os8MUx8kF2PRjD/J7/hce4eaSLIvlNE8 zKUXVvSSUfYq9LlcF8+LkHmvQXQJgu3IpIapCyiAtEnFn5N413P4NOYt04R0jFUtro7NdN ZgV0HSjLiG09ig5hR5Q3dPw1skkzvbiPgHx0dOltsdsO4yQUjwEu+9yusSv91A== DKIM-Signature: v=1; a=ed25519-sha256; c=relaxed/relaxed; d=linutronix.de; s=2020e; t=1740392132; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: references:references; bh=5b26gUKwIOtDz/nxYP1M5mOx9KSbpQ2cUpKA7MwXFdw=; b=l9qoHdHPiAd5PoyR2eGIEnUnYgekwbfNYFUpwyL8HBhonzbXcsRpIP5OjzgRMU78/71i3d 8aZTnI51o1h+7JBw== From: Thomas Gleixner To: LKML Cc: Anna-Maria Behnsen , Frederic Weisbecker , Benjamin Segall , Eric Dumazet , Andrey Vagin , Pavel Tikhomirov , Peter Zijlstra Subject: [patch 06/11] posix-timers: Make signal_struct::next_posix_timer_id an atomic_t References: <20250224095736.145530367@linutronix.de> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Date: Mon, 24 Feb 2025 11:15:32 +0100 (CET) Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" From: Eric Dumazet The global hash_lock protecting the posix timer hash table can be heavily contended especially when there is an extensive linear search for a timer ID. Timer IDs are handed out by monotonically increasing next_posix_timer_id and then validating that there is no timer with the same ID in the hash table. Both operations happen with the global hash lock held. To reduce the hash lock contention the hash will be reworked to a scaled hash with per bucket locks, which requires to handle the ID counter lockless. Prepare for this by making next_posix_timer_id an atomic_t, which can be used lockless with atomic_inc_return(). [ tglx: Adopted from Eric's series, massaged change log and simplified it ] Signed-off-by: Eric Dumazet Signed-off-by: Thomas Gleixner Link: https://lore.kernel.org/all/20250219125522.2535263-2-edumazet@google.= com --- include/linux/sched/signal.h | 2 +- kernel/time/posix-timers.c | 14 +++++--------- 2 files changed, 6 insertions(+), 10 deletions(-) --- a/include/linux/sched/signal.h +++ b/include/linux/sched/signal.h @@ -136,7 +136,7 @@ struct signal_struct { #ifdef CONFIG_POSIX_TIMERS =20 /* POSIX.1b Interval Timers */ - unsigned int next_posix_timer_id; + atomic_t next_posix_timer_id; struct hlist_head posix_timers; struct hlist_head ignored_posix_timers; =20 --- a/kernel/time/posix-timers.c +++ b/kernel/time/posix-timers.c @@ -105,21 +105,17 @@ static bool posix_timer_hashed(struct hl static int posix_timer_add(struct k_itimer *timer) { struct signal_struct *sig =3D current->signal; - struct hlist_head *head; - unsigned int cnt, id; =20 /* * FIXME: Replace this by a per signal struct xarray once there is * a plan to handle the resulting CRIU regression gracefully. */ - for (cnt =3D 0; cnt <=3D INT_MAX; cnt++) { - spin_lock(&hash_lock); - id =3D sig->next_posix_timer_id; - - /* Write the next ID back. Clamp it to the positive space */ - sig->next_posix_timer_id =3D (id + 1) & INT_MAX; + for (unsigned int cnt =3D 0; cnt <=3D INT_MAX; cnt++) { + /* Get the next timer ID and clamp it to positive space */ + unsigned int id =3D (atomic_inc_return(&sig->next_posix_timer_id) - 1) &= INT_MAX; + struct hlist_head *head =3D &posix_timers_hashtable[hash(sig, id)]; =20 - head =3D &posix_timers_hashtable[hash(sig, id)]; + spin_lock(&hash_lock); if (!posix_timer_hashed(head, sig, id)) { /* * Set the timer ID and the signal pointer to make From nobody Sat Feb 7 22:07:55 2026 Received: from galois.linutronix.de (Galois.linutronix.de [193.142.43.55]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 26EA6253F37 for ; Mon, 24 Feb 2025 10:15:35 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=193.142.43.55 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740392138; cv=none; b=cjxBWL8BvJXE0ue5XVNEDQ7Xl4ZeeB2RPqNG70OtKnfUupUALv598P419XPJnHzdL9OQMsLpE7Vn0ZwUEnJSZR3DX8NZNXawoUrWijGS1fg/mdXYbjKtfBA8CdTAGPPrgaB18RitmurISsmldgAXdS3Icq0MYSvTsKANWUa4daY= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740392138; c=relaxed/simple; bh=/4NjpeCdAWUpCFrAtqNBXVrIQ+zOZYg+DCrp4786Rxk=; h=Message-ID:From:To:Cc:Subject:References:MIME-Version: Content-Type:Date; b=AJ8TC9UsRGi6VlQEFyLaTX4CCupoSS8YmmtFqx2xHhcG5aC2R/wVyVEsKtnb0ZXAaXLyV3by37Kkpdq6haXbzOcLIIIAlyuk/9ERwqJY5nJEPK4IJSIV5lsdtDjqjP08kKm1hktv4IR1y1UudVrzkX0XZ6zT+Zbpz00K70dBxQ0= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linutronix.de; spf=pass smtp.mailfrom=linutronix.de; dkim=pass (2048-bit key) header.d=linutronix.de header.i=@linutronix.de header.b=Bhp9f0Nx; dkim=permerror (0-bit key) header.d=linutronix.de header.i=@linutronix.de header.b=a/RDzYeK; arc=none smtp.client-ip=193.142.43.55 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linutronix.de Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linutronix.de Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linutronix.de header.i=@linutronix.de header.b="Bhp9f0Nx"; dkim=permerror (0-bit key) header.d=linutronix.de header.i=@linutronix.de header.b="a/RDzYeK" Message-ID: <20250224101343.410413967@linutronix.de> DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linutronix.de; s=2020; t=1740392134; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: references:references; bh=5DEumkcfOiCiC9+0uSiJuG2GsO94gV682DPkool2oDw=; b=Bhp9f0NxnB9K2+YGRu6a75Cf0171wqnd2+43WQg7M3gdhiL69L7XDvGivoGR3MtPymvlEH J4OnYjd0OJKJvgNnW1Xg6q7AvJZ7rC7QX3SCrbgupTCR+dSDJlyx4Ij+sGciorRe/WToBN JTtbS5pAfKL6WMAypB0Ob5DasCFsFdeqejajY6LoWxseFLWgo15iWqQ6jlZ9rGUob4V6ln ht46frbI7PGQAYUzKx1T3il7/6XuQ9xMf1PzkvH3EdUa9jol6VxVG9zJps5Snsf56n8QWn vPh7V7NpcpVmP/H2EEsXANGmHMPNHTVPIEHjVdV9iQOGTTNDJlAMIR/kKCX8kw== DKIM-Signature: v=1; a=ed25519-sha256; c=relaxed/relaxed; d=linutronix.de; s=2020e; t=1740392134; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: references:references; bh=5DEumkcfOiCiC9+0uSiJuG2GsO94gV682DPkool2oDw=; b=a/RDzYeKqWY+LcFuoguYdA6cLNulOB+t0eEX30h6+TgKjtjTYYrw0bV2mA/OqicQ05xGJ4 Q290LH//ExkizfCw== From: Thomas Gleixner To: LKML Cc: Anna-Maria Behnsen , Frederic Weisbecker , Benjamin Segall , Eric Dumazet , Andrey Vagin , Pavel Tikhomirov , Peter Zijlstra Subject: [patch 07/11] posix-timers: Improve hash table performance References: <20250224095736.145530367@linutronix.de> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Date: Mon, 24 Feb 2025 11:15:33 +0100 (CET) Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Eric and Ben reported a significant performance bottleneck on the global hash, which is used to store posix timers for lookup. Eric tried to do a lockless validation of a new timer ID before trying to insert the timer, but that does not solve the problem. For the non-contended case this is a pointless exercise and for the contended case this extra lookup just creates enough interleaving that all tasks can make progress. There are actually two real solutions to the problem: 1) Provide a per process (signal struct) xarray storage 2) Implement a smarter hash like the one in the futex code #1 works perfectly fine for most cases, but the fact that CRIU enforced a linear increasing timer ID to restore timers makes this problematic. It's easy enough to create a sparse timer ID space, which amounts very fast to a large junk of memory consumed for the xarray. 2048 timers with a ID offset of 512 consume more than one megabyte of memory for the xarray storage. #2 The main advantage of the futex hash is that it uses per hash bucket locks instead of a global hash lock. Aside of that it is scaled according to the number of CPUs at boot time. Experiments with artifical benchmarks have shown that a scaled hash with per bucket locks comes pretty close to the xarray performance and in some scenarios it performes better. Test 1: A single process creates 20000 timers and afterwards invokes timer_getoverrun(2) on each of them: mainline Eric newhash xarray create 23 ms 23 ms 9 ms 8 ms getoverrun 14 ms 14 ms 5 ms 4 ms Test 2: A single process creates 50000 timers and afterwards invokes timer_getoverrun(2) on each of them: mainline Eric newhash xarray create 98 ms 219 ms 20 ms 18 ms getoverrun 62 ms 62 ms 10 ms 9 ms Test 3: A single process creates 100000 timers and afterwards invokes timer_getoverrun(2) on each of them: mainline Eric newhash xarray create 313 ms 750 ms 48 ms 33 ms getoverrun 261 ms 260 ms 20 ms 14 ms Erics changes create quite some overhead in the create() path due to the double list walk, as the main issue according to perf is the list walk itself. With 100k timers each hash bucket contains ~200 timers, which in the worst case need to be all inspected. The same problem applies for getoverrun() where the lookup has to walk through the hash buckets to find the timer it is looking for. The scaled hash obviously reduces hash collisions and lock contention significantly. This becomes more prominent with concurrency. Test 4: A process creates 63 threads and all threads wait on a barrier before each instance creates 20000 timers and afterwards invokes timer_getoverrun(2) on each of them. The threads are pinned on seperate CPUs to achive maximum concurrency. The numbers are the average times per thread: mainline Eric newhash xarray create 180239 ms 38599 ms 579 ms 813 ms getoverrun 2645 ms 2642 ms 32 ms 7 ms Test 5: A process forks 63 times and all forks wait on a barrier before each instance creates 20000 timers and afterwards invokes timer_getoverrun(2) on each of them. The processes are pinned on seperate CPUs to achive maximum concurrency. The numbers are the average times per process: mainline eric newhash xarray create 157253 ms 40008 ms 83 ms 60 ms getoverrun 2611 ms 2614 ms 40 ms 4 ms So clearly the reduction of lock contention with Eric's changes makes a significant difference for the create() loop, but it does not mitigate the problem of long list walks, which is clearly visible on the getoverrun() side because that is purely dominated by the lookup itself. Once the timer is found, the syscall just reads from the timer structure with no other locks or code paths involved and returns. The reason for the difference between the thread and the fork case for the new hash and the xarray is that both suffer from contention on sighand::siglock and the xarray suffers additionally from contention on the xarray lock on insertion. The only case where the reworked hash slighly outperforms the xarray is a tight loop which creates and deletes timers. Test 4: A process creates 63 threads and all threads wait on a barrier before each instance runs a loop which creates and deletes a timer 100000 times in a row. The threads are pinned on seperate CPUs to achive maximum concurrency. The numbers are the average times per thread: mainline Eric newhash xarray loop 5917 ms 5897 ms 5473 ms 7846 ms Test 5: A process forks 63 times and all forks wait on a barrier before each each instance runs a loop which creates and deletes a timer 100000 times in a row. The processes are pinned on seperate CPUs to achive maximum concurrency. The numbers are the average times per process: mainline Eric newhash xarray loop 5137 ms 7828 ms 891 ms 872 ms In both test there is not much contention on the hash, but the ucount accounting for the signal and in the thread case the sighand::siglock contention (plus the xarray locking) contribute dominantly to the overhead. As the memory consumption of the xarray in the sparse ID case is significant, the scaled hash with per bucket locks seems to be the better overall option. While the xarray has faster lookup times for a large number of timers, the actual syscall usage, which requires the lookup is not an extreme hotpath. Most applications utilize signal delivery and all syscalls except timer_getoverrun(2) are all but cheap. So implement a scaled hash with per bucket locks, which offers the best tradeoff between performance and memory consumption. Signed-off-by: Thomas Gleixner --- kernel/time/posix-timers.c | 101 ++++++++++++++++++++++++++++++----------= ----- 1 file changed, 69 insertions(+), 32 deletions(-) --- a/kernel/time/posix-timers.c +++ b/kernel/time/posix-timers.c @@ -12,10 +12,10 @@ #include #include #include -#include #include #include #include +#include #include #include #include @@ -40,8 +40,18 @@ static struct kmem_cache *posix_timers_c * This allows checkpoint/restore to reconstruct the exact timer IDs for * a process. */ -static DEFINE_HASHTABLE(posix_timers_hashtable, 9); -static DEFINE_SPINLOCK(hash_lock); +struct timer_hash_bucket { + spinlock_t lock; + struct hlist_head head; +}; + +static struct { + struct timer_hash_bucket *buckets; + unsigned long bits; +} __timer_data __ro_after_init __aligned(2*sizeof(long)); + +#define timer_buckets (__timer_data.buckets) +#define timer_hashbits (__timer_data.bits) =20 static const struct k_clock * const posix_clocks[]; static const struct k_clock *clockid_to_kclock(const clockid_t id); @@ -63,16 +73,16 @@ static struct k_itimer *__lock_timer(tim =20 static int hash(struct signal_struct *sig, unsigned int nr) { - return hash_32(hash32_ptr(sig) ^ nr, HASH_BITS(posix_timers_hashtable)); + return hash_32(hash32_ptr(sig) ^ nr, timer_hashbits); } =20 static struct k_itimer *posix_timer_by_id(timer_t id) { struct signal_struct *sig =3D current->signal; - struct hlist_head *head =3D &posix_timers_hashtable[hash(sig, id)]; + struct timer_hash_bucket *bucket =3D &timer_buckets[hash(sig, id)]; struct k_itimer *timer; =20 - hlist_for_each_entry_rcu(timer, head, t_hash) { + hlist_for_each_entry_rcu(timer, &bucket->head, t_hash) { /* timer->it_signal can be set concurrently */ if ((READ_ONCE(timer->it_signal) =3D=3D sig) && (timer->it_id =3D=3D id)) return timer; @@ -91,11 +101,13 @@ static inline struct signal_struct *posi return (struct signal_struct *)(val & ~1UL); } =20 -static bool posix_timer_hashed(struct hlist_head *head, struct signal_stru= ct *sig, timer_t id) +static bool posix_timer_hashed(struct timer_hash_bucket *bucket, struct si= gnal_struct *sig, + timer_t id) { + struct hlist_head *head =3D &bucket->head; struct k_itimer *timer; =20 - hlist_for_each_entry_rcu(timer, head, t_hash, lockdep_is_held(&hash_lock)= ) { + hlist_for_each_entry_rcu(timer, head, t_hash, lockdep_is_held(&bucket->lo= ck)) { if ((posix_sig_owner(timer) =3D=3D sig) && (timer->it_id =3D=3D id)) return true; } @@ -106,34 +118,34 @@ static int posix_timer_add(struct k_itim { struct signal_struct *sig =3D current->signal; =20 - /* - * FIXME: Replace this by a per signal struct xarray once there is - * a plan to handle the resulting CRIU regression gracefully. - */ for (unsigned int cnt =3D 0; cnt <=3D INT_MAX; cnt++) { /* Get the next timer ID and clamp it to positive space */ unsigned int id =3D (atomic_inc_return(&sig->next_posix_timer_id) - 1) &= INT_MAX; - struct hlist_head *head =3D &posix_timers_hashtable[hash(sig, id)]; + struct timer_hash_bucket *bucket =3D &timer_buckets[hash(sig, id)]; =20 - spin_lock(&hash_lock); - if (!posix_timer_hashed(head, sig, id)) { + scoped_guard (spinlock, &bucket->lock) { /* - * Set the timer ID and the signal pointer to make - * it identifiable in the hash table. The signal - * pointer has bit 0 set to indicate that it is not - * yet fully initialized. posix_timer_hashed() - * masks this bit out, but the syscall lookup fails - * to match due to it being set. This guarantees - * that there can't be duplicate timer IDs handed - * out. + * Validate under the lock as this could have raced + * against another thread ending up with the same + * ID, which is highly unlikely, but possible. */ - timer->it_id =3D (timer_t)id; - timer->it_signal =3D (struct signal_struct *)((unsigned long)sig | 1UL); - hlist_add_head_rcu(&timer->t_hash, head); - spin_unlock(&hash_lock); - return id; + if (!posix_timer_hashed(bucket, sig, id)) { + /* + * Set the timer ID and the signal pointer to make + * it identifiable in the hash table. The signal + * pointer has bit 0 set to indicate that it is not + * yet fully initialized. posix_timer_hashed() + * masks this bit out, but the syscall lookup fails + * to match due to it being set. This guarantees + * that there can't be duplicate timer IDs handed + * out. + */ + timer->it_id =3D (timer_t)id; + timer->it_signal =3D (struct signal_struct *)((unsigned long)sig | 1UL= ); + hlist_add_head_rcu(&timer->t_hash, &bucket->head); + return id; + } } - spin_unlock(&hash_lock); cond_resched(); } /* POSIX return code when no timer ID could be allocated */ @@ -388,9 +400,11 @@ void posixtimer_free_timer(struct k_itim =20 static void posix_timer_unhash_and_free(struct k_itimer *tmr) { - spin_lock(&hash_lock); - hlist_del_rcu(&tmr->t_hash); - spin_unlock(&hash_lock); + unsigned int idx =3D hash(posix_sig_owner(tmr), tmr->it_id); + struct timer_hash_bucket *bucket =3D &timer_buckets[idx]; + + scoped_guard (spinlock, &bucket->lock) + hlist_del_rcu(&tmr->t_hash); posixtimer_putref(tmr); } =20 @@ -1549,3 +1563,26 @@ static const struct k_clock *clockid_to_ =20 return posix_clocks[array_index_nospec(idx, ARRAY_SIZE(posix_clocks))]; } + +static int __init posixtimer_init(void) +{ + unsigned long i, size; + unsigned int shift; + + if (IS_ENABLED(CONFIG_BASE_SMALL)) + size =3D 512; + else + size =3D roundup_pow_of_two(512 * num_possible_cpus()); + + timer_buckets =3D alloc_large_system_hash("posixtimers", sizeof(*timer_bu= ckets), + size, 0, 0, &shift, NULL, size, size); + size =3D 1UL << shift; + timer_hashbits =3D ilog2(size); + + for (i =3D 0; i < size; i++) { + spin_lock_init(&timer_buckets[i].lock); + INIT_HLIST_HEAD(&timer_buckets[i].head); + } + return 0; +} +core_initcall(posixtimer_init); From nobody Sat Feb 7 22:07:55 2026 Received: from galois.linutronix.de (Galois.linutronix.de [193.142.43.55]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 5EF6D254B18 for ; Mon, 24 Feb 2025 10:15:37 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=193.142.43.55 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740392138; cv=none; b=BEqyIunFbFR4eVtCQt5YryqLLiG/5DolbaQSQuyPyyH3nlGIICjIJcyJH7F9ghurK7jFzwoN0h6OTbOgkjGw7Tt71KA8qzlzMjj/c0n5QlAUw2+ElpRPd3LKmdnuMiDkkTOqpTrTcsAxx/S+Rf+mcdQhkvNJmHiy0JOFzXTkT9o= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740392138; c=relaxed/simple; bh=z2LcqZOrO+c2z55Y2Ou512MgbA+rp3d9GPeexhEBsYM=; h=Message-ID:From:To:Cc:Subject:References:MIME-Version: Content-Type:Date; b=LfPxNfIFp5/r6fbAsRxfWe+MTm2AXlLaQ+AG6kgVqlgIyD7uPrCKY10+0WBfiK/79BJgUKQRK6DsFKSISrAZGJxqJp+vtxTEmMmoLw7oC/PPxl0v8qIxj1w0E1B1ATjLbhATo1eQ01mkCoNpQIOtpTPM/wa8Xm4/efcZiA1kgXs= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linutronix.de; spf=pass smtp.mailfrom=linutronix.de; dkim=pass (2048-bit key) header.d=linutronix.de header.i=@linutronix.de header.b=CCVKzGbW; dkim=permerror (0-bit key) header.d=linutronix.de header.i=@linutronix.de header.b=Y4PtCWUJ; arc=none smtp.client-ip=193.142.43.55 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linutronix.de Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linutronix.de Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linutronix.de header.i=@linutronix.de header.b="CCVKzGbW"; dkim=permerror (0-bit key) header.d=linutronix.de header.i=@linutronix.de header.b="Y4PtCWUJ" Message-ID: <20250224101343.476200215@linutronix.de> DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linutronix.de; s=2020; t=1740392136; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: references:references; bh=TgnqdEMmZ/WqLTYhEIxPYDCSyTBkXav7b/iu1bARJec=; b=CCVKzGbWMXJ7ILTK2K4HmV8q4LRuBWCnJWNP3rJt9G2XXnTHScbXfnHgIVpFeIFvIFTU37 7QZ9iyLEfv1iBzq6WapCNlN3Owwif/i32YRg64uPJYLrQeYerDIRMLaEomrP5ukQpX0IDz JRUlMJ8ekAuOrLMCPqbirZvJ6aeRrATnOw4NJmK8VJaULV2NDv8OQMdm33MSl5YKE34WgV JiXx+CYpZVTBGs/jcU0HbbwG5e341/3xAtbr+OCIsC4cRQlci7n0enjNYFu6QPpkRDMfG5 UoQsH30nHJdVfUSl2Spx5yiJrVx/eMDdGGohRxrBkVZ+EGUswkH/H0EgxyCSlQ== DKIM-Signature: v=1; a=ed25519-sha256; c=relaxed/relaxed; d=linutronix.de; s=2020e; t=1740392136; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: references:references; bh=TgnqdEMmZ/WqLTYhEIxPYDCSyTBkXav7b/iu1bARJec=; b=Y4PtCWUJAmEUOU5lxznK9LTtRCp1n0dTguuqAl/Nf0Stk1pusSu2OABnYozJx+lu57sqpc N67ZQ2hErpUdM3BQ== From: Thomas Gleixner To: LKML Cc: Anna-Maria Behnsen , Frederic Weisbecker , Benjamin Segall , Eric Dumazet , Andrey Vagin , Pavel Tikhomirov , Peter Zijlstra Subject: [patch 08/11] posix-timers: Make per process list RCU safe References: <20250224095736.145530367@linutronix.de> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Date: Mon, 24 Feb 2025 11:15:35 +0100 (CET) Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Preparatory change to remove the sighand locking from the /proc/$PID/timers iterator. Signed-off-by: Thomas Gleixner --- kernel/time/posix-timers.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) --- a/kernel/time/posix-timers.c +++ b/kernel/time/posix-timers.c @@ -496,7 +496,7 @@ static int do_timer_create(clockid_t whi * unmodified signal pointer to make it valid. */ WRITE_ONCE(new_timer->it_signal, current->signal); - hlist_add_head(&new_timer->list, ¤t->signal->posix_timers); + hlist_add_head_rcu(&new_timer->list, ¤t->signal->posix_timers); spin_unlock_irq(¤t->sighand->siglock); /* * After unlocking sighand::siglock @new_timer is subject to @@ -1072,7 +1072,7 @@ static int posix_timer_delete(struct k_i unsigned long sig =3D (unsigned long)timer->it_signal | 1UL; =20 WRITE_ONCE(timer->it_signal, (struct signal_struct *)sig); - hlist_del(&timer->list); + hlist_del_rcu(&timer->list); posix_timer_cleanup_ignored(timer); } From nobody Sat Feb 7 22:07:55 2026 Received: from galois.linutronix.de (Galois.linutronix.de [193.142.43.55]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id CEF18255E52 for ; Mon, 24 Feb 2025 10:15:39 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=193.142.43.55 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740392141; cv=none; b=BYLxwwUY3kpUVu9ziPBh+YJfLsiQybulI+/n7pGs04zkcTJmIe9Lv3KY1NiV70r9eEvXMLAFu/7w86yFdgOrU/E3WlL8YJ6Q6xTbAA+b3djuGvDiksJfzdt3EkjVYan+t0R1lWPdfjvb4+yzgpNCqoU8nJKao9NIe04BLI+qkdY= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740392141; c=relaxed/simple; bh=b6vqBPM7oLI2qCBwGwNXQIwjFm8LdkYmoY7Tiawwdms=; h=Message-ID:From:To:Cc:Subject:References:MIME-Version: Content-Type:Date; b=FoPw1DDLGT9GdJkQzKJv7fmiEi9GUATmZuUAmtWZ0tVF6KQHRuklkILGXUmgoHB54XxgtbjUQ8r3cThIVwM3KtL+Vts+baa5T15vsfkAiSFhRNQjFIv0BsxHTVDJHw3nWYGg1UpEuaJBqxoVI7wkMWU6lGai9Dlm1UmBM4NUsaY= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linutronix.de; spf=pass smtp.mailfrom=linutronix.de; dkim=pass (2048-bit key) header.d=linutronix.de header.i=@linutronix.de header.b=SWAD0CZy; dkim=permerror (0-bit key) header.d=linutronix.de header.i=@linutronix.de header.b=zfJJGlTN; arc=none smtp.client-ip=193.142.43.55 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linutronix.de Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linutronix.de Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linutronix.de header.i=@linutronix.de header.b="SWAD0CZy"; dkim=permerror (0-bit key) header.d=linutronix.de header.i=@linutronix.de header.b="zfJJGlTN" Message-ID: <20250224101343.541884406@linutronix.de> DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linutronix.de; s=2020; t=1740392138; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: references:references; bh=4tV1GUgLnAdVEwIWzNrAxUrIbNAIQLE9mDU8jfmrq7Y=; b=SWAD0CZyKv9UieAnP6IEcWpU294e9IV3rUnj8VoZdOu+p8tvKh9yipOv1Lgi+J8Pn1gjtJ BVoWVCrg0xpRmQoxcm/geEGoRWOZVyW2X+o4BEdmDbOVOF5YGxzRVrQ/I0WyTp7NAnGPKg snApigB7Z9lwOqg2jmJRvDHM/Vu9Y+tWutFiJSUP7yyTnm/pralOzOxmgwfqi0Qs+ONhQo IrXk3gMnW4o74C6L1g2CBYHl1RbK8Ip0tzQlKq0wptwKDL33MuAo9rpTs7BmXesW8g8jyX oDDGxzMl5e0zXIh9NGTl/xCOEPU1wOqmpuDyvQCYMayn5BMok58pRi5q+oJwCg== DKIM-Signature: v=1; a=ed25519-sha256; c=relaxed/relaxed; d=linutronix.de; s=2020e; t=1740392138; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: references:references; bh=4tV1GUgLnAdVEwIWzNrAxUrIbNAIQLE9mDU8jfmrq7Y=; b=zfJJGlTNsjEs5u2Bl5mHyff7rHizl58DkkzUt/VOfW/72BD34Hcw+4FqZwJvbK0dEQqq9K MxzeQAUQyG5RHCBQ== From: Thomas Gleixner To: LKML Cc: Anna-Maria Behnsen , Frederic Weisbecker , Benjamin Segall , Eric Dumazet , Andrey Vagin , Pavel Tikhomirov , Peter Zijlstra Subject: [patch 09/11] posix-timers: Dont iterate /proc/$PID/timers with sighand::siglock held References: <20250224095736.145530367@linutronix.de> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Date: Mon, 24 Feb 2025 11:15:37 +0100 (CET) Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" The readout of /proc/$PID/timers holds sighand::siglock with interrupts disabled. That is required to protect against concurrent modifications of the task::signal::posix_timers list because the list is not RCU safe. With the conversion of the timer storage to RCU protected hlist, this is not longer required. The only requirement is to protect the returned entry against a concurrent free, which is trivial as the timers are RCU protected. Removing the trylock of sighand::siglock is benign because the life time of task_struct::signal is bound to the life time of the task_struct itself. There are two scenarios where this matters: 1) The process is life and not about to be checkpointed 2) The process is stopped via ptrace for checkpointing #1 is a racy snapshot of the armed timers and nothing can rely on it. It's not more than debug information and it has been that way before because sighand lock is dropped when the buffer is full and the restart of the iteration might find a completely different set of timers. The task and therefore task::signal cannot be freed as timers_start() acquired a reference count via get_pid_task(). #2 the process is stopped for checkpointing so nothing can delete or create timers at this point. Neither can the process exit during the traversal. If CRIU fails to observe an exit in progress prior to the dissimination of the timers, then there are more severe problems to solve in the CRIU mechanics as they can't rely on posix timers being enabled in the first place. Therefore replace the lock acquisition with rcu_read_lock() and switch the timer storage traversal over to seq_hlist_*_rcu(). Signed-off-by: Thomas Gleixner --- fs/proc/base.c | 48 ++++++++++++++++++++---------------------------- 1 file changed, 20 insertions(+), 28 deletions(-) --- a/fs/proc/base.c +++ b/fs/proc/base.c @@ -2497,11 +2497,9 @@ static const struct file_operations proc =20 #if defined(CONFIG_CHECKPOINT_RESTORE) && defined(CONFIG_POSIX_TIMERS) struct timers_private { - struct pid *pid; - struct task_struct *task; - struct sighand_struct *sighand; - struct pid_namespace *ns; - unsigned long flags; + struct pid *pid; + struct task_struct *task; + struct pid_namespace *ns; }; =20 static void *timers_start(struct seq_file *m, loff_t *pos) @@ -2512,54 +2510,48 @@ static void *timers_start(struct seq_fil if (!tp->task) return ERR_PTR(-ESRCH); =20 - tp->sighand =3D lock_task_sighand(tp->task, &tp->flags); - if (!tp->sighand) - return ERR_PTR(-ESRCH); - - return seq_hlist_start(&tp->task->signal->posix_timers, *pos); + rcu_read_lock(); + return seq_hlist_start_rcu(&tp->task->signal->posix_timers, *pos); } =20 static void *timers_next(struct seq_file *m, void *v, loff_t *pos) { struct timers_private *tp =3D m->private; - return seq_hlist_next(v, &tp->task->signal->posix_timers, pos); + + return seq_hlist_next_rcu(v, &tp->task->signal->posix_timers, pos); } =20 static void timers_stop(struct seq_file *m, void *v) { struct timers_private *tp =3D m->private; =20 - if (tp->sighand) { - unlock_task_sighand(tp->task, &tp->flags); - tp->sighand =3D NULL; - } - if (tp->task) { put_task_struct(tp->task); tp->task =3D NULL; + rcu_read_unlock(); } } =20 static int show_timer(struct seq_file *m, void *v) { - struct k_itimer *timer; - struct timers_private *tp =3D m->private; - int notify; static const char * const nstr[] =3D { - [SIGEV_SIGNAL] =3D "signal", - [SIGEV_NONE] =3D "none", - [SIGEV_THREAD] =3D "thread", + [SIGEV_SIGNAL] =3D "signal", + [SIGEV_NONE] =3D "none", + [SIGEV_THREAD] =3D "thread", }; =20 - timer =3D hlist_entry((struct hlist_node *)v, struct k_itimer, list); - notify =3D timer->it_sigev_notify; + struct k_itimer *timer =3D hlist_entry((struct hlist_node *)v, struct k_i= timer, list); + struct timers_private *tp =3D m->private; + int notify =3D timer->it_sigev_notify; + + guard(spinlock_irq)(&timer->it_lock); + if (!posixtimer_valid(timer)) + return 0; =20 seq_printf(m, "ID: %d\n", timer->it_id); - seq_printf(m, "signal: %d/%px\n", - timer->sigq.info.si_signo, + seq_printf(m, "signal: %d/%px\n", timer->sigq.info.si_signo, timer->sigq.info.si_value.sival_ptr); - seq_printf(m, "notify: %s/%s.%d\n", - nstr[notify & ~SIGEV_THREAD_ID], + seq_printf(m, "notify: %s/%s.%d\n", nstr[notify & ~SIGEV_THREAD_ID], (notify & SIGEV_THREAD_ID) ? "tid" : "pid", pid_nr_ns(timer->it_pid, tp->ns)); seq_printf(m, "ClockID: %d\n", timer->it_clock); From nobody Sat Feb 7 22:07:55 2026 Received: from galois.linutronix.de (Galois.linutronix.de [193.142.43.55]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 43C252566C6 for ; Mon, 24 Feb 2025 10:15:41 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=193.142.43.55 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740392143; cv=none; b=MSP6hTvrkIoPBi8QcdkQObd2Wd4e5vaUsWNMNVf3Qy6nkTag9QrLckeFGqaQ94Sn+42q8wV9mt002ciYbGGSbo/neoa/wukQhS6XB1nXQmpNQ9+z7tfCaObdEv/Dnbc5+bNIMSfKuNDCSOLDIjciAm3dMYzi2xusqQNpf8kVA6g= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740392143; c=relaxed/simple; bh=tFZKLBufjlSPa2QmZK7wvDYA8mN7BBwRUnjgIaoND3s=; h=Message-ID:From:To:Cc:Subject:References:MIME-Version: Content-Type:Date; b=MVoiaZ57iFefxQQHdixV9k34La+K4x32rEfRjc1M5w91hluXBeTGhj7OBTcuYWcZ3U9MOikefy+A4EOeGgvmY+N8M9x9VRK3s3FOcNq7nThcJkeRaCm5De43IP9kaU30WP/FsctJO2qnC4h/e50qghQ5IjoFNfRzV+paEw2JJV8= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linutronix.de; spf=pass smtp.mailfrom=linutronix.de; dkim=pass (2048-bit key) header.d=linutronix.de header.i=@linutronix.de header.b=h5gMxkCF; dkim=permerror (0-bit key) header.d=linutronix.de header.i=@linutronix.de header.b=vM5YNVS2; arc=none smtp.client-ip=193.142.43.55 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linutronix.de Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linutronix.de Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linutronix.de header.i=@linutronix.de header.b="h5gMxkCF"; dkim=permerror (0-bit key) header.d=linutronix.de header.i=@linutronix.de header.b="vM5YNVS2" Message-ID: <20250224101343.607036635@linutronix.de> DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linutronix.de; s=2020; t=1740392139; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: references:references; bh=qUenPqK6NF1jZZxvjiZu6Tv4No0pSQ/kqqxuaPEsWtQ=; b=h5gMxkCFhlbques8r3OdZKD2TqWW0VPXm3/LFHiSjbjk/4DUGSh/OenM2MLkxzPpOiJBKS 0y98rsfPFou9qzdG001kSGGLpnegM5lPETgcMVz17+KXqU8UgTXBQ3PYOabIKTLidpFAyz 91Ut7Al+21Px7+AsWi6xYjwjsHReEDvKtfp12hQ0Jq3VF+TdghX3+o+f9Pjujyyqdh5hY3 /HEOAQJB4Tj2nE5nd3jOCd5HO+skf2vsdTjCTtNRXCkuWW1ziMML0QU3BRNyAO3G3nr1lB LIOXhGZsrMXdeL8xwbdH4SPZyc9UxEUbumg2pWVYmEc5OxvBo2v/f7OLEqrLrw== DKIM-Signature: v=1; a=ed25519-sha256; c=relaxed/relaxed; d=linutronix.de; s=2020e; t=1740392139; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: references:references; bh=qUenPqK6NF1jZZxvjiZu6Tv4No0pSQ/kqqxuaPEsWtQ=; b=vM5YNVS2gwCM++LzMXno1YDAy76bo6DfBD59dfzvfcypxhrXItLwwuThFykOPac1o5rV+R KJrLOUrMWa1uk+Dw== From: Thomas Gleixner To: LKML Cc: Anna-Maria Behnsen , Frederic Weisbecker , Benjamin Segall , Eric Dumazet , Andrey Vagin , Pavel Tikhomirov , Peter Zijlstra Subject: [patch 10/11] posix-timers: Provide a mechanism to allocate a given timer ID References: <20250224095736.145530367@linutronix.de> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Date: Mon, 24 Feb 2025 11:15:39 +0100 (CET) Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Checkpoint/Restore in Userspace (CRIU) requires to reconstruct posix timers with the same timer ID on restore. It uses sys_timer_create() and relies on the monotonic increasing timer ID provided by this syscall. It creates and deletes timers until the desired ID is reached. This is can loop for a long time, when the checkpointed process had a very sparse timer ID range. It has been debated to implement a new syscall to allow the creation of timers with a given timer ID, but that's tideous due to the 32/64bit compat issues of sigevent_t and of dubious value. The restore mechanism of CRIU creates the timers in a state where all threads of the restored process are held on a barrier and cannot issue syscalls. That means the restorer task has exclusive control. This allows to address this issue with a prctl() so that the restorer thread can do: if (prctl(PR_TIMER_CREATE_RESTORE_IDS, PR_TIMER_CREATE_RESTORE_IDS_ON)) goto linear_mode; create_timers_with_explicit_ids(); prctl(PR_TIMER_CREATE_RESTORE_IDS, PR_TIMER_CREATE_RESTORE_IDS_OFF); =20 This is backwards compatible because the prctl() fails on older kernels and CRIU can fall back to the linear timer ID mechanism. CRIU versions which do not know about the prctl() just work as before. Implement the prctl() and modify timer_create() so that it copies the requested timer ID from userspace by utilizing the existing timer_t pointer, which is used to copy out the allocated timer ID on success. If the prctl() is disabled, which it is by default, timer_create() works as before and does not try to read from the userspace pointer. There is no problem when a broken or rogue user space application enables the prctl(). If the user space pointer does not contain a valid ID, then timer_create() fails. If the data is not initialized, but constains a random valid ID, timer_create() will create that random timer ID or fail if the ID is already given out.=20 =20 As CRIU must use the raw syscall to avoid manipulating the internal state of the restored process, this has no library dependencies and can be adopted by CRIU right away. Signed-off-by: Thomas Gleixner --- include/linux/posix-timers.h | 2 + include/linux/sched/signal.h | 1=20 include/uapi/linux/prctl.h | 10 +++++ kernel/sys.c | 5 ++ kernel/time/posix-timers.c | 86 ++++++++++++++++++++++++++++++--------= ----- 5 files changed, 78 insertions(+), 26 deletions(-) --- a/include/linux/posix-timers.h +++ b/include/linux/posix-timers.h @@ -114,6 +114,7 @@ bool posixtimer_init_sigqueue(struct sig void posixtimer_send_sigqueue(struct k_itimer *tmr); bool posixtimer_deliver_signal(struct kernel_siginfo *info, struct sigqueu= e *timer_sigq); void posixtimer_free_timer(struct k_itimer *timer); +long posixtimer_create_prctl(unsigned long ctrl); =20 /* Init task static initializer */ #define INIT_CPU_TIMERBASE(b) { \ @@ -140,6 +141,7 @@ static inline void posixtimer_rearm_itim static inline bool posixtimer_deliver_signal(struct kernel_siginfo *info, struct sigqueue *timer_sigq) { return false; } static inline void posixtimer_free_timer(struct k_itimer *timer) { } +static inline long posixtimer_create_prctl(unsigned long ctrl) { return -E= INVAL; } #endif =20 #ifdef CONFIG_POSIX_CPU_TIMERS_TASK_WORK --- a/include/linux/sched/signal.h +++ b/include/linux/sched/signal.h @@ -136,6 +136,7 @@ struct signal_struct { #ifdef CONFIG_POSIX_TIMERS =20 /* POSIX.1b Interval Timers */ + unsigned int timer_create_restore_ids:1; atomic_t next_posix_timer_id; struct hlist_head posix_timers; struct hlist_head ignored_posix_timers; --- a/include/uapi/linux/prctl.h +++ b/include/uapi/linux/prctl.h @@ -353,4 +353,14 @@ struct prctl_mm_map { */ #define PR_LOCK_SHADOW_STACK_STATUS 76 =20 +/* + * Controls the mode of timer_create() for CRIU restore operations. + * Enabling this allows CRIU to restore timers with explicit IDs. + * + * Don't use for normal operations as the result might be undefined. + */ +#define PR_TIMER_CREATE_RESTORE_IDS 77 +# define PR_TIMER_CREATE_RESTORE_IDS_OFF 0 +# define PR_TIMER_CREATE_RESTORE_IDS_ON 1 + #endif /* _LINUX_PRCTL_H */ --- a/kernel/sys.c +++ b/kernel/sys.c @@ -2811,6 +2811,11 @@ SYSCALL_DEFINE5(prctl, int, option, unsi return -EINVAL; error =3D arch_lock_shadow_stack_status(me, arg2); break; + case PR_TIMER_CREATE_RESTORE_IDS: + if (arg3 || arg4 || arg5) + return -EINVAL; + error =3D posixtimer_create_prctl(arg2); + break; default: trace_task_prctl_unknown(option, arg2, arg3, arg4, arg5); error =3D -EINVAL; --- a/kernel/time/posix-timers.c +++ b/kernel/time/posix-timers.c @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -57,6 +58,8 @@ static const struct k_clock * const posi static const struct k_clock *clockid_to_kclock(const clockid_t id); static const struct k_clock clock_realtime, clock_monotonic; =20 +#define TIMER_ANY_ID INT_MIN + /* SIGEV_THREAD_ID cannot share a bit with the other SIGEV values. */ #if SIGEV_THREAD_ID !=3D (SIGEV_THREAD_ID & \ ~(SIGEV_SIGNAL | SIGEV_NONE | SIGEV_THREAD)) @@ -114,38 +117,49 @@ static bool posix_timer_hashed(struct ti return false; } =20 -static int posix_timer_add(struct k_itimer *timer) +static bool posix_timer_add_at(struct k_itimer *timer, struct signal_struc= t *sig, unsigned int id) +{ + struct timer_hash_bucket *bucket =3D &timer_buckets[hash(sig, id)]; + + scoped_guard (spinlock, &bucket->lock) { + /* + * Validate under the lock as this could have raced against + * another thread ending up with the same ID, which is + * highly unlikely, but possible. + */ + if (!posix_timer_hashed(bucket, sig, id)) { + /* + * Set the timer ID and the signal pointer to make + * it identifiable in the hash table. The signal + * pointer has bit 0 set to indicate that it is not + * yet fully initialized. posix_timer_hashed() + * masks this bit out, but the syscall lookup fails + * to match due to it being set. This guarantees + * that there can't be duplicate timer IDs handed + * out. + */ + timer->it_id =3D (timer_t)id; + timer->it_signal =3D (struct signal_struct *)((unsigned long)sig | 1UL); + hlist_add_head_rcu(&timer->t_hash, &bucket->head); + return true; + } + } + return false; +} + +static int posix_timer_add(struct k_itimer *timer, int req_id) { struct signal_struct *sig =3D current->signal; =20 + if (unlikely(req_id !=3D TIMER_ANY_ID)) + return posix_timer_add_at(timer, sig, req_id) ? req_id : -EBUSY; + for (unsigned int cnt =3D 0; cnt <=3D INT_MAX; cnt++) { /* Get the next timer ID and clamp it to positive space */ unsigned int id =3D (atomic_inc_return(&sig->next_posix_timer_id) - 1) &= INT_MAX; - struct timer_hash_bucket *bucket =3D &timer_buckets[hash(sig, id)]; =20 - scoped_guard (spinlock, &bucket->lock) { - /* - * Validate under the lock as this could have raced - * against another thread ending up with the same - * ID, which is highly unlikely, but possible. - */ - if (!posix_timer_hashed(bucket, sig, id)) { - /* - * Set the timer ID and the signal pointer to make - * it identifiable in the hash table. The signal - * pointer has bit 0 set to indicate that it is not - * yet fully initialized. posix_timer_hashed() - * masks this bit out, but the syscall lookup fails - * to match due to it being set. This guarantees - * that there can't be duplicate timer IDs handed - * out. - */ - timer->it_id =3D (timer_t)id; - timer->it_signal =3D (struct signal_struct *)((unsigned long)sig | 1UL= ); - hlist_add_head_rcu(&timer->t_hash, &bucket->head); - return id; - } - } + if (posix_timer_add_at(timer, sig, id)) + return id; cond_resched(); } /* POSIX return code when no timer ID could be allocated */ @@ -351,6 +365,16 @@ static enum hrtimer_restart posix_timer_ return HRTIMER_NORESTART; } =20 +long posixtimer_create_prctl(unsigned long ctrl) +{ + if (ctrl > PR_TIMER_CREATE_RESTORE_IDS_ON) + return -EINVAL; + + guard(spinlock_irq)(¤t->sighand->siglock); + current->signal->timer_create_restore_ids =3D ctrl =3D=3D PR_TIMER_CREATE= _RESTORE_IDS_ON; + return 0; +} + static struct pid *good_sigevent(sigevent_t * event) { struct pid *pid =3D task_tgid(current); @@ -419,6 +443,7 @@ static int do_timer_create(clockid_t whi timer_t __user *created_timer_id) { const struct k_clock *kc =3D clockid_to_kclock(which_clock); + timer_t req_id =3D TIMER_ANY_ID; struct k_itimer *new_timer; int error, new_timer_id; =20 @@ -433,11 +458,20 @@ static int do_timer_create(clockid_t whi =20 spin_lock_init(&new_timer->it_lock); =20 + /* Special case for CRIU to restore timers with a given timer ID. */ + if (unlikely(current->signal->timer_create_restore_ids)) { + if (copy_from_user(&req_id, created_timer_id, sizeof(req_id))) + return -EFAULT; + /* Valid IDs are 0..INT_MAX */ + if ((unsigned int)req_id > INT_MAX) + return -EINVAL; + } + /* * Add the timer to the hash table. The timer is not yet valid * after insertion, but has a unique ID allocated. */ - new_timer_id =3D posix_timer_add(new_timer); + new_timer_id =3D posix_timer_add(new_timer, req_id); if (new_timer_id < 0) { posixtimer_free_timer(new_timer); return new_timer_id; From nobody Sat Feb 7 22:07:55 2026 Received: from galois.linutronix.de (Galois.linutronix.de [193.142.43.55]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id DEDF824E4B0 for ; Mon, 24 Feb 2025 10:15:42 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=193.142.43.55 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740392144; cv=none; b=tjUtRA3TJMX05zIddIHx30b8NV2V3F22BfsGo37ImrXaUAoKGTnvf9C7Jef6sLRFA1le6TZyCHqLCbVHKKrN5HjSqxns6ChA/XP65H2GmPWFsxht6QzXMFGldmUvZbMt0MYEceEmFzfVrjWVeZo8GMoHHujwfGDvXkg2P0xtjeA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740392144; c=relaxed/simple; bh=nYZZhHJLGe1myZ2Y5eWN6i9XXZzDhbtyKF0ZgvRPPW4=; h=Message-ID:From:To:Cc:Subject:References:MIME-Version: Content-Type:Date; b=VBQQzJjSIwxqgvU4jwesEGr9ocZvtUlUVHy5//jfx59yK68UNRNHBJ0zUMJZtb5p4H4HjcGlNQGvsHmkdnPYpwORvnWU2nSr+3+X1d+DluBRd0os+LiZfrkaYTCVZtN/P2aHc2+9juO52AzFmkfPNsG6wDS0Lk7U8U3bnzTA4Cg= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linutronix.de; spf=pass smtp.mailfrom=linutronix.de; dkim=pass (2048-bit key) header.d=linutronix.de header.i=@linutronix.de header.b=HPCsXcVf; dkim=permerror (0-bit key) header.d=linutronix.de header.i=@linutronix.de header.b=dWOo6AWA; arc=none smtp.client-ip=193.142.43.55 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linutronix.de Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linutronix.de Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linutronix.de header.i=@linutronix.de header.b="HPCsXcVf"; dkim=permerror (0-bit key) header.d=linutronix.de header.i=@linutronix.de header.b="dWOo6AWA" Message-ID: <20250224101343.672288753@linutronix.de> DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linutronix.de; s=2020; t=1740392141; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: references:references; bh=BbMg7HjWIRqHiwnyJ0qix1onrX11tdlxf6bBcAlKQxs=; b=HPCsXcVfeSjdU9dHObds7CWU+o9IjBsOj4Vl5lZQLwYS2Lnbt0skVj3dHnolrJMQWRZeA4 hV/1/4YL7WJuzglgV7UdB86+oXjetdS6YFEqC6IjqFOKVgLn3XLH0xi2z9N1oCBFhYUyHp Y5oTu8lDbL+ekJ++DF5Emd4oUdBEstvkYsOSXwTSuk/3/eAYvHSHNNlQr6R4K188CAGnfB 9HVAmUFrnQ+nkqDL+PTN2Ou50BRzjfyvjPtw/Ol0PtM2APeb7jU92FjHpOvh7HwyyWWIMU Sa0FyVbnyEedbiTqypqZs6KXg3TnA5jKVtrjtcoSS2tjEo2Clh2mlEPeUssUPQ== DKIM-Signature: v=1; a=ed25519-sha256; c=relaxed/relaxed; d=linutronix.de; s=2020e; t=1740392141; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: references:references; bh=BbMg7HjWIRqHiwnyJ0qix1onrX11tdlxf6bBcAlKQxs=; b=dWOo6AWArJFlHDUJbRuBA93JZKoiXwubZH/RZBFYcnVHkha83zqK6v5jZmoC47y2/cb7yl 74odQDthSOjvB3Dg== From: Thomas Gleixner To: LKML Cc: Anna-Maria Behnsen , Frederic Weisbecker , Benjamin Segall , Eric Dumazet , Andrey Vagin , Pavel Tikhomirov , Peter Zijlstra Subject: [patch 11/11] selftests/timers/posix-timers: Add a test for exact allocation mode References: <20250224095736.145530367@linutronix.de> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Date: Mon, 24 Feb 2025 11:15:41 +0100 (CET) Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" The exact timer ID allocation mode is used by CRIU to restore timers with a given ID. Add a test case for it. It's skipped on older kernels when the prctl() fails. Signed-off-by: Thomas Gleixner --- tools/testing/selftests/timers/posix_timers.c | 68 +++++++++++++++++++++= ++++- 1 file changed, 67 insertions(+), 1 deletion(-) --- a/tools/testing/selftests/timers/posix_timers.c +++ b/tools/testing/selftests/timers/posix_timers.c @@ -7,6 +7,7 @@ * Kernel loop code stolen from Steven Rostedt */ #define _GNU_SOURCE +#include #include #include #include @@ -599,14 +600,79 @@ static void check_overrun(int which, con "check_overrun %s\n", name); } =20 +#include + +static int do_timer_create(int *id) +{ + return syscall(__NR_timer_create, CLOCK_MONOTONIC, NULL, id); +} + +static int do_timer_delete(int id) +{ + return syscall(__NR_timer_delete, id); +} + +static void check_timer_create_exact(void) +{ + int id, rid; + + /* Allocate a timer for comparison after switch back from exact mode */ + if (do_timer_create(&id) < 0) + fatal_error(NULL, "timer_create()"); + + if (do_timer_delete(id)) + fatal_error(NULL, "timer_delete()"); + + if (prctl(77, 1, 0, 0, 0)) { + switch (errno) { + case EINVAL: + ksft_test_result_skip("check timer create exact, not supported\n"); + return; + default: + ksft_test_result_skip("check timer create exact, errno =3D %d\n", errno= ); + return; + } + } + + rid =3D id + 8; + if (do_timer_create(&rid) < 0) + fatal_error(NULL, "timer_create()"); + + if (do_timer_delete(rid)) + fatal_error(NULL, "timer_delete()"); + + if (prctl(77, 0, 0, 0, 0)) + fatal_error(NULL, "prctl()"); + + if (rid !=3D id + 8) { + ksft_test_result_fail("check timer create exact %d !=3D %d\n", rid, id += 8); + return; + } + + /* Validate that it went back to normal mode */ + if (do_timer_create(&rid) < 0) + fatal_error(NULL, "timer_create()"); + + if (do_timer_delete(rid)) + fatal_error(NULL, "timer_delete()"); + + /* Same ID if linear mode is off, next ID if enabled */ + if (rid =3D=3D id || rid =3D=3D id + 1) + ksft_test_result_pass("check timer create exact\n"); + else + ksft_test_result_fail("check timer create exact. Disabling failed.\n"); +} + int main(int argc, char **argv) { ksft_print_header(); - ksft_set_plan(18); + ksft_set_plan(19); =20 ksft_print_msg("Testing posix timers. False negative may happen on CPU ex= ecution \n"); ksft_print_msg("based timers if other threads run on the CPU...\n"); =20 + check_timer_create_exact(); + check_itimer(ITIMER_VIRTUAL, "ITIMER_VIRTUAL"); check_itimer(ITIMER_PROF, "ITIMER_PROF"); check_itimer(ITIMER_REAL, "ITIMER_REAL");