From nobody Wed Oct 8 05:57:14 2025 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 E78EC254AE1; Tue, 7 Oct 2025 21:39:31 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1759873172; cv=none; b=ngNX38pwCrDAguNSNjY5FOpFY84GWRwGMAQ6Rfe81QFODL2BzdetEnEYU0vfjX+EdSciETS5JI9Ry6Rbe/rG52PeAe5fvfvpUw+3ZPKHWBe7immTGVPME35sQrQvXAQ3QC6Ldn+02Ai/T0rzEzDyIMnfJ0E3dWSy6iIP1ILtlYI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1759873172; c=relaxed/simple; bh=zL+0EonX4yAc7B6yjhhjBannMKC0T+wNhNBCV0IzQeE=; h=Message-ID:Date:From:To:Cc:Subject:References:MIME-Version: Content-Type; b=JQWAFGcUxUSUvedzooUh86Ra5Xa5iBqdEzFHZVgwlC8gDZ/42zI6bN5TMTDuIqWTwc8OrOagbNILXEj2Tvxv7Z83GyvWkxF6BRM+N947v+sh/Voo6vBYOtQUu7X6+3afpvY9Z+5xadGG3/BXWI+ZqIpWk3shBcCo0xH0cF+8PLQ= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=EJ9fuBWT; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="EJ9fuBWT" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 48D76C4CEFE; Tue, 7 Oct 2025 21:39:31 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1759873171; bh=zL+0EonX4yAc7B6yjhhjBannMKC0T+wNhNBCV0IzQeE=; h=Date:From:To:Cc:Subject:References:From; b=EJ9fuBWTnqOj26UmHnoVgQ9ml5OG2YvYpbneUS3/AKdOhFgUI5Tz/Jl6NoLEf4zSv X/U4GbgGewBKIEZCXlX9LipmjrVeUc2hCZmYbsjDbortRJrA6P+G6YM+UKQWCylFqp NvYajZWan3a/k/TL3GYD97dCUGaSpVIBj2dDnw+JggLBKBgzyn+OLIkr59oXI3sAs9 q+dJeHNhdihvCOi47vmzKvGUXUV2Vw15pIMSkdLz24TpxVw5fnmW60bGYU7J0QLUia CEUvu/UBitkZVCnLGS1tnjIFAnCdeN07i1FnQD6PRClu78vXG0R2rxqw7tzAgUibbq 1PLVktQ+cwctg== Received: from rostedt by gandalf with local (Exim 4.98.2) (envelope-from ) id 1v6FQx-00000007Xfg-2sCb; Tue, 07 Oct 2025 17:41:23 -0400 Message-ID: <20251007214123.537465618@kernel.org> User-Agent: quilt/0.68 Date: Tue, 07 Oct 2025 17:40:09 -0400 From: Steven Rostedt To: linux-kernel@vger.kernel.org, linux-trace-kernel@vger.kernel.org, bpf@vger.kernel.org, x86@kernel.org Cc: Masami Hiramatsu , Mathieu Desnoyers , Josh Poimboeuf , Peter Zijlstra , Ingo Molnar , Jiri Olsa , Arnaldo Carvalho de Melo , Namhyung Kim , Thomas Gleixner , Andrii Nakryiko , Indu Bhagat , "Jose E. Marchesi" , Beau Belgrave , Jens Remus , Linus Torvalds , Andrew Morton , Florian Weimer , Sam James , Kees Cook , "Carlos O'Donell" Subject: [PATCH v16 1/4] unwind: Add interface to allow tracing a single task References: <20251007214008.080852573@kernel.org> 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" From: Steven Rostedt If a tracer (namely perf) is only tracing a single task, it doesn't need the full functionality of the deferred stacktrace infrastructure. That infrastructure has a limited number of users as it needs to handle multiple tracers that can trace multiple tasks at the same time, creating a multi to multi relationship. But for a tracer that is tracing a single task, that creates a single to multi relationship (a tracer tracing a single task and a task that can have several tracers tracing it). This allows for data to be allocated at the time of initialization to let the tracer use its own task_work data structures to attach to the task. Add a new interface called unwind_deferred_task_init() that works similar to the unwind_deferred_init(), but this interface is used when the tracer will only ever trace a single task at the same time. The unwind_work descriptor that is initialized during this init function now has a struct callback_head field that is used to attach itself to a task_work. The work->bit for this task is set to the UNWIND_PENDING_BIT (but defined as UNWIND_TASK) to differentiate it from unwind_works that are tracing any task, as their work->bit will be one of the allocated bits in the unwind_mask. The rest of the calls are the same. That is, the unwind_deferred_request() and unwind_deferred_cancel() are called on this, and these functions will know that this unwind_work descriptor traces a single task. Even the callback function works the same. If a tracer were to try to use this unwind_work on multiple tasks at the same time, it will simply fail to attach to the second task if one is already pending a deferred stacktrace, and a WARN_ON is produced. Signed-off-by: Steven Rostedt (Google) --- include/linux/unwind_deferred.h | 15 ++ kernel/unwind/deferred.c | 283 +++++++++++++++++++++++++++----- 2 files changed, 255 insertions(+), 43 deletions(-) diff --git a/include/linux/unwind_deferred.h b/include/linux/unwind_deferre= d.h index f4743c8cff4c..6f0f04ba538d 100644 --- a/include/linux/unwind_deferred.h +++ b/include/linux/unwind_deferred.h @@ -2,6 +2,7 @@ #ifndef _LINUX_UNWIND_USER_DEFERRED_H #define _LINUX_UNWIND_USER_DEFERRED_H =20 +#include #include #include #include @@ -15,6 +16,9 @@ typedef void (*unwind_callback_t)(struct unwind_work *wor= k, struct unwind_work { struct list_head list; unwind_callback_t func; + struct callback_head work; + struct task_struct *task; + struct rcuwait wait; int bit; }; =20 @@ -32,11 +36,22 @@ enum { UNWIND_USED =3D BIT(UNWIND_USED_BIT) }; =20 +/* + * UNWIND_PENDING is set in the task's info->unwind_mask when + * a deferred unwind is requested on that task. If the unwind + * descriptor is used only to trace a specific task, it's bit + * is the UNWIND_PENDING_BIT. This gets set as the work->bit + * and is to distinguish unwind_work descriptors that trace + * a single task from those that trace all tasks. + */ +#define UNWIND_TASK UNWIND_PENDING_BIT + void unwind_task_init(struct task_struct *task); void unwind_task_free(struct task_struct *task); =20 int unwind_user_faultable(struct unwind_stacktrace *trace); =20 +int unwind_deferred_task_init(struct unwind_work *work, unwind_callback_t = func); int unwind_deferred_init(struct unwind_work *work, unwind_callback_t func); int unwind_deferred_request(struct unwind_work *work, u64 *cookie); void unwind_deferred_cancel(struct unwind_work *work); diff --git a/kernel/unwind/deferred.c b/kernel/unwind/deferred.c index ceeeff562302..f34b60713a4b 100644 --- a/kernel/unwind/deferred.c +++ b/kernel/unwind/deferred.c @@ -44,6 +44,7 @@ static inline bool try_assign_cnt(struct unwind_task_info= *info, u32 cnt) /* Guards adding to or removing from the list of callbacks */ static DEFINE_MUTEX(callback_mutex); static LIST_HEAD(callbacks); +static LIST_HEAD(task_callbacks); =20 #define RESERVED_BITS (UNWIND_PENDING | UNWIND_USED) =20 @@ -155,12 +156,18 @@ static void process_unwind_deferred(struct task_struc= t *task) unsigned long bits; u64 cookie; =20 - if (WARN_ON_ONCE(!unwind_pending(info))) - return; - /* Clear pending bit but make sure to have the current bits */ bits =3D atomic_long_fetch_andnot(UNWIND_PENDING, &info->unwind_mask); + + /* Remove the callbacks that were already completed */ + if (info->cache) + bits &=3D ~(info->cache->unwind_completed); + + /* If all callbacks have already been done, there's nothing to do */ + if (!bits) + return; + /* * From here on out, the callback must always be called, even if it's * just an empty trace. @@ -170,9 +177,6 @@ static void process_unwind_deferred(struct task_struct = *task) =20 unwind_user_faultable(&trace); =20 - if (info->cache) - bits &=3D ~(info->cache->unwind_completed); - cookie =3D info->id.id; =20 guard(srcu)(&unwind_srcu); @@ -186,11 +190,95 @@ static void process_unwind_deferred(struct task_struc= t *task) } } =20 -static void unwind_deferred_task_work(struct callback_head *head) +/* Callback for an unwind work that traces all tasks */ +static void unwind_deferred_work(struct callback_head *head) { process_unwind_deferred(current); } =20 +/* Get the trace for an unwind work that traces a single task */ +static void get_deferred_task_stacktrace(struct task_struct *task, + struct unwind_stacktrace *trace, + u64 *cookie, bool clear_pending) +{ + struct unwind_task_info *info =3D &task->unwind_info; + + if (clear_pending) + atomic_long_andnot(UNWIND_PENDING, &info->unwind_mask); + + trace->nr =3D 0; + trace->entries =3D NULL; + + unwind_user_faultable(trace); + + *cookie =3D info->id.id; +} + +/* Callback for an unwind work that only traces this task */ +static void unwind_deferred_task_work(struct callback_head *head) +{ + struct unwind_work *work =3D container_of(head, struct unwind_work, work); + struct unwind_task_info *info =3D ¤t->unwind_info; + struct unwind_stacktrace trace; + u64 cookie; + + guard(srcu)(&unwind_srcu); + + /* Always clear the pending bit when this is called */ + atomic_long_andnot(UNWIND_PENDING, &info->unwind_mask); + + /* Is this work being canceled? */ + if (unlikely(work->bit < 0)) + work->task =3D NULL; + + if (!work->task) + goto out; + + /* + * From here on out, the callback must always be called, even if it's + * just an empty trace. + */ + get_deferred_task_stacktrace(current, &trace, &cookie, false); + work->func(work, &trace, cookie); + work->task =3D NULL; +out: + /* Synchronize with cancel_unwind_task() */ + rcuwait_wake_up(&work->wait); +} + +/* Flush any pending work for an exiting task */ +static void process_unwind_tasks(struct task_struct *task) +{ + struct unwind_stacktrace trace; + struct unwind_work *work; + u64 cookie =3D 0; + + guard(srcu)(&unwind_srcu); + + /* The task is exiting, flush any pending per task unwind works */ + list_for_each_entry_srcu(work, &task_callbacks, list, + srcu_read_lock_held(&unwind_srcu)) { + if (work->task !=3D task) + continue; + + /* There may be waiters in cancel_unwind_task() */ + if (work->bit < 0) + goto wakeup; + + task_work_cancel(task, &work->work); + + /* Only need to get the trace once */ + if (!cookie) + get_deferred_task_stacktrace(task, &trace, + &cookie, true); + work->func(work, &trace, cookie); +wakeup: + work->task =3D NULL; + /* Synchronize with cancel_unwind_task() */ + rcuwait_wake_up(&work->wait); + } +} + void unwind_deferred_task_exit(struct task_struct *task) { struct unwind_task_info *info =3D ¤t->unwind_info; @@ -199,10 +287,80 @@ void unwind_deferred_task_exit(struct task_struct *ta= sk) return; =20 process_unwind_deferred(task); + process_unwind_tasks(task); =20 task_work_cancel(task, &info->work); } =20 +static int queue_unwind_task(struct unwind_work *work, int twa_mode, + struct unwind_task_info *info) +{ + struct task_struct *task =3D READ_ONCE(work->task); + int ret; + + if (task) { + /* Did the tracer break its contract? */ + WARN_ON_ONCE(task !=3D current); + return 1; + } + + if (!try_cmpxchg(&work->task, &task, current)) + return 1; + + /* The work has been claimed, now schedule it. */ + ret =3D task_work_add(current, &work->work, twa_mode); + + if (WARN_ON_ONCE(ret)) + work->task =3D NULL; + else + atomic_long_or(UNWIND_PENDING, &info->unwind_mask); + + return ret; +} + +static int queue_unwind_work(struct unwind_work *work, int twa_mode, + struct unwind_task_info *info) +{ + unsigned long bit =3D BIT(work->bit); + unsigned long old, bits; + int ret; + + /* Check if the unwind_work only traces this task */ + if (work->bit =3D=3D UNWIND_TASK) + return queue_unwind_task(work, twa_mode, info); + + old =3D atomic_long_read(&info->unwind_mask); + + /* Is this already queued or executed */ + if (old & bit) + return 1; + + /* + * This work's bit hasn't been set yet. Now set it with the PENDING + * bit and fetch the current value of unwind_mask. If ether the + * work's bit or PENDING was already set, then this is already queued + * to have a callback. + */ + bits =3D UNWIND_PENDING | bit; + old =3D atomic_long_fetch_or(bits, &info->unwind_mask); + if (old & bits) { + /* + * If the work's bit was set, whatever set it had better + * have also set pending and queued a callback. + */ + WARN_ON_ONCE(!(old & UNWIND_PENDING)); + return old & bit; + } + + /* The work has been claimed, now schedule it. */ + ret =3D task_work_add(current, &info->work, twa_mode); + + if (WARN_ON_ONCE(ret)) + atomic_long_set(&info->unwind_mask, 0); + + return ret; +} + /** * unwind_deferred_request - Request a user stacktrace on task kernel exit * @work: Unwind descriptor requesting the trace @@ -232,9 +390,6 @@ int unwind_deferred_request(struct unwind_work *work, u= 64 *cookie) { struct unwind_task_info *info =3D ¤t->unwind_info; int twa_mode =3D TWA_RESUME; - unsigned long old, bits; - unsigned long bit; - int ret; =20 *cookie =3D 0; =20 @@ -254,47 +409,45 @@ int unwind_deferred_request(struct unwind_work *work,= u64 *cookie) } =20 /* Do not allow cancelled works to request again */ - bit =3D READ_ONCE(work->bit); - if (WARN_ON_ONCE(bit < 0)) + if (WARN_ON_ONCE(READ_ONCE(work->bit) < 0)) return -EINVAL; =20 - /* Only need the mask now */ - bit =3D BIT(bit); - guard(irqsave)(); =20 *cookie =3D get_cookie(info); =20 - old =3D atomic_long_read(&info->unwind_mask); + return queue_unwind_work(work, twa_mode, info); +} =20 - /* Is this already queued or executed */ - if (old & bit) - return 1; +static void cancel_unwind_task(struct unwind_work *work) +{ + struct task_struct *task; =20 - /* - * This work's bit hasn't been set yet. Now set it with the PENDING - * bit and fetch the current value of unwind_mask. If ether the - * work's bit or PENDING was already set, then this is already queued - * to have a callback. - */ - bits =3D UNWIND_PENDING | bit; - old =3D atomic_long_fetch_or(bits, &info->unwind_mask); - if (old & bits) { + task =3D READ_ONCE(work->task); + + if (!task || !task_work_cancel(task, &work->work)) { /* - * If the work's bit was set, whatever set it had better - * have also set pending and queued a callback. + * If the task_work_cancel() fails to cancel it could mean that + * the task_work is just about to execute. This needs to wait + * until the work->func() is finished before returning. + * This is required because the SRCU section may not have been + * entered yet, and the synchronize_srcu() will not wait for it. */ - WARN_ON_ONCE(!(old & UNWIND_PENDING)); - return old & bit; + if (task) { + rcuwait_wait_event(&work->wait, work->task =3D=3D NULL, + TASK_UNINTERRUPTIBLE); + } } =20 - /* The work has been claimed, now schedule it. */ - ret =3D task_work_add(current, &info->work, twa_mode); - - if (WARN_ON_ONCE(ret)) - atomic_long_set(&info->unwind_mask, 0); + /* + * Needed to protect loop in process_unwind_tasks(). + * This also guarantees that unwind_deferred_task_work() is + * completely done and the work structure is no longer referenced. + */ + synchronize_srcu(&unwind_srcu); =20 - return ret; + /* Still set task to NULL if task_work_cancel() succeeded */ + work->task =3D NULL; } =20 void unwind_deferred_cancel(struct unwind_work *work) @@ -307,16 +460,24 @@ void unwind_deferred_cancel(struct unwind_work *work) =20 bit =3D work->bit; =20 - /* No work should be using a reserved bit */ - if (WARN_ON_ONCE(BIT(bit) & RESERVED_BITS)) + /* Was it initialized ? */ + if (!bit) return; =20 - guard(mutex)(&callback_mutex); - list_del_rcu(&work->list); + scoped_guard(mutex, &callback_mutex) { + list_del_rcu(&work->list); + } =20 /* Do not allow any more requests and prevent callbacks */ work->bit =3D -1; =20 + if (bit =3D=3D UNWIND_TASK) + return cancel_unwind_task(work); + + /* No work should be using a reserved bit */ + if (WARN_ON_ONCE(BIT(bit) & RESERVED_BITS)) + return; + __clear_bit(bit, &unwind_mask); =20 synchronize_srcu(&unwind_srcu); @@ -330,6 +491,17 @@ void unwind_deferred_cancel(struct unwind_work *work) } } =20 +/** + * unwind_deferred_init - Init unwind_work that traces any task + * @work: The unwind_work descriptor to initialize + * @func: The callback function that will have the stacktrace + * + * Initialize a work that can trace any task. There's only a limited + * number of these that can be allocated. + * + * Returns 0 on success or -EBUSY if the limit of these unwind_works have + * been exceeded. + */ int unwind_deferred_init(struct unwind_work *work, unwind_callback_t func) { memset(work, 0, sizeof(*work)); @@ -348,12 +520,37 @@ int unwind_deferred_init(struct unwind_work *work, un= wind_callback_t func) return 0; } =20 +/** + * unwind_deferred_task_init - Init unwind_work that traces a single task + * @work: The unwind_work descriptor to initialize + * @func: The callback function that will have the stacktrace + * + * Initialize a work that will always trace only a single task. It is + * up to the caller to make sure that the unwind_deferred_requeust() + * will always be called on the same task for the @work descriptor. + * + * Note, unlike unwind_deferred_init() there is no limit of these works + * that can be initialized and used. + */ +int unwind_deferred_task_init(struct unwind_work *work, unwind_callback_t = func) +{ + memset(work, 0, sizeof(*work)); + work->bit =3D UNWIND_TASK; + init_task_work(&work->work, unwind_deferred_task_work); + work->func =3D func; + rcuwait_init(&work->wait); + + guard(mutex)(&callback_mutex); + list_add_rcu(&work->list, &task_callbacks); + return 0; +} + void unwind_task_init(struct task_struct *task) { struct unwind_task_info *info =3D &task->unwind_info; =20 memset(info, 0, sizeof(*info)); - init_task_work(&info->work, unwind_deferred_task_work); + init_task_work(&info->work, unwind_deferred_work); atomic_long_set(&info->unwind_mask, 0); } =20 --=20 2.50.1 From nobody Wed Oct 8 05:57:14 2025 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 CFB7F253F3D; Tue, 7 Oct 2025 21:39:31 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1759873171; cv=none; b=PT75WCyIExniJ7eqtot9GhaaC0T7UWeOfxgTQMFJodsbNMQAy1OV4QdfT+7x6e7DaSsw3ydPAa/T/6vzcjz4RtNVrgypcUFkJeWgRcHa1LruhJI2ZgJD83sWt2EXQXUZJaNDUNxLmuflRXnSHpHu4TZo55QvtAoZVI9g3DiRdN4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1759873171; c=relaxed/simple; bh=RbmBYiPpCFuN1S5X77JBvvRnJR/euKv0kkHDqGcrugQ=; h=Message-ID:Date:From:To:Cc:Subject:References:MIME-Version: Content-Type; b=DpW3mYRa+9kwOx8gCbAFpZF2QpAz7sG4tnLHc0FP1dNXiiX/Xm1CZb2YlM4fdy6VebSihnpnyN3uAUBUZHdw+7LTaMWPYAVsL0pmCiPFvUi3+xlDuXnA/IC64Wqhzwxs1Ur2vHbDK7ZDHPLvCZefLJyaRkiuQmdB33AwNAgDS7o= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=BEQKNpmg; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="BEQKNpmg" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 55638C113D0; Tue, 7 Oct 2025 21:39:31 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1759873171; bh=RbmBYiPpCFuN1S5X77JBvvRnJR/euKv0kkHDqGcrugQ=; h=Date:From:To:Cc:Subject:References:From; b=BEQKNpmgpq2zgKNhmOwrMV1CwVc/Kp3EaHwUgA4TlnRItntfoq0i8fVf/p377t3Uj JUHVWMfgO79Z2ZEOj482e8xW3QuW25T1R9SStthu9QqL70tmCbXB6F8B6T+hh7Qjey DcCuiJnNO2MEYXw4E+BE9qJl2rJD33MA1xiGdR6IzKu4Yw4x5XoEJhD9tV9ollilw9 GowdwOtokB+t69f/DAUHE00sx9WjLG2c18gRp453vLFEy67ToolPCAthub/a6Ufgdc Mdiw1hr2+HBEfsOUhfvQerl6/2tFwm6zJ+SponJAWnpyp9M5HNSfj1uL1fHXJ8wyP3 oAw0a7xD2j5aA== Received: from rostedt by gandalf with local (Exim 4.98.2) (envelope-from ) id 1v6FQx-00000007XgD-3Zdc; Tue, 07 Oct 2025 17:41:23 -0400 Message-ID: <20251007214123.705413492@kernel.org> User-Agent: quilt/0.68 Date: Tue, 07 Oct 2025 17:40:10 -0400 From: Steven Rostedt To: linux-kernel@vger.kernel.org, linux-trace-kernel@vger.kernel.org, bpf@vger.kernel.org, x86@kernel.org Cc: Masami Hiramatsu , Mathieu Desnoyers , Josh Poimboeuf , Peter Zijlstra , Ingo Molnar , Jiri Olsa , Arnaldo Carvalho de Melo , Namhyung Kim , Thomas Gleixner , Andrii Nakryiko , Indu Bhagat , "Jose E. Marchesi" , Beau Belgrave , Jens Remus , Linus Torvalds , Andrew Morton , Florian Weimer , Sam James , Kees Cook , "Carlos O'Donell" Subject: [PATCH v16 2/4] perf: Support deferred user callchains References: <20251007214008.080852573@kernel.org> 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" From: Josh Poimboeuf If the user fault unwind is available (the one that will be used for sframes), have perf be able to utilize it. Currently all user stack traces are done at the request site. This mostly happens in interrupt or NMI context where user space is only accessible if it is currently present in memory. It is possible that the user stack was swapped out and is not present, but mostly the use of sframes will require faulting in user pages which will not be possible from interrupt context. Instead, add a frame work that will delay the reading of the user space stack until the task goes back to user space where faulting in pages is possible. This is also advantageous as the user space stack doesn't change while in the kernel, and this will also remove duplicate entries of user space stacks for a long running system call being profiled. A new perf context is created called PERF_CONTEXT_USER_DEFERRED. It is added to the kernel callchain, usually when an interrupt or NMI is triggered (but can be added to any callchain). When a deferred unwind is required, it uses the new deferred unwind infrastructure. When tracing a single task and a user stack trace is required, perf will call unwind_deferred_request(). This will trigger a task_work that on task kernel space exit will call the perf function perf_event_deferred_task() with the user stacktrace and a cookie (an identifier for that stack trace). This user stack trace will go into a new perf type called PERF_RECORD_CALLCHAIN_DEFERRED. The perf user space will need to attach this stack trace to each of the previous kernel callchains for that task with the PERF_CONTEXT_USER_DEFERRED context in them. Suggested-by: Peter Zijlstra Co-developed-by: Steven Rostedt (Google) Signed-off-by: Josh Poimboeuf Signed-off-by: Steven Rostedt (Google) --- Changes since v15: https://lore.kernel.org/20250825180801.727927527@kernel.= org - Peter Zijlstra pointed out that the code mostly duplicated the code of the unwind infrastructure, and had the same bugs as it had. The unwind infrastructure was updated to allow a tracer to use it for a single task. The perf code now uses that which greatly simplified this version over the previous one. include/linux/perf_event.h | 5 +- include/uapi/linux/perf_event.h | 20 ++++- kernel/bpf/stackmap.c | 4 +- kernel/events/callchain.c | 11 ++- kernel/events/core.c | 110 +++++++++++++++++++++++++- tools/include/uapi/linux/perf_event.h | 20 ++++- 6 files changed, 162 insertions(+), 8 deletions(-) diff --git a/include/linux/perf_event.h b/include/linux/perf_event.h index fd1d91017b99..152e3dacff98 100644 --- a/include/linux/perf_event.h +++ b/include/linux/perf_event.h @@ -53,6 +53,7 @@ #include #include #include +#include =20 #include =20 @@ -880,6 +881,8 @@ struct perf_event { struct callback_head pending_task; unsigned int pending_work; =20 + struct unwind_work unwind_work; + atomic_t event_limit; =20 /* address range filters */ @@ -1720,7 +1723,7 @@ extern void perf_callchain_user(struct perf_callchain= _entry_ctx *entry, struct p extern void perf_callchain_kernel(struct perf_callchain_entry_ctx *entry, = struct pt_regs *regs); extern struct perf_callchain_entry * get_perf_callchain(struct pt_regs *regs, bool kernel, bool user, - u32 max_stack, bool crosstask, bool add_mark); + u32 max_stack, bool crosstask, bool add_mark, bool defer_user); extern int get_callchain_buffers(int max_stack); extern void put_callchain_buffers(void); extern struct perf_callchain_entry *get_callchain_entry(int *rctx); diff --git a/include/uapi/linux/perf_event.h b/include/uapi/linux/perf_even= t.h index 78a362b80027..20b8f890113b 100644 --- a/include/uapi/linux/perf_event.h +++ b/include/uapi/linux/perf_event.h @@ -463,7 +463,8 @@ struct perf_event_attr { inherit_thread : 1, /* children only inherit if cloned with CLONE_THR= EAD */ remove_on_exec : 1, /* event is removed from task on exec */ sigtrap : 1, /* send synchronous SIGTRAP on event */ - __reserved_1 : 26; + defer_callchain: 1, /* generate PERF_RECORD_CALLCHAIN_DEFERRED record= s */ + __reserved_1 : 25; =20 union { __u32 wakeup_events; /* wake up every n events */ @@ -1239,6 +1240,22 @@ enum perf_event_type { */ PERF_RECORD_AUX_OUTPUT_HW_ID =3D 21, =20 + /* + * This user callchain capture was deferred until shortly before + * returning to user space. Previous samples would have kernel + * callchains only and they need to be stitched with this to make full + * callchains. + * + * struct { + * struct perf_event_header header; + * u64 cookie; + * u64 nr; + * u64 ips[nr]; + * struct sample_id sample_id; + * }; + */ + PERF_RECORD_CALLCHAIN_DEFERRED =3D 22, + PERF_RECORD_MAX, /* non-ABI */ }; =20 @@ -1269,6 +1286,7 @@ enum perf_callchain_context { PERF_CONTEXT_HV =3D (__u64)-32, PERF_CONTEXT_KERNEL =3D (__u64)-128, PERF_CONTEXT_USER =3D (__u64)-512, + PERF_CONTEXT_USER_DEFERRED =3D (__u64)-640, =20 PERF_CONTEXT_GUEST =3D (__u64)-2048, PERF_CONTEXT_GUEST_KERNEL =3D (__u64)-2176, diff --git a/kernel/bpf/stackmap.c b/kernel/bpf/stackmap.c index ec3a57a5fba1..339f7cbbcf36 100644 --- a/kernel/bpf/stackmap.c +++ b/kernel/bpf/stackmap.c @@ -315,7 +315,7 @@ BPF_CALL_3(bpf_get_stackid, struct pt_regs *, regs, str= uct bpf_map *, map, max_depth =3D sysctl_perf_event_max_stack; =20 trace =3D get_perf_callchain(regs, kernel, user, max_depth, - false, false); + false, false, false); =20 if (unlikely(!trace)) /* couldn't fetch the stack trace */ @@ -452,7 +452,7 @@ static long __bpf_get_stack(struct pt_regs *regs, struc= t task_struct *task, trace =3D get_callchain_entry_for_task(task, max_depth); else trace =3D get_perf_callchain(regs, kernel, user, max_depth, - crosstask, false); + crosstask, false, false); =20 if (unlikely(!trace) || trace->nr < skip) { if (may_fault) diff --git a/kernel/events/callchain.c b/kernel/events/callchain.c index 808c0d7a31fa..d0e0da66a164 100644 --- a/kernel/events/callchain.c +++ b/kernel/events/callchain.c @@ -218,7 +218,7 @@ static void fixup_uretprobe_trampoline_entries(struct p= erf_callchain_entry *entr =20 struct perf_callchain_entry * get_perf_callchain(struct pt_regs *regs, bool kernel, bool user, - u32 max_stack, bool crosstask, bool add_mark) + u32 max_stack, bool crosstask, bool add_mark, bool defer_user) { struct perf_callchain_entry *entry; struct perf_callchain_entry_ctx ctx; @@ -251,6 +251,15 @@ get_perf_callchain(struct pt_regs *regs, bool kernel, = bool user, regs =3D task_pt_regs(current); } =20 + if (defer_user) { + /* + * Foretell the coming of PERF_RECORD_CALLCHAIN_DEFERRED + * which can be stitched to this one. + */ + perf_callchain_store_context(&ctx, PERF_CONTEXT_USER_DEFERRED); + goto exit_put; + } + if (add_mark) perf_callchain_store_context(&ctx, PERF_CONTEXT_USER); =20 diff --git a/kernel/events/core.c b/kernel/events/core.c index 28de3baff792..be94b437e7e0 100644 --- a/kernel/events/core.c +++ b/kernel/events/core.c @@ -5582,6 +5582,67 @@ static bool exclusive_event_installable(struct perf_= event *event, return true; } =20 +static void perf_pending_unwind_sync(struct perf_event *event) +{ + struct unwind_work *work =3D &event->unwind_work; + + unwind_deferred_cancel(work); +} + +struct perf_callchain_deferred_event { + struct perf_event_header header; + u64 cookie; + u64 nr; + u64 ips[]; +}; + +static void perf_event_callchain_deferred(struct perf_event *event, + struct unwind_stacktrace *trace, + u64 cookie) +{ + struct perf_callchain_deferred_event deferred_event; + u64 callchain_context =3D PERF_CONTEXT_USER; + struct perf_output_handle handle; + struct perf_sample_data data; + u64 nr; + + nr =3D trace->nr + 1 ; /* '+1' =3D=3D callchain_context */ + + deferred_event.header.type =3D PERF_RECORD_CALLCHAIN_DEFERRED; + deferred_event.header.misc =3D PERF_RECORD_MISC_USER; + deferred_event.header.size =3D sizeof(deferred_event) + (nr * sizeof(u64)= ); + + deferred_event.nr =3D nr; + deferred_event.cookie =3D cookie; + + perf_event_header__init_id(&deferred_event.header, &data, event); + + if (perf_output_begin(&handle, &data, event, deferred_event.header.size)) + return; + + perf_output_put(&handle, deferred_event); + perf_output_put(&handle, callchain_context); + /* trace->entries[] are not guaranteed to be 64bit */ + for (int i =3D 0; i < trace->nr; i++) { + u64 entry =3D trace->entries[i]; + perf_output_put(&handle, entry); + } + perf_event__output_id_sample(event, &handle, &data); + + perf_output_end(&handle); +} + +/* Deferred unwinding callback for task specific events */ +static void perf_event_deferred_task(struct unwind_work *work, + struct unwind_stacktrace *trace, u64 cookie) +{ + struct perf_event *event =3D container_of(work, struct perf_event, unwind= _work); + + perf_event_callchain_deferred(event, trace, cookie); + + local_dec(&event->ctx->nr_no_switch_fast); +} + static void perf_free_addr_filters(struct perf_event *event); =20 /* vs perf_event_alloc() error */ @@ -5649,6 +5710,7 @@ static void _free_event(struct perf_event *event) { irq_work_sync(&event->pending_irq); irq_work_sync(&event->pending_disable_irq); + perf_pending_unwind_sync(event); =20 unaccount_event(event); =20 @@ -8194,6 +8256,28 @@ static u64 perf_get_page_size(unsigned long addr) =20 static struct perf_callchain_entry __empty_callchain =3D { .nr =3D 0, }; =20 +/* + * Returns: +* > 0 : if already queued. + * 0 : if it performed the queuing + * < 0 : if it did not get queued. + */ +static int deferred_request(struct perf_event *event) +{ + struct unwind_work *work =3D &event->unwind_work; + u64 cookie; + + /* Only defer for task events */ + if (!event->ctx->task) + return -EINVAL; + + if ((current->flags & (PF_KTHREAD | PF_USER_WORKER)) || + !user_mode(task_pt_regs(current))) + return -EINVAL; + + return unwind_deferred_request(work, &cookie); +} + struct perf_callchain_entry * perf_callchain(struct perf_event *event, struct pt_regs *regs) { @@ -8204,6 +8288,8 @@ perf_callchain(struct perf_event *event, struct pt_re= gs *regs) bool crosstask =3D event->ctx->task && event->ctx->task !=3D current; const u32 max_stack =3D event->attr.sample_max_stack; struct perf_callchain_entry *callchain; + bool defer_user =3D IS_ENABLED(CONFIG_UNWIND_USER) && user && + event->attr.defer_callchain; =20 if (!current->mm) user =3D false; @@ -8211,8 +8297,21 @@ perf_callchain(struct perf_event *event, struct pt_r= egs *regs) if (!kernel && !user) return &__empty_callchain; =20 - callchain =3D get_perf_callchain(regs, kernel, user, - max_stack, crosstask, true); + /* Disallow cross-task callchains. */ + if (event->ctx->task && event->ctx->task !=3D current) + return &__empty_callchain; + + if (defer_user) { + int ret =3D deferred_request(event); + if (!ret) + local_inc(&event->ctx->nr_no_switch_fast); + else if (ret < 0) + defer_user =3D false; + } + + callchain =3D get_perf_callchain(regs, kernel, user, max_stack, + crosstask, true, defer_user); + return callchain ?: &__empty_callchain; } =20 @@ -13046,6 +13145,13 @@ perf_event_alloc(struct perf_event_attr *attr, int= cpu, } } =20 + if (event->attr.defer_callchain) { + if (task) { + err =3D unwind_deferred_task_init(&event->unwind_work, + perf_event_deferred_task); + } + } + err =3D security_perf_event_alloc(event); if (err) return ERR_PTR(err); diff --git a/tools/include/uapi/linux/perf_event.h b/tools/include/uapi/lin= ux/perf_event.h index 78a362b80027..20b8f890113b 100644 --- a/tools/include/uapi/linux/perf_event.h +++ b/tools/include/uapi/linux/perf_event.h @@ -463,7 +463,8 @@ struct perf_event_attr { inherit_thread : 1, /* children only inherit if cloned with CLONE_THR= EAD */ remove_on_exec : 1, /* event is removed from task on exec */ sigtrap : 1, /* send synchronous SIGTRAP on event */ - __reserved_1 : 26; + defer_callchain: 1, /* generate PERF_RECORD_CALLCHAIN_DEFERRED record= s */ + __reserved_1 : 25; =20 union { __u32 wakeup_events; /* wake up every n events */ @@ -1239,6 +1240,22 @@ enum perf_event_type { */ PERF_RECORD_AUX_OUTPUT_HW_ID =3D 21, =20 + /* + * This user callchain capture was deferred until shortly before + * returning to user space. Previous samples would have kernel + * callchains only and they need to be stitched with this to make full + * callchains. + * + * struct { + * struct perf_event_header header; + * u64 cookie; + * u64 nr; + * u64 ips[nr]; + * struct sample_id sample_id; + * }; + */ + PERF_RECORD_CALLCHAIN_DEFERRED =3D 22, + PERF_RECORD_MAX, /* non-ABI */ }; =20 @@ -1269,6 +1286,7 @@ enum perf_callchain_context { PERF_CONTEXT_HV =3D (__u64)-32, PERF_CONTEXT_KERNEL =3D (__u64)-128, PERF_CONTEXT_USER =3D (__u64)-512, + PERF_CONTEXT_USER_DEFERRED =3D (__u64)-640, =20 PERF_CONTEXT_GUEST =3D (__u64)-2048, PERF_CONTEXT_GUEST_KERNEL =3D (__u64)-2176, --=20 2.50.1 From nobody Wed Oct 8 05:57:14 2025 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 EF8002550AF; Tue, 7 Oct 2025 21:39:31 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1759873172; cv=none; b=LQzfWapsKyFiorNQLLIrf5Nlc6kL6AWY6GqMWELdM75Qg2Jk0nVJISf/7hOLNFFE7tntZUi1hZFdWoxGbAmQZM732B3gpHmK/UdC+uIhRKGIg2FUgbZY7kTA+gsLp+rlwbIRxnBPLg/5bL/0iyihMxDeJ2Giw7niYHSFDg7s6Fc= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1759873172; c=relaxed/simple; bh=VcLags0CJY4WAx/UAO0GeWwJ+C1iWDfDYb8zS+Ww8eE=; h=Message-ID:Date:From:To:Cc:Subject:References:MIME-Version: Content-Type; b=UO5RUOLlpScAW++eYl3RRtzSbEqcLDOP8S5ejIKghkpJRi3vbP4bDkNQ/RPDh6aTIqca0IlmuP04OSm5VDplu+ALxweADUbcE0YW+lwha6sOhZCFDKybJok/tTOZmyeZsVFcTvE3vX9NAxl3+Lyn7c7wF5dPDidUUCMj19cBh1I= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=Sj0VhK6J; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="Sj0VhK6J" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 9158EC4AF10; Tue, 7 Oct 2025 21:39:31 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1759873171; bh=VcLags0CJY4WAx/UAO0GeWwJ+C1iWDfDYb8zS+Ww8eE=; h=Date:From:To:Cc:Subject:References:From; b=Sj0VhK6JcX5HmJh8mbjjgpnqoP3EJYs9UPCtiODpUmj/7PhlPOXmdQG4a8kIn/UHm 5eL03fB4fVSI/T86EuFoRHPeAtz3KRfSEiyQJedlIRgkD0uZ7dEzI+cmy5ThH8RYbX vQy/6fe9YxVVIeqqAq+E45iOpxOYeodXjnjorhOf/HG3AC5BkqY7Lt5eB4OIzvuw7e FrLtU92G6IgD9r86Dthj1teio8dd005ExnwPdGVl/Jlyyy/rSYwd8l/GgzCV8uInq0 rF5lDIIPOpMTxDrWtGv4p2hOSkf27QK4vq9GXMJwCHwyR0BMOoCaGsCKmfrBpiXgin 2YaJ3FfzlFvvw== Received: from rostedt by gandalf with local (Exim 4.98.2) (envelope-from ) id 1v6FQy-00000007Xgh-05Jg; Tue, 07 Oct 2025 17:41:24 -0400 Message-ID: <20251007214123.872765932@kernel.org> User-Agent: quilt/0.68 Date: Tue, 07 Oct 2025 17:40:11 -0400 From: Steven Rostedt To: linux-kernel@vger.kernel.org, linux-trace-kernel@vger.kernel.org, bpf@vger.kernel.org, x86@kernel.org Cc: Masami Hiramatsu , Mathieu Desnoyers , Josh Poimboeuf , Peter Zijlstra , Ingo Molnar , Jiri Olsa , Arnaldo Carvalho de Melo , Namhyung Kim , Thomas Gleixner , Andrii Nakryiko , Indu Bhagat , "Jose E. Marchesi" , Beau Belgrave , Jens Remus , Linus Torvalds , Andrew Morton , Florian Weimer , Sam James , Kees Cook , "Carlos O'Donell" Subject: [PATCH v16 3/4] perf: Have the deferred request record the user context cookie References: <20251007214008.080852573@kernel.org> 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" From: Steven Rostedt When a request to have a deferred unwind is made, have the cookie associated to the user context recorded in the event that represents that request. It is added after the PERF_CONTEXT_USER_DEFERRED in the callchain. That perf context is a marker of where to add the associated user space stack trace in the callchain. Adding the cookie after that marker will not affect the appending of the callchain as it will be overwritten by the user space stack in the perf tool. The cookie will be used to match the cookie that is saved when the deferred callchain is recorded. The perf tool will be able to use the cooking saved at the request to know if the callchain that was recorded when the task goes back to user space is for that event. If there were dropped events after the request was made where it dropped the calltrace that happened when the task went back to user space and then came back into the kernel and a new request was dropped, but then the record started again and it recorded a new callchain going back to user space, this callchain would not be for the initial request. The cookie matching will prevent this scenario from happening. The cookie prevents: record kernel stack trace with PERF_CONTEXT_USER_DEFERRED [ dropped events starts here ] record user stack trace - DROPPED [enters user space ] [exits user space back to the kernel ] record kernel stack trace with PERF_CONTEXT_USER_DEFERRED - DROPPED! [ events stop being dropped here ] record user stack trace Without a differentiating "cookie" identifier, the user space tool will incorrectly attach the last recorded user stack trace to the first kernel stack trace with the PERF_CONTEXT_USER_DEFERRED, as using the TID is not enough to identify this situation. Signed-off-by: Steven Rostedt (Google) --- include/linux/perf_event.h | 2 +- include/uapi/linux/perf_event.h | 5 +++++ kernel/bpf/stackmap.c | 4 ++-- kernel/events/callchain.c | 9 ++++++--- kernel/events/core.c | 12 ++++++------ tools/include/uapi/linux/perf_event.h | 5 +++++ 6 files changed, 25 insertions(+), 12 deletions(-) diff --git a/include/linux/perf_event.h b/include/linux/perf_event.h index 152e3dacff98..a0f95f751b44 100644 --- a/include/linux/perf_event.h +++ b/include/linux/perf_event.h @@ -1723,7 +1723,7 @@ extern void perf_callchain_user(struct perf_callchain= _entry_ctx *entry, struct p extern void perf_callchain_kernel(struct perf_callchain_entry_ctx *entry, = struct pt_regs *regs); extern struct perf_callchain_entry * get_perf_callchain(struct pt_regs *regs, bool kernel, bool user, - u32 max_stack, bool crosstask, bool add_mark, bool defer_user); + u32 max_stack, bool crosstask, bool add_mark, u64 defer_cookie); extern int get_callchain_buffers(int max_stack); extern void put_callchain_buffers(void); extern struct perf_callchain_entry *get_callchain_entry(int *rctx); diff --git a/include/uapi/linux/perf_event.h b/include/uapi/linux/perf_even= t.h index 20b8f890113b..79232e85a8fc 100644 --- a/include/uapi/linux/perf_event.h +++ b/include/uapi/linux/perf_event.h @@ -1282,6 +1282,11 @@ enum perf_bpf_event_type { #define PERF_MAX_STACK_DEPTH 127 #define PERF_MAX_CONTEXTS_PER_STACK 8 =20 +/* + * The PERF_CONTEXT_USER_DEFERRED has two items (context and cookie) + */ +#define PERF_DEFERRED_ITEMS 2 + enum perf_callchain_context { PERF_CONTEXT_HV =3D (__u64)-32, PERF_CONTEXT_KERNEL =3D (__u64)-128, diff --git a/kernel/bpf/stackmap.c b/kernel/bpf/stackmap.c index 339f7cbbcf36..ef6021111fe3 100644 --- a/kernel/bpf/stackmap.c +++ b/kernel/bpf/stackmap.c @@ -315,7 +315,7 @@ BPF_CALL_3(bpf_get_stackid, struct pt_regs *, regs, str= uct bpf_map *, map, max_depth =3D sysctl_perf_event_max_stack; =20 trace =3D get_perf_callchain(regs, kernel, user, max_depth, - false, false, false); + false, false, 0); =20 if (unlikely(!trace)) /* couldn't fetch the stack trace */ @@ -452,7 +452,7 @@ static long __bpf_get_stack(struct pt_regs *regs, struc= t task_struct *task, trace =3D get_callchain_entry_for_task(task, max_depth); else trace =3D get_perf_callchain(regs, kernel, user, max_depth, - crosstask, false, false); + crosstask, false, 0); =20 if (unlikely(!trace) || trace->nr < skip) { if (may_fault) diff --git a/kernel/events/callchain.c b/kernel/events/callchain.c index d0e0da66a164..b9c7e00725d6 100644 --- a/kernel/events/callchain.c +++ b/kernel/events/callchain.c @@ -218,7 +218,7 @@ static void fixup_uretprobe_trampoline_entries(struct p= erf_callchain_entry *entr =20 struct perf_callchain_entry * get_perf_callchain(struct pt_regs *regs, bool kernel, bool user, - u32 max_stack, bool crosstask, bool add_mark, bool defer_user) + u32 max_stack, bool crosstask, bool add_mark, u64 defer_cookie) { struct perf_callchain_entry *entry; struct perf_callchain_entry_ctx ctx; @@ -251,12 +251,15 @@ get_perf_callchain(struct pt_regs *regs, bool kernel,= bool user, regs =3D task_pt_regs(current); } =20 - if (defer_user) { + if (defer_cookie) { /* * Foretell the coming of PERF_RECORD_CALLCHAIN_DEFERRED - * which can be stitched to this one. + * which can be stitched to this one, and add + * the cookie after it (it will be cut off when the + * user stack is copied to the callchain). */ perf_callchain_store_context(&ctx, PERF_CONTEXT_USER_DEFERRED); + perf_callchain_store_context(&ctx, defer_cookie); goto exit_put; } =20 diff --git a/kernel/events/core.c b/kernel/events/core.c index be94b437e7e0..f003a1f9497a 100644 --- a/kernel/events/core.c +++ b/kernel/events/core.c @@ -8262,10 +8262,9 @@ static struct perf_callchain_entry __empty_callchain= =3D { .nr =3D 0, }; * 0 : if it performed the queuing * < 0 : if it did not get queued. */ -static int deferred_request(struct perf_event *event) +static int deferred_request(struct perf_event *event, u64 *defer_cookie) { struct unwind_work *work =3D &event->unwind_work; - u64 cookie; =20 /* Only defer for task events */ if (!event->ctx->task) @@ -8275,7 +8274,7 @@ static int deferred_request(struct perf_event *event) !user_mode(task_pt_regs(current))) return -EINVAL; =20 - return unwind_deferred_request(work, &cookie); + return unwind_deferred_request(work, defer_cookie); } =20 struct perf_callchain_entry * @@ -8288,6 +8287,7 @@ perf_callchain(struct perf_event *event, struct pt_re= gs *regs) bool crosstask =3D event->ctx->task && event->ctx->task !=3D current; const u32 max_stack =3D event->attr.sample_max_stack; struct perf_callchain_entry *callchain; + u64 defer_cookie =3D 0; bool defer_user =3D IS_ENABLED(CONFIG_UNWIND_USER) && user && event->attr.defer_callchain; =20 @@ -8302,15 +8302,15 @@ perf_callchain(struct perf_event *event, struct pt_= regs *regs) return &__empty_callchain; =20 if (defer_user) { - int ret =3D deferred_request(event); + int ret =3D deferred_request(event, &defer_cookie); if (!ret) local_inc(&event->ctx->nr_no_switch_fast); else if (ret < 0) - defer_user =3D false; + defer_cookie =3D 0; } =20 callchain =3D get_perf_callchain(regs, kernel, user, max_stack, - crosstask, true, defer_user); + crosstask, true, defer_cookie); =20 return callchain ?: &__empty_callchain; } diff --git a/tools/include/uapi/linux/perf_event.h b/tools/include/uapi/lin= ux/perf_event.h index 20b8f890113b..79232e85a8fc 100644 --- a/tools/include/uapi/linux/perf_event.h +++ b/tools/include/uapi/linux/perf_event.h @@ -1282,6 +1282,11 @@ enum perf_bpf_event_type { #define PERF_MAX_STACK_DEPTH 127 #define PERF_MAX_CONTEXTS_PER_STACK 8 =20 +/* + * The PERF_CONTEXT_USER_DEFERRED has two items (context and cookie) + */ +#define PERF_DEFERRED_ITEMS 2 + enum perf_callchain_context { PERF_CONTEXT_HV =3D (__u64)-32, PERF_CONTEXT_KERNEL =3D (__u64)-128, --=20 2.50.1 From nobody Wed Oct 8 05:57:14 2025 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 6809E257AC7; Tue, 7 Oct 2025 21:39:32 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1759873172; cv=none; b=Pd20lfsJk3uNAL7VDLpAJF8na8v+a1/mbCgsOAr9upGRPBfarYhHhdq3H+oxnvR48oUWeLdaf4DBtoLfEPXXgmggFhxz0gAbWbitZfoM9tkMeBS6N/v/FitlkgtUsazM6ZPiER37sAmBWE67uIdc9kfiULqTCjOURtnJCg0qvjk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1759873172; c=relaxed/simple; bh=D06TbRvbVUHVeuqDOyzHwBOpkcOYTaaD6lbumAflENI=; h=Message-ID:Date:From:To:Cc:Subject:References:MIME-Version: Content-Type; b=RqKQzoAqJuxvSP5mjrjk99L07cxEF+n2qfcXBA0aG0gBgSzNwzeu2fLc/ZpAc7420IO8hz/PQvCC9W80MxSgVcynYVNpXqWwriCVuRVhsXvtySvnPi5IfugllaOVh1p2HE5J/gXiLAI3YgUDOpCl9ZbpeZLcegeRyX2iVsLXwIY= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=V808DNoc; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="V808DNoc" Received: by smtp.kernel.org (Postfix) with ESMTPSA id BEE00C4CEF1; Tue, 7 Oct 2025 21:39:31 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1759873171; bh=D06TbRvbVUHVeuqDOyzHwBOpkcOYTaaD6lbumAflENI=; h=Date:From:To:Cc:Subject:References:From; b=V808DNochsSz23Wt5h2hCDYkiU+D91eOcVnejAcf29WHh1slPBfvNnY+yvVR+w7NT O+03GDRS8g7rt/Fz+RNivRcaRl/efJAfRUF/XTjb8VIk0+4ZyvlshHK07S55mvOGK+ RV1ec/gcV0vW3hGdJL2X48RBNyGFMrqw1ABKd5qiWhGv8miRbGZEHEOKV/OExtM47H 1RJXBUglBRpqusAV6vp79mZfBxfqnOywWmSbTsxufs6qtfxsu3ZOaJn+5suBEPbGv9 tBPHYgPXv9jZBFcAIznVA42rduebpp1bBUN27ir2Yw+EQ7r3AIuxiy3Wt9lQfT8oKC JFi5ZkcAlG3lg== Received: from rostedt by gandalf with local (Exim 4.98.2) (envelope-from ) id 1v6FQy-00000007XhB-0ows; Tue, 07 Oct 2025 17:41:24 -0400 Message-ID: <20251007214124.043929009@kernel.org> User-Agent: quilt/0.68 Date: Tue, 07 Oct 2025 17:40:12 -0400 From: Steven Rostedt To: linux-kernel@vger.kernel.org, linux-trace-kernel@vger.kernel.org, bpf@vger.kernel.org, x86@kernel.org Cc: Masami Hiramatsu , Mathieu Desnoyers , Josh Poimboeuf , Peter Zijlstra , Ingo Molnar , Jiri Olsa , Arnaldo Carvalho de Melo , Namhyung Kim , Thomas Gleixner , Andrii Nakryiko , Indu Bhagat , "Jose E. Marchesi" , Beau Belgrave , Jens Remus , Linus Torvalds , Andrew Morton , Florian Weimer , Sam James , Kees Cook , "Carlos O'Donell" Subject: [PATCH v16 4/4] perf: Support deferred user callchains for per CPU events References: <20251007214008.080852573@kernel.org> 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" From: Steven Rostedt The deferred unwinder works fine for task events (events that trace only a specific task), as it can use a task_work from an interrupt or NMI and when the task goes back to user space it will call the event's callback to do the deferred unwinding. But for per CPU events things are not so simple. When a per CPU event wants a deferred unwinding to occur, it cannot simply use a task_work as there's a many to many relationship. If the task migrates and another task is scheduled in where the per CPU event wants a deferred unwinding to occur on that task as well, and the task that migrated to another CPU has that CPU's event want to unwind it too, each CPU may need unwinding from more than one task, and each task may have requests from many CPUs. The main issue is that from the kernel point of view, there's currently nothing that associates a per CPU event for one CPU to the per CPU events that cover the other CPUs for a given process. To the kernel, they are all just individual event buffers. This is problematic if a delayed request is made on one CPU and the task migrates to another CPU where the delayed user stack trace will be performed. The kernel needs to know which CPU buffer to add it to that belongs to the same process that initiated the deferred request. To solve this, when a per CPU event is created that has defer_callchain attribute set, it will do a lookup from a global list (unwind_deferred_list), for a perf_unwind_deferred descriptor that has the id that matches the PID of the current task's group_leader. (The process ID for all the threads of a process) If it is not found, then it will create one and add it to the global list. This descriptor contains an array of all possible CPUs, where each element is a perf_unwind_cpu descriptor. The perf_unwind_cpu descriptor has a list of all the per CPU events that is tracing the matching CPU that corresponds to its index in the array, where the events belong to a task that has the same group_leader. It also has a processing bit and rcuwait to handle removal. For each occupied perf_unwind_cpu descriptor in the array, the perf_deferred_unwind descriptor increments its nr_cpu_events. When a perf_unwind_cpu descriptor is empty, the nr_cpu_events is decremented. This is used to know when to free the perf_deferred_unwind descriptor, as when it becomes empty, it is no longer referenced. Finally, the perf_deferred_unwind descriptor has an id that holds the PID of the group_leader for the tasks that the events were created by. When a second (or more) per CPU event is created where the perf_deferred_unwind descriptor already exists, it just adds itself to the perf_unwind_cpu array of that descriptor. Updating the necessary counter. This is used to map different per CPU events to each other based on their group leader PID. Each of these perf_deferred_unwind descriptors have a unwind_work that registers with the deferred unwind infrastructure via unwind_deferred_init(), where it also registers a callback to perf_event_deferred_cpu(). Now when a per CPU event requests a deferred unwinding, it calls unwind_deferred_request() with the associated perf_deferred_unwind descriptor. It is expected that the program that uses this has events on all CPUs, as the deferred trace may not be called on the CPU event that requested it. That is, the task may migrate and its user stack trace will be recorded on the CPU event of the CPU that it exits back to user space on. Signed-off-by: Steven Rostedt (Google) --- include/linux/perf_event.h | 4 + kernel/events/core.c | 260 ++++++++++++++++++++++++++++++++++++- 2 files changed, 260 insertions(+), 4 deletions(-) diff --git a/include/linux/perf_event.h b/include/linux/perf_event.h index a0f95f751b44..b6b7cd6d67a5 100644 --- a/include/linux/perf_event.h +++ b/include/linux/perf_event.h @@ -733,6 +733,7 @@ struct swevent_hlist { struct bpf_prog; struct perf_cgroup; struct perf_buffer; +struct perf_unwind_deferred; =20 struct pmu_event_list { raw_spinlock_t lock; @@ -883,6 +884,9 @@ struct perf_event { =20 struct unwind_work unwind_work; =20 + struct perf_unwind_deferred *unwind_deferred; + struct list_head unwind_list; + atomic_t event_limit; =20 /* address range filters */ diff --git a/kernel/events/core.c b/kernel/events/core.c index f003a1f9497a..f3e48cc4b32d 100644 --- a/kernel/events/core.c +++ b/kernel/events/core.c @@ -5582,10 +5582,192 @@ static bool exclusive_event_installable(struct per= f_event *event, return true; } =20 +/* Holds a list of per CPU events that registered for deferred unwinding */ +struct perf_unwind_cpu { + struct list_head list; + struct rcuwait pending_unwind_wait; + int processing; +}; + +struct perf_unwind_deferred { + struct list_head list; + struct unwind_work unwind_work; + struct perf_unwind_cpu __rcu *cpu_events; + struct rcu_head rcu_head; + int nr_cpu_events; + int id; +}; + +static DEFINE_MUTEX(unwind_deferred_mutex); +static LIST_HEAD(unwind_deferred_list); + +static void perf_event_deferred_cpu(struct unwind_work *work, + struct unwind_stacktrace *trace, u64 cookie); + +/* + * Add a per CPU event. + * + * The deferred callstack can happen on a different CPU than what was + * requested. If one CPU event requests a deferred callstack, but the + * tasks migrates, it will execute on a different CPU and save the + * stack trace to that CPU event. + * + * In order to map all the CPU events with the same application, + * use the current->group_leader->pid as the identifier of what + * events share the same program. + * + * A perf_unwind_deferred descriptor is created for each unique + * group_leader pid, and all the events that have the same group_leader + * pid will be linked to the same deferred descriptor. + * + * If there's no descriptor that matches the current group_leader pid, + * one will be created. + */ +static int perf_add_unwind_deferred(struct perf_event *event) +{ + struct perf_unwind_deferred *defer; + struct perf_unwind_cpu *cpu_events; + int id =3D current->group_leader->pid; + bool found =3D false; + int ret =3D 0; + + if (event->cpu < 0) + return -EINVAL; + + guard(mutex)(&unwind_deferred_mutex); + + list_for_each_entry(defer, &unwind_deferred_list, list) { + if (defer->id =3D=3D id) { + found =3D true; + break; + } + } + + if (!found) { + defer =3D kzalloc(sizeof(*defer), GFP_KERNEL); + if (!defer) + return -ENOMEM; + list_add(&defer->list, &unwind_deferred_list); + defer->id =3D id; + } + + /* + * The deferred desciptor has an array for every CPU. + * Each entry in this array is a link list of all the CPU + * events for the corresponding CPU. This is a quick way to + * find the associated event for a given CPU in + * perf_event_deferred_cpu(). + */ + if (!defer->nr_cpu_events) { + cpu_events =3D kcalloc(num_possible_cpus(), + sizeof(*cpu_events), + GFP_KERNEL); + if (!cpu_events) { + ret =3D -ENOMEM; + goto free; + } + for (int cpu =3D 0; cpu < num_possible_cpus(); cpu++) { + rcuwait_init(&cpu_events[cpu].pending_unwind_wait); + INIT_LIST_HEAD(&cpu_events[cpu].list); + } + + rcu_assign_pointer(defer->cpu_events, cpu_events); + + ret =3D unwind_deferred_init(&defer->unwind_work, + perf_event_deferred_cpu); + if (ret) + goto free; + } + cpu_events =3D rcu_dereference_protected(defer->cpu_events, + lockdep_is_held(&unwind_deferred_mutex)); + + /* + * The defer->nr_cpu_events is the count of the number + * of non-empty lists in the cpu_events array. If the list + * being added to is already occupied, the nr_cpu_events does + * not need to get incremented. + */ + if (list_empty(&cpu_events[event->cpu].list)) + defer->nr_cpu_events++; + list_add_tail_rcu(&event->unwind_list, &cpu_events[event->cpu].list); + + event->unwind_deferred =3D defer; + return 0; +free: + /* Nothing to do if there was already an existing event attached */ + if (found) + return ret; + + list_del(&defer->list); + kfree(cpu_events); + kfree(defer); + return ret; +} + +static void free_unwind_deferred_rcu(struct rcu_head *head) +{ + struct perf_unwind_cpu *cpu_events; + struct perf_unwind_deferred *defer =3D + container_of(head, struct perf_unwind_deferred, rcu_head); + + WARN_ON_ONCE(defer->nr_cpu_events); + /* + * This is called by call_rcu() and there are no more + * references to cpu_events. + */ + cpu_events =3D rcu_dereference_protected(defer->cpu_events, true); + kfree(cpu_events); + kfree(defer); +} + +static void perf_remove_unwind_deferred(struct perf_event *event) +{ + struct perf_unwind_deferred *defer =3D event->unwind_deferred; + struct perf_unwind_cpu *cpu_events, *cpu_unwind; + + if (!defer) + return; + + guard(mutex)(&unwind_deferred_mutex); + list_del_rcu(&event->unwind_list); + + cpu_events =3D rcu_dereference_protected(defer->cpu_events, + lockdep_is_held(&unwind_deferred_mutex)); + cpu_unwind =3D &cpu_events[event->cpu]; + + if (list_empty(&cpu_unwind->list)) { + defer->nr_cpu_events--; + if (!defer->nr_cpu_events) + unwind_deferred_cancel(&defer->unwind_work); + } + + event->unwind_deferred =3D NULL; + + /* + * Make sure perf_event_deferred_cpu() is done with this event. + * That function will set cpu_unwind->processing and then + * call smp_mb() before iterating the list of its events. + * If the event's unwind_deferred is NULL, it will be skipped. + * The smp_mb() in that function matches the mb() in + * rcuwait_wait_event(). + */ + rcuwait_wait_event(&cpu_unwind->pending_unwind_wait, + !cpu_unwind->processing, TASK_UNINTERRUPTIBLE); + + /* Is this still being used by other per CPU events? */ + if (defer->nr_cpu_events) + return; + + list_del(&defer->list); + /* The defer->cpu_events is protected by RCU */ + call_rcu(&defer->rcu_head, free_unwind_deferred_rcu); +} + static void perf_pending_unwind_sync(struct perf_event *event) { struct unwind_work *work =3D &event->unwind_work; =20 + perf_remove_unwind_deferred(event); unwind_deferred_cancel(work); } =20 @@ -5643,6 +5825,54 @@ static void perf_event_deferred_task(struct unwind_w= ork *work, local_dec(&event->ctx->nr_no_switch_fast); } =20 +/* + * Deferred unwinding callback for per CPU events. + * Note, the request for the deferred unwinding may have happened + * on a different CPU. + */ +static void perf_event_deferred_cpu(struct unwind_work *work, + struct unwind_stacktrace *trace, u64 cookie) +{ + struct perf_unwind_deferred *defer =3D + container_of(work, struct perf_unwind_deferred, unwind_work); + struct perf_unwind_cpu *cpu_events, *cpu_unwind; + struct perf_event *event; + int cpu; + + guard(rcu)(); + guard(preempt)(); + + cpu =3D smp_processor_id(); + cpu_events =3D rcu_dereference(defer->cpu_events); + cpu_unwind =3D &cpu_events[cpu]; + + WRITE_ONCE(cpu_unwind->processing, 1); + /* + * Make sure the above is seen before the event->unwind_deferred + * is checked. This matches the mb() in rcuwait_rcu_wait_event() in + * perf_remove_unwind_deferred(). + */ + smp_mb(); + + list_for_each_entry_rcu(event, &cpu_unwind->list, unwind_list) { + /* If unwind_deferred is NULL the event is going away */ + if (unlikely(!event->unwind_deferred)) + continue; + perf_event_callchain_deferred(event, trace, cookie); + /* Only the first CPU event gets the trace */ + break; + } + + /* + * The perf_event_callchain_deferred() must finish before setting + * cpu_unwind->processing to zero. This is also to synchronize + * with the rcuwait in perf_remove_unwind_deferred(). + */ + smp_mb(); + WRITE_ONCE(cpu_unwind->processing, 0); + rcuwait_wake_up(&cpu_unwind->pending_unwind_wait); +} + static void perf_free_addr_filters(struct perf_event *event); =20 /* vs perf_event_alloc() error */ @@ -8256,6 +8486,22 @@ static u64 perf_get_page_size(unsigned long addr) =20 static struct perf_callchain_entry __empty_callchain =3D { .nr =3D 0, }; =20 + +static int deferred_unwind_request(struct perf_unwind_deferred *defer, + u64 *defer_cookie) +{ + int ret; + + ret =3D unwind_deferred_request(&defer->unwind_work, defer_cookie); + + /* + * Return 1 on success or negative on error. + * Do not return zero as not to increment nr_no_switch_fast. + * That's not needed here. + */ + return ret < 0 ? ret : 1; +} + /* * Returns: * > 0 : if already queued. @@ -8265,15 +8511,16 @@ static struct perf_callchain_entry __empty_callchai= n =3D { .nr =3D 0, }; static int deferred_request(struct perf_event *event, u64 *defer_cookie) { struct unwind_work *work =3D &event->unwind_work; - - /* Only defer for task events */ - if (!event->ctx->task) - return -EINVAL; + struct perf_unwind_deferred *defer; =20 if ((current->flags & (PF_KTHREAD | PF_USER_WORKER)) || !user_mode(task_pt_regs(current))) return -EINVAL; =20 + defer =3D READ_ONCE(event->unwind_deferred); + if (defer) + return deferred_unwind_request(defer, defer_cookie); + return unwind_deferred_request(work, defer_cookie); } =20 @@ -13149,6 +13396,11 @@ perf_event_alloc(struct perf_event_attr *attr, int= cpu, if (task) { err =3D unwind_deferred_task_init(&event->unwind_work, perf_event_deferred_task); + } else { + /* Setup unwind deferring for per CPU events */ + err =3D perf_add_unwind_deferred(event); + if (err) + return ERR_PTR(err); } } =20 --=20 2.50.1