| 0/0 |
2026/05/25 17:05 |
flow |
assessment-security |
28m
Results: map[DenialOfService:false Explanation:Based on the analysis of the provided KCSAN data-race report and the kernel
source code, here is the assessment of the bug:
**Bug Mechanism:**
The report indicates a data race on an 8-byte memory location.
- The **write** occurs in `hrtimer_interrupt()` (in `kernel/time/hrtimer.c`),
which updates the clock event device's state. The line number in the report
points to `dev->next_event_forced = 0;`, but the 8-byte write and the values
involved (`0x0000001e0bd33790`, which is ~130 seconds in nanoseconds) confirm
that the actual raced variable is the adjacent `dev->next_event` timestamp
(which is set to `KTIME_MAX` right above it and later reprogrammed).
- The **read** occurs in `print_tickdevice()` (in `kernel/time/timer_list.c`),
which is invoked when user-space reads the `/proc/timer_list` file. It reads
`dev->next_event` locklessly to print the scheduled next event time for
debugging/informational purposes.
**Security Impact:**
1. **Not Exploitable & No Denial of Service:** This is a completely benign data
race. The lockless read is only used to format a string for the
`/proc/timer_list` output. If a race occurs, the worst-case scenario is that a
torn or intermediate timestamp value is printed to the proc file. It does not
corrupt kernel memory, alter control flow, or cause any crashes/hangs.
2. **Not Accessible to Unprivileged Users:** The `/proc/timer_list` file is
created with strict `0400` permissions (read-only for the global root user).
Unprivileged processes cannot open or read this file.
3. **Not Accessible in User Namespaces:** Because `/proc/timer_list` is a global
procfs entry owned by the global root, a process inside a user namespace (even
with namespace-root privileges) cannot bypass the DAC checks to read it.
In conclusion, this is a harmless informational data race restricted to the
global root user, posing no security risk. Exploitable:false FilesystemTrigger:false NetworkTrigger:false PeripheralTrigger:false RemoteTrigger:false Unprivileged:false UserNamespace:false VMGuestTrigger:false VMHostTrigger:false]
|
| 1/1 |
2026/05/25 17:05 |
action |
syz-repro-to-c-repro |
0m
Results:
|
| 2/1 |
2026/05/25 17:05 |
action |
kernel-checkouter |
1m
Results: map[KernelSrc:/app/workdir/cache/src/e06259987e21716562942c92486821a0ed330aec]
|
| 3/1 |
2026/05/25 17:07 |
action |
kernel-builder |
11m
Results: map[KernelObj:/app/workdir/cache/build/efb2441cf361d5b74859879b345e558afd5ee686]
|
| 4/1 |
2026/05/25 17:19 |
action |
codesearch-prepare |
12m
Results: map[Index:codesearch-index]
|
| 5/1 |
2026/05/25 17:31 |
agent |
expert |
2m
Model:
Results: map[DenialOfService:false Exploitable:false FilesystemTrigger:false NetworkTrigger:false PeripheralTrigger:false RemoteTrigger:false Unprivileged:false UserNamespace:false VMGuestTrigger:false VMHostTrigger:false]
Instruction:
You are an experienced Linux kernel security engineer. Your task is to analyze given kernel bug report
and determine its security impact based on the following dimensions.
Use the provided tools to examine the source code, check for capability checks (e.g., capable(), ns_capable()),
and understand the nature of the bug. Analyze the given kernel build and configuration.
You can check the kernel config by grepping ".config" file; you can check kernel cmdline by greeping
".config" file for "CONFIG_CMDLINE=". Assume sysctl parameters have default values.
But analyze for the corresponding production build w/o debugging tools enabled (like KASAN, KMSAN, UBSAN).
Try different strategies when analyzing the bug:
- think of ways in which the vulnerable code is unreachable
- or the other way around: try to come up with different ideas of how an unprivileged user can reach the bug
If still unsure err on the side of the bug being non-exploitable/not-accessible.
In the final reply, provide a reasoning for your assessment.
Analysis dimensions:
* Exploitable:
Determine if the bug can result in memory corruption or elevated privileges.
Memory safety issues are almost always exploitable (KASAN or UBSAN reports for use-after-free, out-of-bounds;
refcounting issues, corrupted lists, etc). When kernel is crashing on a completly wild pointer access
(e.g. user-space address, or non-canonical address, but not on NULL or address corresponding to KASAN shadow
for NULL address), including both data accesses and control tranfers, that's also usually implies possibility
of exploitation. Such reports usually say "unable to handle kernel paging request".
Uses of uninitialized values detected by KMSAN may be exploitable b/c attacker frequently can affect uninit
values with spraying techniques. However, for these exploitabability depends on how exactly the uninit value
is used in the code, and what it affects.
Think of what happens after the bug is triggered. Some bugs cause kernel panic and halt execution,
they are harder to exploit. For example, BUG reports halts the kernel. However, WARNING reports don't halt
execution in production builds. Debug bug detection tools (like KASAN, KMSAN, KCSAN, UBSAN) are also not enabled
in production builds, so attacker can freely exploit these bugs w/o being detected by these tools.
If you see an integer overflow, think how the overflowed value used later (if it's used as allocation size,
or an array index). If you see an out-of-bounds read, think if it's followed by an out-of-bounds write as well.
Some KCSAN data-races may be exploitable by skilled attackers as well. Think what data structures got corrupted
as the result of data races and how. However, note that kernel has lots of "benign" data races that don't lead
to any runtime misbehavior at all.
* Denial Of Service:
Determine if the bug can result in denial-of-service. Most bugs can, since they cause system crash,
hangs, deadlocks, or resource leaks. This is mostly applicable to WARNING bugs that won't cause system crash
in production. For these think what will be consequences of the violation of the kernel assumptions flagged
by the WARNING. In some cases the unexpected condition is also properly handled by the normal control flow
(e.g. with "if (WARN_ON(...))"), these won't cause denial-of-service. If the condition is not handled,
then it may or may not cause denial-of-service.
* Accessible From Unprivileged Processes:
Determine if the bug can be reached from a typical (non-root) user process that does NOT have any special capabilities
(like CAP_SYS_ADMIN, CAP_NET_ADMIN, CAP_NET_RAW, CAP_PERFMON) or access to device nodes restricted to root.
Assume that unprivileged_bpf_disabled=1, that is eBPF loading is not accessible. However, cBPF (classical BPF)
is still accessible to non-root processes.
Assume that user namespaces are not accessible, that is, the process cannot get the mentioned capabilities even
within a new user namespace (checked by ns_capable() function in the kernel sources).
* Accessible From User Namespaces:
Determine if the bug can be reached within a user-namespace where the process has all capabilities
(including CAP_SYS_ADMIN, CAP_NET_ADMIN, CAP_NET_RAW, CAP_PERFMON). Such capabilities are checked with ns_capable()
function in the kernel sources.
* VM Guest Trigger:
Determine if the bug can be triggered from the context of a typical KVM guest (e.g., set up by a QEMU VMM).
Consider accesses to standard Linux host paravirtualized features (virtio-blk, virtio-net, etc.),
and handling of VM exits in the KVM code.
* VM Host Trigger in The Confidetial Computing Context:
Determine if the bug can be triggered in a confidential computing guest kernel from the context of a KVM host.
Consider access to standard Linux guest paravirtualized features (virtio-blk, virtio-net, etc.).
* Ethernet Network Trigger:
Determine if the bug can be triggered by processing ingress network Ethernet traffic, either directly (network stack)
or via drivers exposed to network data.
* Other Remote Trigger:
Determine if the bug can be triggered by processing remote traffic other than Ethernet (Wifi, Bluetooth, NFC, etc).
* Peripheral Trigger:
Determine if the bug can be triggered via an untrusted peripheral device that can be physically plugged
into a system, such as a USB device or a niche hardware driver handling external hardware inputs.
This is particularly important for mobile and desktop environments where users can plug in unknown devices.
* Malicious Filesystem Trigger:
Determine if the bug can be triggered by the kernel mounting and parsing a malicious filesystem image.
This is highly critical for Desktop and Mobile environments where external media or downloaded images
might be auto-mounted.
Don't make assumptions about the kernel source code (it may be different from what you assume it is).
Extensively use the provided code access tools (codesearch-*, git-*, grepper, etc)
to examine the actual source code, and confirm any assumptions.
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt:
The kernel bug report is:
==================================================================
BUG: KCSAN: data-race in hrtimer_interrupt / print_tickdevice
write to 0xffff888237d17ba0 of 8 bytes by interrupt on cpu 1:
hrtimer_interrupt+0x69/0x850 kernel/time/hrtimer.c:2092
local_apic_timer_interrupt arch/x86/kernel/apic/apic.c:1050 [inline]
__sysvec_apic_timer_interrupt+0x5f/0x1c0 arch/x86/kernel/apic/apic.c:1067
instr_sysvec_apic_timer_interrupt arch/x86/kernel/apic/apic.c:1061 [inline]
sysvec_apic_timer_interrupt+0x6f/0x80 arch/x86/kernel/apic/apic.c:1061
asm_sysvec_apic_timer_interrupt+0x1a/0x20 arch/x86/include/asm/idtentry.h:697
__sanitizer_cov_trace_pc+0x5c/0x70 kernel/kcov.c:233
xas_next_entry include/linux/xarray.h:1736 [inline]
next_uptodate_folio+0x172/0x7e0 mm/filemap.c:3705
filemap_map_pages+0xa00/0xea0 mm/filemap.c:3940
do_fault_around mm/memory.c:5867 [inline]
do_read_fault mm/memory.c:5900 [inline]
do_fault mm/memory.c:6043 [inline]
do_pte_missing mm/memory.c:4566 [inline]
handle_pte_fault mm/memory.c:6427 [inline]
__handle_mm_fault mm/memory.c:6565 [inline]
handle_mm_fault+0x1508/0x2e70 mm/memory.c:6734
faultin_page mm/gup.c:1126 [inline]
__get_user_pages+0x1290/0x1f10 mm/gup.c:1428
populate_vma_page_range mm/gup.c:1860 [inline]
__mm_populate+0x242/0x390 mm/gup.c:1963
mm_populate include/linux/mm.h:4137 [inline]
vm_mmap_pgoff+0x23b/0x2d0 mm/util.c:586
ksys_mmap_pgoff+0xc1/0x310 mm/mmap.c:606
x64_sys_call+0x14df/0x3020 arch/x86/include/generated/asm/syscalls_64.h:10
do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
do_syscall_64+0x12c/0x3b0 arch/x86/entry/syscall_64.c:94
entry_SYSCALL_64_after_hwframe+0x77/0x7f
read to 0xffff888237d17ba0 of 8 bytes by task 6224 on cpu 0:
print_tickdevice+0x142/0x340 kernel/time/timer_list.c:204
timer_list_show+0x6c/0x170 kernel/time/timer_list.c:296
seq_read_iter+0x636/0x940 fs/seq_file.c:273
proc_reg_read_iter+0x110/0x180 fs/proc/inode.c:299
copy_splice_read+0x471/0x6c0 fs/splice.c:362
do_splice_read fs/splice.c:980 [inline]
splice_direct_to_actor+0x26e/0x670 fs/splice.c:1084
do_splice_direct_actor fs/splice.c:1202 [inline]
do_splice_direct+0x119/0x1a0 fs/splice.c:1228
do_sendfile+0x382/0x650 fs/read_write.c:1372
__do_sys_sendfile64 fs/read_write.c:1433 [inline]
__se_sys_sendfile64 fs/read_write.c:1419 [inline]
__x64_sys_sendfile64+0x105/0x150 fs/read_write.c:1419
x64_sys_call+0x2dc4/0x3020 arch/x86/include/generated/asm/syscalls_64.h:41
do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
do_syscall_64+0x12c/0x3b0 arch/x86/entry/syscall_64.c:94
entry_SYSCALL_64_after_hwframe+0x77/0x7f
value changed: 0x0000001e0bd33790 -> 0x0000001e0bfaba80
Reported by Kernel Concurrency Sanitizer on:
CPU: 0 UID: 0 PID: 6224 Comm: syz.2.871 Tainted: G W syzkaller #0 PREEMPT(full)
Tainted: [W]=WARN
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 04/18/2026
==================================================================
Reply: Based on the analysis of the provided KCSAN data-race report and the kernel source code, here is the assessment of the bug:
**Bug Mechanism:**
The report indicates a data race on an 8-byte memory location.
- The **write** occurs in `hrtimer_interrupt()` (in `kernel/time/hrtimer.c`), which updates the clock event device's state. The line number in the report points to `dev->next_event_forced = 0;`, but the 8-byte write and the values involved (`0x0000001e0bd33790`, which is ~130 seconds in nanoseconds) confirm that the actual raced variable is the adjacent `dev->next_event` timestamp (which is set to `KTIME_MAX` right above it and later reprogrammed).
- The **read** occurs in `print_tickdevice()` (in `kernel/time/timer_list.c`), which is invoked when user-space reads the `/proc/timer_list` file. It reads `dev->next_event` locklessly to print the scheduled next event time for debugging/informational purposes.
**Security Impact:**
1. **Not Exploitable & No Denial of Service:** This is a completely benign data race. The lockless read is only used to format a string for the `/proc/timer_list` output. If a race occurs, the worst-case scenario is that a torn or intermediate timestamp value is printed to the proc file. It does not corrupt kernel memory, alter control flow, or cause any crashes/hangs.
2. **Not Accessible to Unprivileged Users:** The `/proc/timer_list` file is created with strict `0400` permissions (read-only for the global root user). Unprivileged processes cannot open or read this file.
3. **Not Accessible in User Namespaces:** Because `/proc/timer_list` is a global procfs entry owned by the global root, a process inside a user namespace (even with namespace-root privileges) cannot bypass the DAC checks to read it.
In conclusion, this is a harmless informational data race restricted to the global root user, posing no security risk.
|
| 6/2 |
2026/05/25 17:31 |
llm |
expert |
0m
Model:
Tokens:
input: 6884
output: 18
thoughts: 115
Thoughts: **Analyzing a KCSAN Data-Race Report**
Okay, so I've got a KCSAN data-race report here. Looks like there's a race condition. Specifically, `hrtimer_interrupt` in `kernel/time/hrtimer.c` is writing to some memory location, and concurrently, `print_tickdevice` in `kernel/time/timer_list.c` is reading from it. This is a classic race scenario, and we need to understand the interaction better.
The write operation is happening at line 2092 in `kernel/time/hrtimer.c`, which makes things a bit easier to pinpoint. Now I need to dive into that code and understand precisely what memory location is being written to within `hrtimer_interrupt` at that line.
|
| 7/2 |
2026/05/25 17:31 |
tool |
grepper |
0m
Args: map[Expression:hrtimer_interrupt]
Results: map[Output:Documentation/tools/rtla/rtla-timerlat-top.rst=49=higher is found::
--
Documentation/tools/rtla/rtla-timerlat-top.rst-87- -> __hrtimer_run_queues
Documentation/tools/rtla/rtla-timerlat-top.rst:88: -> hrtimer_interrupt
Documentation/tools/rtla/rtla-timerlat-top.rst-89- -> __sysvec_apic_timer_interrupt
--
Documentation/trace/ftrace.rst=1761=was over.
--
Documentation/trace/ftrace.rst-1793- bash-1994 1d.h1 13us : exit_idle <-smp_apic_timer_interrupt
Documentation/trace/ftrace.rst:1794: bash-1994 1d.h1 13us : hrtimer_interrupt <-smp_apic_timer_interrupt
Documentation/trace/ftrace.rst:1795: bash-1994 1d.h1 13us : _raw_spin_lock <-hrtimer_interrupt
Documentation/trace/ftrace.rst-1796- bash-1994 1d.h1 14us : add_preempt_count <-_raw_spin_lock
Documentation/trace/ftrace.rst:1797: bash-1994 1d.h2 14us : ktime_get_update_offsets <-hrtimer_interrupt
Documentation/trace/ftrace.rst-1798- [...]
--
Documentation/trace/ftrace.rst=2160=Doing the same with chrt -r 5 and function-trace set.
--
Documentation/trace/ftrace.rst-2193- <idle>-0 3dNh1 6us : add_preempt_count <-_raw_spin_lock
Documentation/trace/ftrace.rst:2194: <idle>-0 3dNh2 7us : _raw_spin_unlock <-hrtimer_interrupt
Documentation/trace/ftrace.rst-2195- <idle>-0 3dNh2 7us : sub_preempt_count <-_raw_spin_unlock
Documentation/trace/ftrace.rst:2196: <idle>-0 3dNh1 7us : tick_program_event <-hrtimer_interrupt
Documentation/trace/ftrace.rst-2197- <idle>-0 3dNh1 7us : clockevents_program_event <-tick_program_event
--
Documentation/trace/ftrace.rst=3030=listed in:
--
Documentation/trace/ftrace.rst-3044-
Documentation/trace/ftrace.rst:3045:If I am only interested in sys_nanosleep and hrtimer_interrupt::
Documentation/trace/ftrace.rst-3046-
Documentation/trace/ftrace.rst:3047: # echo sys_nanosleep hrtimer_interrupt > set_ftrace_filter
Documentation/trace/ftrace.rst-3048- # echo function > current_tracer
--
Documentation/trace/ftrace.rst-3064- usleep-2665 [001] .... 4186.475355: sys_nanosleep <-system_call_fastpath
Documentation/trace/ftrace.rst:3065: <idle>-0 [001] d.h1 4186.475409: hrtimer_interrupt <-smp_apic_timer_interrupt
Documentation/trace/ftrace.rst:3066: usleep-2665 [001] d.h1 4186.475426: hrtimer_interrupt <-smp_apic_timer_interrupt
Documentation/trace/ftrace.rst:3067: <idle>-0 [003] d.h1 4186.475426: hrtimer_interrupt <-smp_apic_timer_interrupt
Documentation/trace/ftrace.rst:3068: <idle>-0 [002] d.h1 4186.475427: hrtimer_interrupt <-smp_apic_timer_interrupt
Documentation/trace/ftrace.rst-3069-
Documentation/trace/ftrace.rst=3070=To see which functions are being traced, you can cat the file:
--
Documentation/trace/ftrace.rst-3073- # cat set_ftrace_filter
Documentation/trace/ftrace.rst:3074: hrtimer_interrupt
Documentation/trace/ftrace.rst-3075- sys_nanosleep
--
Documentation/trace/ftrace.rst=3120=Notice that we lost the sys_nanosleep.
--
Documentation/trace/ftrace.rst-3133- hrtimer_get_next_event
Documentation/trace/ftrace.rst:3134: hrtimer_interrupt
Documentation/trace/ftrace.rst-3135- hrtimer_nanosleep
--
Documentation/trace/ftrace.rst=3153=Again, now we want to append.
--
Documentation/trace/ftrace.rst-3171- hrtimer_get_next_event
Documentation/trace/ftrace.rst:3172: hrtimer_interrupt
Documentation/trace/ftrace.rst-3173- sys_nanosleep
--
Documentation/trace/timerlat-tracer.rst=142=irq disabled. For example::
--
Documentation/trace/timerlat-tracer.rst-156- => __hrtimer_run_queues
Documentation/trace/timerlat-tracer.rst:157: => hrtimer_interrupt
Documentation/trace/timerlat-tracer.rst-158- => __sysvec_apic_timer_interrupt
--
drivers/gpu/drm/ci/xfails/msm-sm8350-hdk-skips.txt=20=msm/msm_mapping@ring
--
drivers/gpu/drm/ci/xfails/msm-sm8350-hdk-skips.txt-163-# [ 228.514087] __hrtimer_run_queues+0x3b0/0x40c
drivers/gpu/drm/ci/xfails/msm-sm8350-hdk-skips.txt:164:# [ 228.518612] hrtimer_interrupt+0xe8/0x248
drivers/gpu/drm/ci/xfails/msm-sm8350-hdk-skips.txt-165-# [ 228.522777] arch_timer_handler_virt+0x2c/0x44
--
include/linux/entry-common.h=72=static __always_inline long syscall_trace_enter(struct pt_regs *regs, unsigned long work)
--
include/linux/entry-common.h-88- * the CPU. The work stops the slice timer to avoid an extra round
include/linux/entry-common.h:89: * through hrtimer_interrupt().
include/linux/entry-common.h-90- */
--
include/linux/hrtimer.h=128=struct clock_event_device;
include/linux/hrtimer.h-129-
include/linux/hrtimer.h:130:extern void hrtimer_interrupt(struct clock_event_device *dev);
include/linux/hrtimer.h-131-
--
include/linux/hrtimer_defs.h=38=enum hrtimer_base_type {
--
include/linux/hrtimer_defs.h-64- * @nr_hangs: Total number of hrtimer interrupt hangs
include/linux/hrtimer_defs.h:65: * @max_hang_time: Maximum time spent in hrtimer_interrupt
include/linux/hrtimer_defs.h-66- * @softirq_expiry_lock: Lock which is taken while softirq based hrtimer are expired
--
include/linux/nmi.h=122=void lockup_detector_reconfigure(void);
--
include/linux/nmi.h-124-#ifdef CONFIG_HARDLOCKUP_DETECTOR_BUDDY
include/linux/nmi.h:125:void watchdog_buddy_check_hardlockup(int hrtimer_interrupts);
include/linux/nmi.h-126-#else
include/linux/nmi.h:127:static inline void watchdog_buddy_check_hardlockup(int hrtimer_interrupts) {}
include/linux/nmi.h-128-#endif
--
kernel/rseq.c=631=static void rseq_cancel_slice_extension_timer(void)
--
kernel/rseq.c-640- * expensive as it has to reprogram the hardware, but that's less
kernel/rseq.c:641: * expensive than going through a full hrtimer_interrupt() cycle
kernel/rseq.c-642- * for nothing.
--
kernel/time/hrtimer.c=587=static void hrtimer_bases_first(struct hrtimer_cpu_base *cpu_base,unsigned int active,
--
kernel/time/hrtimer.c-604- * but does not set cpu_base::*expires_next, that is done by
kernel/time/hrtimer.c:605: * hrtimer[_force]_reprogram and hrtimer_interrupt only. When updating
kernel/time/hrtimer.c-606- * cpu_base::*expires_next right away, reprogramming logic would no longer
--
kernel/time/hrtimer.c=1888=static void __run_hrtimer(struct hrtimer_cpu_base *cpu_base, struct hrtimer_clock_base *base,
--
kernel/time/hrtimer.c-1938- * we do not reprogram the event hardware. Happens either in
kernel/time/hrtimer.c:1939: * hrtimer_start_range_ns() or in hrtimer_interrupt()
kernel/time/hrtimer.c-1940- *
--
kernel/time/hrtimer.c=2062=static __always_inline void
kernel/time/hrtimer.c:2063:hrtimer_interrupt_rearm(struct hrtimer_cpu_base *cpu_base, ktime_t expires_next)
kernel/time/hrtimer.c-2064-{
kernel/time/hrtimer.c:2065: /* hrtimer_interrupt() just re-evaluated the first expiring timer */
kernel/time/hrtimer.c-2066- cpu_base->deferred_needs_update = false;
--
kernel/time/hrtimer.c=2072=static __always_inline void
kernel/time/hrtimer.c:2073:hrtimer_interrupt_rearm(struct hrtimer_cpu_base *cpu_base, ktime_t expires_next)
kernel/time/hrtimer.c-2074-{
--
kernel/time/hrtimer.c-2082- */
kernel/time/hrtimer.c:2083:void hrtimer_interrupt(struct clock_event_device *dev)
kernel/time/hrtimer.c-2084-{
--
kernel/time/hrtimer.c-2137-
kernel/time/hrtimer.c:2138: hrtimer_interrupt_rearm(cpu_base, expires_next);
kernel/time/hrtimer.c-2139- raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
--
kernel/time/hrtimer.c=2438=static void migrate_hrtimer_list(struct hrtimer_clock_base *old_base,
--
kernel/time/hrtimer.c-2459- * expires before the earliest on this CPU, but we run
kernel/time/hrtimer.c:2460: * hrtimer_interrupt after we migrated everything to
kernel/time/hrtimer.c-2461- * sort out already expired timers and reprogram the
--
kernel/time/tick-broadcast-hrtimer.c=20=static int bc_shutdown(struct clock_event_device *evt)
--
kernel/time/tick-broadcast-hrtimer.c-27- * lock(broadcast_lock);
kernel/time/tick-broadcast-hrtimer.c:28: * hrtimer_interrupt()
kernel/time/tick-broadcast-hrtimer.c-29- * bc_handler()
--
kernel/time/tick-oneshot.c=142=int tick_init_highres(void)
kernel/time/tick-oneshot.c-143-{
kernel/time/tick-oneshot.c:144: return tick_switch_to_oneshot(hrtimer_interrupt);
kernel/time/tick-oneshot.c-145-}
--
kernel/time/timekeeping.c=2697=void do_timer(unsigned long ticks)
--
kernel/time/timekeeping.c-2713- *
kernel/time/timekeeping.c:2714: * Called from hrtimer_interrupt() or retrigger_next_event()
kernel/time/timekeeping.c-2715- */
--
kernel/watchdog.c=139=__setup("nmi_watchdog=", hardlockup_panic_setup);
--
kernel/watchdog.c-144-
kernel/watchdog.c:145:static DEFINE_PER_CPU(atomic_t, hrtimer_interrupts);
kernel/watchdog.c:146:static DEFINE_PER_CPU(int, hrtimer_interrupts_saved);
kernel/watchdog.c:147:static DEFINE_PER_CPU(int, hrtimer_interrupts_missed);
kernel/watchdog.c-148-static DEFINE_PER_CPU(bool, watchdog_hardlockup_warned);
--
kernel/watchdog.c=170=static void watchdog_hardlockup_update_reset(unsigned int cpu)
kernel/watchdog.c-171-{
kernel/watchdog.c:172: int hrint = atomic_read(&per_cpu(hrtimer_interrupts, cpu));
kernel/watchdog.c-173-
--
kernel/watchdog.c-175- * NOTE: we don't need any fancy atomic_t or READ_ONCE/WRITE_ONCE
kernel/watchdog.c:176: * for hrtimer_interrupts_saved. hrtimer_interrupts_saved is
kernel/watchdog.c-177- * written/read by a single CPU.
kernel/watchdog.c-178- */
kernel/watchdog.c:179: per_cpu(hrtimer_interrupts_saved, cpu) = hrint;
kernel/watchdog.c:180: per_cpu(hrtimer_interrupts_missed, cpu) = 0;
kernel/watchdog.c-181-}
--
kernel/watchdog.c=183=static bool is_hardlockup(unsigned int cpu)
kernel/watchdog.c-184-{
kernel/watchdog.c:185: int hrint = atomic_read(&per_cpu(hrtimer_interrupts, cpu));
kernel/watchdog.c-186-
kernel/watchdog.c:187: if (per_cpu(hrtimer_interrupts_saved, cpu) != hrint) {
kernel/watchdog.c-188- watchdog_hardlockup_update_reset(cpu);
--
kernel/watchdog.c-191-
kernel/watchdog.c:192: per_cpu(hrtimer_interrupts_missed, cpu)++;
kernel/watchdog.c:193: if (per_cpu(hrtimer_interrupts_missed, cpu) % watchdog_hardlockup_miss_thresh)
kernel/watchdog.c-194- return false;
--
kernel/watchdog.c=199=static void watchdog_hardlockup_kick(void)
--
kernel/watchdog.c-202-
kernel/watchdog.c:203: new_interrupts = atomic_inc_return(this_cpu_ptr(&hrtimer_interrupts));
kernel/watchdog.c-204- watchdog_buddy_check_hardlockup(new_interrupts);
--
kernel/watchdog_buddy.c=62=void watchdog_hardlockup_disable(unsigned int cpu)
--
kernel/watchdog_buddy.c-68- * checking the one after this one. If this CPU just finished checking
kernel/watchdog_buddy.c:69: * the next CPU and updating hrtimer_interrupts_saved, and then the
kernel/watchdog_buddy.c-70- * previous CPU checks it within one sample period, it will trigger a
--
kernel/watchdog_buddy.c-85-
kernel/watchdog_buddy.c:86:void watchdog_buddy_check_hardlockup(int hrtimer_interrupts)
kernel/watchdog_buddy.c-87-{
]
|
| 8/2 |
2026/05/25 17:31 |
llm |
expert |
0m
Model:
Tokens:
input: 11504
output: 18
thoughts: 22
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Diving into the High-Resolution Timer Implementation**
Alright, let's drill down. I'm focusing my attention on `kernel/time/hrtimer.c` – specifically, I'm going to take a hard look at line 2092. This is where the rubber meets the road, so to speak, in understanding the subtleties of how the high-resolution timer is behaving. My intuition tells me that some aspect of the observed behavior I'm investigating will likely manifest at this location. I'm anticipating some critical operation concerning the timer's state, interrupt handling, or the queue management. Given the surrounding code, I'm expecting to either find the source of the issue, or perhaps be directed to other functions, from where I can go further.
|
| 9/2 |
2026/05/25 17:31 |
tool |
grepper |
0m
Args: map[Expression:hrtimer_interrupt]
Results: map[Output:Documentation/tools/rtla/rtla-timerlat-top.rst=49=higher is found::
--
Documentation/tools/rtla/rtla-timerlat-top.rst-87- -> __hrtimer_run_queues
Documentation/tools/rtla/rtla-timerlat-top.rst:88: -> hrtimer_interrupt
Documentation/tools/rtla/rtla-timerlat-top.rst-89- -> __sysvec_apic_timer_interrupt
--
Documentation/trace/ftrace.rst=1761=was over.
--
Documentation/trace/ftrace.rst-1793- bash-1994 1d.h1 13us : exit_idle <-smp_apic_timer_interrupt
Documentation/trace/ftrace.rst:1794: bash-1994 1d.h1 13us : hrtimer_interrupt <-smp_apic_timer_interrupt
Documentation/trace/ftrace.rst:1795: bash-1994 1d.h1 13us : _raw_spin_lock <-hrtimer_interrupt
Documentation/trace/ftrace.rst-1796- bash-1994 1d.h1 14us : add_preempt_count <-_raw_spin_lock
Documentation/trace/ftrace.rst:1797: bash-1994 1d.h2 14us : ktime_get_update_offsets <-hrtimer_interrupt
Documentation/trace/ftrace.rst-1798- [...]
--
Documentation/trace/ftrace.rst=2160=Doing the same with chrt -r 5 and function-trace set.
--
Documentation/trace/ftrace.rst-2193- <idle>-0 3dNh1 6us : add_preempt_count <-_raw_spin_lock
Documentation/trace/ftrace.rst:2194: <idle>-0 3dNh2 7us : _raw_spin_unlock <-hrtimer_interrupt
Documentation/trace/ftrace.rst-2195- <idle>-0 3dNh2 7us : sub_preempt_count <-_raw_spin_unlock
Documentation/trace/ftrace.rst:2196: <idle>-0 3dNh1 7us : tick_program_event <-hrtimer_interrupt
Documentation/trace/ftrace.rst-2197- <idle>-0 3dNh1 7us : clockevents_program_event <-tick_program_event
--
Documentation/trace/ftrace.rst=3030=listed in:
--
Documentation/trace/ftrace.rst-3044-
Documentation/trace/ftrace.rst:3045:If I am only interested in sys_nanosleep and hrtimer_interrupt::
Documentation/trace/ftrace.rst-3046-
Documentation/trace/ftrace.rst:3047: # echo sys_nanosleep hrtimer_interrupt > set_ftrace_filter
Documentation/trace/ftrace.rst-3048- # echo function > current_tracer
--
Documentation/trace/ftrace.rst-3064- usleep-2665 [001] .... 4186.475355: sys_nanosleep <-system_call_fastpath
Documentation/trace/ftrace.rst:3065: <idle>-0 [001] d.h1 4186.475409: hrtimer_interrupt <-smp_apic_timer_interrupt
Documentation/trace/ftrace.rst:3066: usleep-2665 [001] d.h1 4186.475426: hrtimer_interrupt <-smp_apic_timer_interrupt
Documentation/trace/ftrace.rst:3067: <idle>-0 [003] d.h1 4186.475426: hrtimer_interrupt <-smp_apic_timer_interrupt
Documentation/trace/ftrace.rst:3068: <idle>-0 [002] d.h1 4186.475427: hrtimer_interrupt <-smp_apic_timer_interrupt
Documentation/trace/ftrace.rst-3069-
Documentation/trace/ftrace.rst=3070=To see which functions are being traced, you can cat the file:
--
Documentation/trace/ftrace.rst-3073- # cat set_ftrace_filter
Documentation/trace/ftrace.rst:3074: hrtimer_interrupt
Documentation/trace/ftrace.rst-3075- sys_nanosleep
--
Documentation/trace/ftrace.rst=3120=Notice that we lost the sys_nanosleep.
--
Documentation/trace/ftrace.rst-3133- hrtimer_get_next_event
Documentation/trace/ftrace.rst:3134: hrtimer_interrupt
Documentation/trace/ftrace.rst-3135- hrtimer_nanosleep
--
Documentation/trace/ftrace.rst=3153=Again, now we want to append.
--
Documentation/trace/ftrace.rst-3171- hrtimer_get_next_event
Documentation/trace/ftrace.rst:3172: hrtimer_interrupt
Documentation/trace/ftrace.rst-3173- sys_nanosleep
--
Documentation/trace/timerlat-tracer.rst=142=irq disabled. For example::
--
Documentation/trace/timerlat-tracer.rst-156- => __hrtimer_run_queues
Documentation/trace/timerlat-tracer.rst:157: => hrtimer_interrupt
Documentation/trace/timerlat-tracer.rst-158- => __sysvec_apic_timer_interrupt
--
drivers/gpu/drm/ci/xfails/msm-sm8350-hdk-skips.txt=20=msm/msm_mapping@ring
--
drivers/gpu/drm/ci/xfails/msm-sm8350-hdk-skips.txt-163-# [ 228.514087] __hrtimer_run_queues+0x3b0/0x40c
drivers/gpu/drm/ci/xfails/msm-sm8350-hdk-skips.txt:164:# [ 228.518612] hrtimer_interrupt+0xe8/0x248
drivers/gpu/drm/ci/xfails/msm-sm8350-hdk-skips.txt-165-# [ 228.522777] arch_timer_handler_virt+0x2c/0x44
--
include/linux/entry-common.h=72=static __always_inline long syscall_trace_enter(struct pt_regs *regs, unsigned long work)
--
include/linux/entry-common.h-88- * the CPU. The work stops the slice timer to avoid an extra round
include/linux/entry-common.h:89: * through hrtimer_interrupt().
include/linux/entry-common.h-90- */
--
include/linux/hrtimer.h=128=struct clock_event_device;
include/linux/hrtimer.h-129-
include/linux/hrtimer.h:130:extern void hrtimer_interrupt(struct clock_event_device *dev);
include/linux/hrtimer.h-131-
--
include/linux/hrtimer_defs.h=38=enum hrtimer_base_type {
--
include/linux/hrtimer_defs.h-64- * @nr_hangs: Total number of hrtimer interrupt hangs
include/linux/hrtimer_defs.h:65: * @max_hang_time: Maximum time spent in hrtimer_interrupt
include/linux/hrtimer_defs.h-66- * @softirq_expiry_lock: Lock which is taken while softirq based hrtimer are expired
--
include/linux/nmi.h=122=void lockup_detector_reconfigure(void);
--
include/linux/nmi.h-124-#ifdef CONFIG_HARDLOCKUP_DETECTOR_BUDDY
include/linux/nmi.h:125:void watchdog_buddy_check_hardlockup(int hrtimer_interrupts);
include/linux/nmi.h-126-#else
include/linux/nmi.h:127:static inline void watchdog_buddy_check_hardlockup(int hrtimer_interrupts) {}
include/linux/nmi.h-128-#endif
--
kernel/rseq.c=631=static void rseq_cancel_slice_extension_timer(void)
--
kernel/rseq.c-640- * expensive as it has to reprogram the hardware, but that's less
kernel/rseq.c:641: * expensive than going through a full hrtimer_interrupt() cycle
kernel/rseq.c-642- * for nothing.
--
kernel/time/hrtimer.c=587=static void hrtimer_bases_first(struct hrtimer_cpu_base *cpu_base,unsigned int active,
--
kernel/time/hrtimer.c-604- * but does not set cpu_base::*expires_next, that is done by
kernel/time/hrtimer.c:605: * hrtimer[_force]_reprogram and hrtimer_interrupt only. When updating
kernel/time/hrtimer.c-606- * cpu_base::*expires_next right away, reprogramming logic would no longer
--
kernel/time/hrtimer.c=1888=static void __run_hrtimer(struct hrtimer_cpu_base *cpu_base, struct hrtimer_clock_base *base,
--
kernel/time/hrtimer.c-1938- * we do not reprogram the event hardware. Happens either in
kernel/time/hrtimer.c:1939: * hrtimer_start_range_ns() or in hrtimer_interrupt()
kernel/time/hrtimer.c-1940- *
--
kernel/time/hrtimer.c=2062=static __always_inline void
kernel/time/hrtimer.c:2063:hrtimer_interrupt_rearm(struct hrtimer_cpu_base *cpu_base, ktime_t expires_next)
kernel/time/hrtimer.c-2064-{
kernel/time/hrtimer.c:2065: /* hrtimer_interrupt() just re-evaluated the first expiring timer */
kernel/time/hrtimer.c-2066- cpu_base->deferred_needs_update = false;
--
kernel/time/hrtimer.c=2072=static __always_inline void
kernel/time/hrtimer.c:2073:hrtimer_interrupt_rearm(struct hrtimer_cpu_base *cpu_base, ktime_t expires_next)
kernel/time/hrtimer.c-2074-{
--
kernel/time/hrtimer.c-2082- */
kernel/time/hrtimer.c:2083:void hrtimer_interrupt(struct clock_event_device *dev)
kernel/time/hrtimer.c-2084-{
--
kernel/time/hrtimer.c-2137-
kernel/time/hrtimer.c:2138: hrtimer_interrupt_rearm(cpu_base, expires_next);
kernel/time/hrtimer.c-2139- raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
--
kernel/time/hrtimer.c=2438=static void migrate_hrtimer_list(struct hrtimer_clock_base *old_base,
--
kernel/time/hrtimer.c-2459- * expires before the earliest on this CPU, but we run
kernel/time/hrtimer.c:2460: * hrtimer_interrupt after we migrated everything to
kernel/time/hrtimer.c-2461- * sort out already expired timers and reprogram the
--
kernel/time/tick-broadcast-hrtimer.c=20=static int bc_shutdown(struct clock_event_device *evt)
--
kernel/time/tick-broadcast-hrtimer.c-27- * lock(broadcast_lock);
kernel/time/tick-broadcast-hrtimer.c:28: * hrtimer_interrupt()
kernel/time/tick-broadcast-hrtimer.c-29- * bc_handler()
--
kernel/time/tick-oneshot.c=142=int tick_init_highres(void)
kernel/time/tick-oneshot.c-143-{
kernel/time/tick-oneshot.c:144: return tick_switch_to_oneshot(hrtimer_interrupt);
kernel/time/tick-oneshot.c-145-}
--
kernel/time/timekeeping.c=2697=void do_timer(unsigned long ticks)
--
kernel/time/timekeeping.c-2713- *
kernel/time/timekeeping.c:2714: * Called from hrtimer_interrupt() or retrigger_next_event()
kernel/time/timekeeping.c-2715- */
--
kernel/watchdog.c=139=__setup("nmi_watchdog=", hardlockup_panic_setup);
--
kernel/watchdog.c-144-
kernel/watchdog.c:145:static DEFINE_PER_CPU(atomic_t, hrtimer_interrupts);
kernel/watchdog.c:146:static DEFINE_PER_CPU(int, hrtimer_interrupts_saved);
kernel/watchdog.c:147:static DEFINE_PER_CPU(int, hrtimer_interrupts_missed);
kernel/watchdog.c-148-static DEFINE_PER_CPU(bool, watchdog_hardlockup_warned);
--
kernel/watchdog.c=170=static void watchdog_hardlockup_update_reset(unsigned int cpu)
kernel/watchdog.c-171-{
kernel/watchdog.c:172: int hrint = atomic_read(&per_cpu(hrtimer_interrupts, cpu));
kernel/watchdog.c-173-
--
kernel/watchdog.c-175- * NOTE: we don't need any fancy atomic_t or READ_ONCE/WRITE_ONCE
kernel/watchdog.c:176: * for hrtimer_interrupts_saved. hrtimer_interrupts_saved is
kernel/watchdog.c-177- * written/read by a single CPU.
kernel/watchdog.c-178- */
kernel/watchdog.c:179: per_cpu(hrtimer_interrupts_saved, cpu) = hrint;
kernel/watchdog.c:180: per_cpu(hrtimer_interrupts_missed, cpu) = 0;
kernel/watchdog.c-181-}
--
kernel/watchdog.c=183=static bool is_hardlockup(unsigned int cpu)
kernel/watchdog.c-184-{
kernel/watchdog.c:185: int hrint = atomic_read(&per_cpu(hrtimer_interrupts, cpu));
kernel/watchdog.c-186-
kernel/watchdog.c:187: if (per_cpu(hrtimer_interrupts_saved, cpu) != hrint) {
kernel/watchdog.c-188- watchdog_hardlockup_update_reset(cpu);
--
kernel/watchdog.c-191-
kernel/watchdog.c:192: per_cpu(hrtimer_interrupts_missed, cpu)++;
kernel/watchdog.c:193: if (per_cpu(hrtimer_interrupts_missed, cpu) % watchdog_hardlockup_miss_thresh)
kernel/watchdog.c-194- return false;
--
kernel/watchdog.c=199=static void watchdog_hardlockup_kick(void)
--
kernel/watchdog.c-202-
kernel/watchdog.c:203: new_interrupts = atomic_inc_return(this_cpu_ptr(&hrtimer_interrupts));
kernel/watchdog.c-204- watchdog_buddy_check_hardlockup(new_interrupts);
--
kernel/watchdog_buddy.c=62=void watchdog_hardlockup_disable(unsigned int cpu)
--
kernel/watchdog_buddy.c-68- * checking the one after this one. If this CPU just finished checking
kernel/watchdog_buddy.c:69: * the next CPU and updating hrtimer_interrupts_saved, and then the
kernel/watchdog_buddy.c-70- * previous CPU checks it within one sample period, it will trigger a
--
kernel/watchdog_buddy.c-85-
kernel/watchdog_buddy.c:86:void watchdog_buddy_check_hardlockup(int hrtimer_interrupts)
kernel/watchdog_buddy.c-87-{
]
|
| 10/2 |
2026/05/25 17:31 |
llm |
expert |
0m
Model:
Tokens:
input: 16042
output: 23
thoughts: 22
Thoughts: Here's my take on the thought process:
**Diving into the High-Resolution Timer Code**
Okay, time to get my hands dirty. I need to refresh my memory on the high-resolution timer implementation within the kernel. Let's see... I seem to recall some potential areas of interest around the management of the timers themselves. That would mean digging into the core `hrtimer.c` file. I'm going to jump straight to the source. Specifically, I should check around line 2092 in `kernel/time/hrtimer.c`. I have a feeling something interesting is happening there. Hopefully, that location will provide some clues about what I'm looking into.
|
| 11/2 |
2026/05/25 17:31 |
tool |
read-file |
0m
Args: map[File:kernel/time/hrtimer.c]
Results: map[Contents:// SPDX-License-Identifier: GPL-2.0
/*
* Copyright(C) 2005-2006, Linutronix GmbH, Thomas Gleixner <tglx@kernel.org>
* Copyright(C) 2005-2007, Red Hat, Inc., Ingo Molnar
* Copyright(C) 2006-2007 Timesys Corp., Thomas Gleixner
*
* High-resolution kernel timers
*
* In contrast to the low-resolution timeout API, aka timer wheel,
* hrtimers provide finer resolution and accuracy depending on system
* configuration and capabilities.
*
* Started by: Thomas Gleixner and Ingo Molnar
*
* Credits:
* Based on the original timer wheel code
*
* Help, testing, suggestions, bugfixes, improvements were
* provided by:
*
* George Anzinger, Andrew Morton, Steven Rostedt, Roman Zippel
* et. al.
*/
#include <linux/cpu.h>
#include <linux/export.h>
#include <linux/percpu.h>
#include <linux/hrtimer.h>
#include <linux/notifier.h>
#include <linux/syscalls.h>
#include <linux/interrupt.h>
#include <linux/tick.h>
#include <linux/err.h>
#include <linux/debugobjects.h>
#include <linux/sched/signal.h>
#include <linux/sched/sysctl.h>
#include <linux/sched/rt.h>
#include <linux/sched/deadline.h>
#include <linux/sched/nohz.h>
#include <linux/sched/debug.h>
#include <linux/sched/isolation.h>
#include <linux/timer.h>
#include <linux/freezer.h>
#include <linux/compat.h>
#include <linux/uaccess.h>
#include <trace/events/timer.h>
#include "tick-internal.h"
/*
* Constants to set the queued state of the timer (INACTIVE, ENQUEUED)
*
* The callback state is kept separate in the CPU base because having it in
* the timer would required touching the timer after the callback, which
* makes it impossible to free the timer from the callback function.
*
* Therefore we track the callback state in:
*
* timer->base->cpu_base->running == timer
*
* On SMP it is possible to have a "callback function running and enqueued"
* status. It happens for example when a posix timer expired and the callback
* queued a signal. Between dropping the lock which protects the posix timer
* and reacquiring the base lock of the hrtimer, another CPU can deliver the
* signal and rearm the timer.
*
* All state transitions are protected by cpu_base->lock.
*/
#define HRTIMER_STATE_INACTIVE false
#define HRTIMER_STATE_ENQUEUED true
/*
* The resolution of the clocks. The resolution value is returned in
* the clock_getres() system call to give application programmers an
* idea of the (in)accuracy of timers. Timer values are rounded up to
* this resolution values.
*/
#define HIGH_RES_NSEC 1
/*
* Masks for selecting the soft and hard context timers from
* cpu_base->active
*/
#define MASK_SHIFT (HRTIMER_BASE_MONOTONIC_SOFT)
#define HRTIMER_ACTIVE_HARD ((1U << MASK_SHIFT) - 1)
#define HRTIMER_ACTIVE_SOFT (HRTIMER_ACTIVE_HARD << MASK_SHIFT)
#define HRTIMER_ACTIVE_ALL (HRTIMER_ACTIVE_SOFT | HRTIMER_ACTIVE_HARD)
static void retrigger_next_event(void *arg);
static ktime_t __hrtimer_cb_get_time(clockid_t clock_id);
/*
* The timer bases:
*
* There are more clockids than hrtimer bases. Thus, we index
* into the timer bases by the hrtimer_base_type enum. When trying
* to reach a base using a clockid, hrtimer_clockid_to_base()
* is used to convert from clockid to the proper hrtimer_base_type.
*/
#define BASE_INIT(idx, cid) \
[idx] = { .index = idx, .clockid = cid }
DEFINE_PER_CPU(struct hrtimer_cpu_base, hrtimer_bases) =
{
.lock = __RAW_SPIN_LOCK_UNLOCKED(hrtimer_bases.lock),
.clock_base = {
BASE_INIT(HRTIMER_BASE_MONOTONIC, CLOCK_MONOTONIC),
BASE_INIT(HRTIMER_BASE_REALTIME, CLOCK_REALTIME),
BASE_INIT(HRTIMER_BASE_BOOTTIME, CLOCK_BOOTTIME),
BASE_INIT(HRTIMER_BASE_TAI, CLOCK_TAI),
BASE_INIT(HRTIMER_BASE_MONOTONIC_SOFT, CLOCK_MONOTONIC),
BASE_INIT(HRTIMER_BASE_REALTIME_SOFT, CLOCK_REALTIME),
BASE_INIT(HRTIMER_BASE_BOOTTIME_SOFT, CLOCK_BOOTTIME),
BASE_INIT(HRTIMER_BASE_TAI_SOFT, CLOCK_TAI),
},
.csd = CSD_INIT(retrigger_next_event, NULL)
};
static inline bool hrtimer_base_is_online(struct hrtimer_cpu_base *base)
{
if (!IS_ENABLED(CONFIG_HOTPLUG_CPU))
return true;
else
return likely(base->online);
}
#ifdef CONFIG_HIGH_RES_TIMERS
DEFINE_STATIC_KEY_FALSE(hrtimer_highres_enabled_key);
static void hrtimer_hres_workfn(struct work_struct *work)
{
static_branch_enable(&hrtimer_highres_enabled_key);
}
static DECLARE_WORK(hrtimer_hres_work, hrtimer_hres_workfn);
static inline void hrtimer_schedule_hres_work(void)
{
if (!hrtimer_highres_enabled())
schedule_work(&hrtimer_hres_work);
}
#else
static inline void hrtimer_schedule_hres_work(void) { }
#endif
/*
* Functions and macros which are different for UP/SMP systems are kept in a
* single place
*/
#ifdef CONFIG_SMP
/*
* We require the migration_base for lock_hrtimer_base()/switch_hrtimer_base()
* such that hrtimer_callback_running() can unconditionally dereference
* timer->base->cpu_base
*/
static struct hrtimer_cpu_base migration_cpu_base = {
.clock_base = {
[0] = {
.cpu_base = &migration_cpu_base,
.seq = SEQCNT_RAW_SPINLOCK_ZERO(migration_cpu_base.seq,
&migration_cpu_base.lock),
},
},
};
#define migration_base migration_cpu_base.clock_base[0]
/*
* We are using hashed locking: holding per_cpu(hrtimer_bases)[n].lock
* means that all timers which are tied to this base via timer->base are
* locked, and the base itself is locked too.
*
* So __run_timers/migrate_timers can safely modify all timers which could
* be found on the lists/queues.
*
* When the timer's base is locked, and the timer removed from list, it is
* possible to set timer->base = &migration_base and drop the lock: the timer
* remains locked.
*/
static struct hrtimer_clock_base *lock_hrtimer_base(const struct hrtimer *timer,
unsigned long *flags)
__acquires(&timer->base->lock)
{
for (;;) {
struct hrtimer_clock_base *base = READ_ONCE(timer->base);
if (likely(base != &migration_base)) {
raw_spin_lock_irqsave(&base->cpu_base->lock, *flags);
if (likely(base == timer->base))
return base;
/* The timer has migrated to another CPU: */
raw_spin_unlock_irqrestore(&base->cpu_base->lock, *flags);
}
cpu_relax();
}
}
/*
* Check if the elected target is suitable considering its next
* event and the hotplug state of the current CPU.
*
* If the elected target is remote and its next event is after the timer
* to queue, then a remote reprogram is necessary. However there is no
* guarantee the IPI handling the operation would arrive in time to meet
* the high resolution deadline. In this case the local CPU becomes a
* preferred target, unless it is offline.
*
* High and low resolution modes are handled the same way for simplicity.
*
* Called with cpu_base->lock of target cpu held.
*/
static bool hrtimer_suitable_target(struct hrtimer *timer, struct hrtimer_clock_base *new_base,
struct hrtimer_cpu_base *new_cpu_base,
struct hrtimer_cpu_base *this_cpu_base)
{
ktime_t expires;
/*
* The local CPU clockevent can be reprogrammed. Also get_target_base()
* guarantees it is online.
*/
if (new_cpu_base == this_cpu_base)
return true;
/*
* The offline local CPU can't be the default target if the
* next remote target event is after this timer. Keep the
* elected new base. An IPI will be issued to reprogram
* it as a last resort.
*/
if (!hrtimer_base_is_online(this_cpu_base))
return true;
expires = ktime_sub(hrtimer_get_expires(timer), new_base->offset);
return expires >= new_base->cpu_base->expires_next;
}
static inline struct hrtimer_cpu_base *get_target_base(struct hrtimer_cpu_base *base, bool pinned)
{
if (!hrtimer_base_is_online(base)) {
int cpu = cpumask_any_and(cpu_online_mask, housekeeping_cpumask(HK_TYPE_TIMER));
return &per_cpu(hrtimer_bases, cpu);
}
#if defined(CONFIG_SMP) && defined(CONFIG_NO_HZ_COMMON)
if (static_branch_likely(&timers_migration_enabled) && !pinned)
return &per_cpu(hrtimer_bases, get_nohz_timer_target());
#endif
return base;
}
/*
* We switch the timer base to a power-optimized selected CPU target,
* if:
* - NO_HZ_COMMON is enabled
* - timer migration is enabled
* - the timer callback is not running
* - the timer is not the first expiring timer on the new target
*
* If one of the above requirements is not fulfilled we move the timer
* to the current CPU or leave it on the previously assigned CPU if
* the timer callback is currently running.
*/
static inline struct hrtimer_clock_base *
switch_hrtimer_base(struct hrtimer *timer, struct hrtimer_clock_base *base, bool pinned)
{
struct hrtimer_cpu_base *new_cpu_base, *this_cpu_base;
struct hrtimer_clock_base *new_base;
int basenum = base->index;
this_cpu_base = this_cpu_ptr(&hrtimer_bases);
new_cpu_base = get_target_base(this_cpu_base, pinned);
again:
new_base = &new_cpu_base->clock_base[basenum];
if (base != new_base) {
/*
* We are trying to move timer to new_base. However we can't
* change timer's base while it is running, so we keep it on
* the same CPU. No hassle vs. reprogramming the event source
* in the high resolution case. The remote CPU will take care
* of this when the timer function has completed. There is no
* conflict as we hold the lock until the timer is enqueued.
*/
if (unlikely(hrtimer_callback_running(timer)))
return base;
/* See the comment in lock_hrtimer_base() */
WRITE_ONCE(timer->base, &migration_base);
raw_spin_unlock(&base->cpu_base->lock);
raw_spin_lock(&new_base->cpu_base->lock);
if (!hrtimer_suitable_target(timer, new_base, new_cpu_base, this_cpu_base)) {
raw_spin_unlock(&new_base->cpu_base->lock);
raw_spin_lock(&base->cpu_base->lock);
new_cpu_base = this_cpu_base;
WRITE_ONCE(timer->base, base);
goto again;
}
WRITE_ONCE(timer->base, new_base);
} else {
if (!hrtimer_suitable_target(timer, new_base, new_cpu_base, this_cpu_base)) {
new_cpu_base = this_cpu_base;
goto again;
}
}
return new_base;
}
#else /* CONFIG_SMP */
static inline struct hrtimer_clock_base *lock_hrtimer_base(const struct hrtimer *timer,
unsigned long *flags)
__acquires(&timer->base->cpu_base->lock)
{
struct hrtimer_clock_base *base = timer->base;
raw_spin_lock_irqsave(&base->cpu_base->lock, *flags);
return base;
}
# define switch_hrtimer_base(t, b, p) (b)
#endif /* !CONFIG_SMP */
/*
* Functions for the union type storage format of ktime_t which are
* too large for inlining:
*/
#if BITS_PER_LONG < 64
/*
* Divide a ktime value by a nanosecond value
*/
s64 __ktime_divns(const ktime_t kt, s64 div)
{
int sft = 0;
s64 dclc;
u64 tmp;
dclc = ktime_to_ns(kt);
tmp = dclc < 0 ? -dclc : dclc;
/* Make sure the divisor is less than 2^32: */
while (div >> 32) {
sft++;
div >>= 1;
}
tmp >>= sft;
do_div(tmp, (u32) div);
return dclc < 0 ? -tmp : tmp;
}
EXPORT_SYMBOL_GPL(__ktime_divns);
#endif /* BITS_PER_LONG < 64 */
/*
* Add two ktime values and do a safety check for overflow:
*/
ktime_t ktime_add_safe(const ktime_t lhs, const ktime_t rhs)
{
ktime_t res = ktime_add_unsafe(lhs, rhs);
/*
* We use KTIME_SEC_MAX here, the maximum timeout which we can
* return to user space in a timespec:
*/
if (res < 0 || res < lhs || res < rhs)
res = ktime_set(KTIME_SEC_MAX, 0);
return res;
}
EXPORT_SYMBOL_GPL(ktime_add_safe);
#ifdef CONFIG_DEBUG_OBJECTS_TIMERS
static const struct debug_obj_descr hrtimer_debug_descr;
static void *hrtimer_debug_hint(void *addr)
{
return ACCESS_PRIVATE((struct hrtimer *)addr, function);
}
/*
* fixup_init is called when:
* - an active object is initialized
*/
static bool hrtimer_fixup_init(void *addr, enum debug_obj_state state)
{
struct hrtimer *timer = addr;
switch (state) {
case ODEBUG_STATE_ACTIVE:
hrtimer_cancel(timer);
debug_object_init(timer, &hrtimer_debug_descr);
return true;
default:
return false;
}
}
/*
* fixup_activate is called when:
* - an active object is activated
* - an unknown non-static object is activated
*/
static bool hrtimer_fixup_activate(void *addr, enum debug_obj_state state)
{
switch (state) {
case ODEBUG_STATE_ACTIVE:
WARN_ON(1);
fallthrough;
default:
return false;
}
}
/*
* fixup_free is called when:
* - an active object is freed
*/
static bool hrtimer_fixup_free(void *addr, enum debug_obj_state state)
{
struct hrtimer *timer = addr;
switch (state) {
case ODEBUG_STATE_ACTIVE:
hrtimer_cancel(timer);
debug_object_free(timer, &hrtimer_debug_descr);
return true;
default:
return false;
}
}
/* Stub timer callback for improperly used timers. */
static enum hrtimer_restart stub_timer(struct hrtimer *unused)
{
WARN_ON_ONCE(1);
return HRTIMER_NORESTART;
}
/*
* hrtimer_fixup_assert_init is called when:
* - an untracked/uninit-ed object is found
*/
static bool hrtimer_fixup_assert_init(void *addr, enum debug_obj_state state)
{
struct hrtimer *timer = addr;
switch (state) {
case ODEBUG_STATE_NOTAVAILABLE:
hrtimer_setup(timer, stub_timer, CLOCK_MONOTONIC, 0);
return true;
default:
return false;
}
}
static const struct debug_obj_descr hrtimer_debug_descr = {
.name = "hrtimer",
.debug_hint = hrtimer_debug_hint,
.fixup_init = hrtimer_fixup_init,
.fixup_activate = hrtimer_fixup_activate,
.fixup_free = hrtimer_fixup_free,
.fixup_assert_init = hrtimer_fixup_assert_init,
};
static inline void debug_hrtimer_init(struct hrtimer *timer)
{
debug_object_init(timer, &hrtimer_debug_descr);
}
static inline void debug_hrtimer_init_on_stack(struct hrtimer *timer)
{
debug_object_init_on_stack(timer, &hrtimer_debug_descr);
}
static inline void debug_hrtimer_activate(struct hrtimer *timer, enum hrtimer_mode mode)
{
debug_object_activate(timer, &hrtimer_debug_descr);
}
static inline void debug_hrtimer_deactivate(struct hrtimer *timer)
{
debug_object_deactivate(timer, &hrtimer_debug_descr);
}
static inline void debug_hrtimer_assert_init(struct hrtimer *timer)
{
debug_object_assert_init(timer, &hrtimer_debug_descr);
}
void destroy_hrtimer_on_stack(struct hrtimer *timer)
{
debug_object_free(timer, &hrtimer_debug_descr);
}
EXPORT_SYMBOL_GPL(destroy_hrtimer_on_stack);
#else
static inline void debug_hrtimer_init(struct hrtimer *timer) { }
static inline void debug_hrtimer_init_on_stack(struct hrtimer *timer) { }
static inline void debug_hrtimer_activate(struct hrtimer *timer, enum hrtimer_mode mode) { }
static inline void debug_hrtimer_deactivate(struct hrtimer *timer) { }
static inline void debug_hrtimer_assert_init(struct hrtimer *timer) { }
#endif
static inline void debug_setup(struct hrtimer *timer, clockid_t clockid, enum hrtimer_mode mode)
{
debug_hrtimer_init(timer);
trace_hrtimer_setup(timer, clockid, mode);
}
static inline void debug_setup_on_stack(struct hrtimer *timer, clockid_t clockid,
enum hrtimer_mode mode)
{
debug_hrtimer_init_on_stack(timer);
trace_hrtimer_setup(timer, clockid, mode);
}
static inline void debug_activate(struct hrtimer *timer, enum hrtimer_mode mode, bool was_armed)
{
debug_hrtimer_activate(timer, mode);
trace_hrtimer_start(timer, mode, was_armed);
}
#define for_each_active_base(base, cpu_base, active) \
for (unsigned int idx = ffs(active); idx--; idx = ffs((active))) \
for (bool done = false; !done; active &= ~(1U << idx)) \
for (base = &cpu_base->clock_base[idx]; !done; done = true)
#define hrtimer_from_timerqueue_node(_n) container_of_const(_n, struct hrtimer, node)
#if defined(CONFIG_NO_HZ_COMMON)
/*
* Same as hrtimer_bases_next_event() below, but skips the excluded timer and
* does not update cpu_base->next_timer/expires.
*/
static ktime_t hrtimer_bases_next_event_without(struct hrtimer_cpu_base *cpu_base,
const struct hrtimer *exclude,
unsigned int active, ktime_t expires_next)
{
struct hrtimer_clock_base *base;
ktime_t expires;
lockdep_assert_held(&cpu_base->lock);
for_each_active_base(base, cpu_base, active) {
expires = ktime_sub(base->expires_next, base->offset);
if (expires >= expires_next)
continue;
/*
* If the excluded timer is the first on this base evaluate the
* next timer.
*/
struct timerqueue_linked_node *node = timerqueue_linked_first(&base->active);
if (unlikely(&exclude->node == node)) {
node = timerqueue_linked_next(node);
if (!node)
continue;
expires = ktime_sub(node->expires, base->offset);
if (expires >= expires_next)
continue;
}
expires_next = expires;
}
/* If base->offset changed, the result might be negative */
return max(expires_next, 0);
}
#endif
static __always_inline struct hrtimer *clock_base_next_timer(struct hrtimer_clock_base *base)
{
struct timerqueue_linked_node *next = timerqueue_linked_first(&base->active);
return hrtimer_from_timerqueue_node(next);
}
/* Find the base with the earliest expiry */
static void hrtimer_bases_first(struct hrtimer_cpu_base *cpu_base,unsigned int active,
ktime_t *expires_next, struct hrtimer **next_timer)
{
struct hrtimer_clock_base *base;
ktime_t expires;
for_each_active_base(base, cpu_base, active) {
expires = ktime_sub(base->expires_next, base->offset);
if (expires < *expires_next) {
*expires_next = expires;
*next_timer = clock_base_next_timer(base);
}
}
}
/*
* Recomputes cpu_base::*next_timer and returns the earliest expires_next
* but does not set cpu_base::*expires_next, that is done by
* hrtimer[_force]_reprogram and hrtimer_interrupt only. When updating
* cpu_base::*expires_next right away, reprogramming logic would no longer
* work.
*
* When a softirq is pending, we can ignore the HRTIMER_ACTIVE_SOFT bases,
* those timers will get run whenever the softirq gets handled, at the end of
* hrtimer_run_softirq(), hrtimer_update_softirq_timer() will re-add these bases.
*
* Therefore softirq values are those from the HRTIMER_ACTIVE_SOFT clock bases.
* The !softirq values are the minima across HRTIMER_ACTIVE_ALL, unless an actual
* softirq is pending, in which case they're the minima of HRTIMER_ACTIVE_HARD.
*
* @active_mask must be one of:
* - HRTIMER_ACTIVE_ALL,
* - HRTIMER_ACTIVE_SOFT, or
* - HRTIMER_ACTIVE_HARD.
*/
static ktime_t __hrtimer_get_next_event(struct hrtimer_cpu_base *cpu_base, unsigned int active_mask)
{
struct hrtimer *next_timer = NULL;
ktime_t expires_next = KTIME_MAX;
unsigned int active;
lockdep_assert_held(&cpu_base->lock);
if (!cpu_base->softirq_activated && (active_mask & HRTIMER_ACTIVE_SOFT)) {
active = cpu_base->active_bases & HRTIMER_ACTIVE_SOFT;
if (active)
hrtimer_bases_first(cpu_base, active, &expires_next, &next_timer);
cpu_base->softirq_next_timer = next_timer;
}
if (active_mask & HRTIMER_ACTIVE_HARD) {
active = cpu_base->active_bases & HRTIMER_ACTIVE_HARD;
if (active)
hrtimer_bases_first(cpu_base, active, &expires_next, &next_timer);
cpu_base->next_timer = next_timer;
}
return max(expires_next, 0);
}
static ktime_t hrtimer_update_next_event(struct hrtimer_cpu_base *cpu_base)
{
ktime_t expires_next, soft = KTIME_MAX;
/*
* If the soft interrupt has already been activated, ignore the
* soft bases. They will be handled in the already raised soft
* interrupt.
*/
if (!cpu_base->softirq_activated) {
soft = __hrtimer_get_next_event(cpu_base, HRTIMER_ACTIVE_SOFT);
/*
* Update the soft expiry time. clock_settime() might have
* affected it.
*/
cpu_base->softirq_expires_next = soft;
}
expires_next = __hrtimer_get_next_event(cpu_base, HRTIMER_ACTIVE_HARD);
/*
* If a softirq timer is expiring first, update cpu_base->next_timer
* and program the hardware with the soft expiry time.
*/
if (expires_next > soft) {
cpu_base->next_timer = cpu_base->softirq_next_timer;
expires_next = soft;
}
return expires_next;
}
static inline ktime_t hrtimer_update_base(struct hrtimer_cpu_base *base)
{
ktime_t *offs_real = &base->clock_base[HRTIMER_BASE_REALTIME].offset;
ktime_t *offs_boot = &base->clock_base[HRTIMER_BASE_BOOTTIME].offset;
ktime_t *offs_tai = &base->clock_base[HRTIMER_BASE_TAI].offset;
ktime_t now = ktime_get_update_offsets_now(&base->clock_was_set_seq, offs_real,
offs_boot, offs_tai);
base->clock_base[HRTIMER_BASE_REALTIME_SOFT].offset = *offs_real;
base->clock_base[HRTIMER_BASE_BOOTTIME_SOFT].offset = *offs_boot;
base->clock_base[HRTIMER_BASE_TAI_SOFT].offset = *offs_tai;
return now;
}
/*
* Is the high resolution mode active in the CPU base. This cannot use the
* static key as the CPUs are switched to high resolution mode
* asynchronously.
*/
static inline int hrtimer_hres_active(struct hrtimer_cpu_base *cpu_base)
{
return IS_ENABLED(CONFIG_HIGH_RES_TIMERS) ?
cpu_base->hres_active : 0;
}
static inline void hrtimer_rearm_event(ktime_t expires_next, bool deferred)
{
trace_hrtimer_rearm(expires_next, deferred);
tick_program_event(expires_next, 1);
}
static void __hrtimer_reprogram(struct hrtimer_cpu_base *cpu_base, struct hrtimer *next_timer,
ktime_t expires_next)
{
cpu_base->expires_next = expires_next;
/*
* If hres is not active, hardware does not have to be
* reprogrammed yet.
*
* If a hang was detected in the last timer interrupt then we
* leave the hang delay active in the hardware. We want the
* system to make progress. That also prevents the following
* scenario:
* T1 expires 50ms from now
* T2 expires 5s from now
*
* T1 is removed, so this code is called and would reprogram
* the hardware to 5s from now. Any hrtimer_start after that
* will not reprogram the hardware due to hang_detected being
* set. So we'd effectively block all timers until the T2 event
* fires.
*/
if (!hrtimer_hres_active(cpu_base) || cpu_base->hang_detected)
return;
hrtimer_rearm_event(expires_next, false);
}
/* Reprogram the event source with a evaluation of all clock bases */
static void hrtimer_force_reprogram(struct hrtimer_cpu_base *cpu_base, bool skip_equal)
{
ktime_t expires_next = hrtimer_update_next_event(cpu_base);
if (skip_equal && expires_next == cpu_base->expires_next)
return;
__hrtimer_reprogram(cpu_base, cpu_base->next_timer, expires_next);
}
/* High resolution timer related functions */
#ifdef CONFIG_HIGH_RES_TIMERS
/* High resolution timer enabled ? */
static bool hrtimer_hres_enabled __read_mostly = true;
unsigned int hrtimer_resolution __read_mostly = LOW_RES_NSEC;
EXPORT_SYMBOL_GPL(hrtimer_resolution);
/* Enable / Disable high resolution mode */
static int __init setup_hrtimer_hres(char *str)
{
return (kstrtobool(str, &hrtimer_hres_enabled) == 0);
}
__setup("highres=", setup_hrtimer_hres);
/* hrtimer_high_res_enabled - query, if the highres mode is enabled */
static inline bool hrtimer_is_hres_enabled(void)
{
return hrtimer_hres_enabled;
}
/* Switch to high resolution mode */
static void hrtimer_switch_to_hres(void)
{
struct hrtimer_cpu_base *base = this_cpu_ptr(&hrtimer_bases);
if (tick_init_highres()) {
pr_warn("Could not switch to high resolution mode on CPU %u\n", base->cpu);
return;
}
base->hres_active = true;
hrtimer_resolution = HIGH_RES_NSEC;
tick_setup_sched_timer(true);
/* "Retrigger" the interrupt to get things going */
retrigger_next_event(NULL);
hrtimer_schedule_hres_work();
}
#else
static inline bool hrtimer_is_hres_enabled(void) { return 0; }
static inline void hrtimer_switch_to_hres(void) { }
#endif /* CONFIG_HIGH_RES_TIMERS */
/*
* Retrigger next event is called after clock was set with interrupts
* disabled through an SMP function call or directly from low level
* resume code.
*
* This is only invoked when:
* - CONFIG_HIGH_RES_TIMERS is enabled.
* - CONFIG_NOHZ_COMMON is enabled
*
* For the other cases this function is empty and because the call sites
* are optimized out it vanishes as well, i.e. no need for lots of
* #ifdeffery.
*/
static void retrigger_next_event(void *arg)
{
struct hrtimer_cpu_base *base = this_cpu_ptr(&hrtimer_bases);
/*
* When high resolution mode or nohz is active, then the offsets of
* CLOCK_REALTIME/TAI/BOOTTIME have to be updated. Otherwise the
* next tick will take care of that.
*
* If high resolution mode is active then the next expiring timer
* must be reevaluated and the clock event device reprogrammed if
* necessary.
*
* In the NOHZ case the update of the offset and the reevaluation
* of the next expiring timer is enough. The return from the SMP
* function call will take care of the reprogramming in case the
* CPU was in a NOHZ idle sleep.
*
* In periodic low resolution mode, the next softirq expiration
* must also be updated.
*/
guard(raw_spinlock)(&base->lock);
hrtimer_update_base(base);
if (hrtimer_hres_active(base))
hrtimer_force_reprogram(base, /* skip_equal */ false);
else
hrtimer_update_next_event(base);
}
/*
* When a timer is enqueued and expires earlier than the already enqueued
* timers, we have to check, whether it expires earlier than the timer for
* which the clock event device was armed.
*
* Called with interrupts disabled and base->cpu_base.lock held
*/
static void hrtimer_reprogram(struct hrtimer *timer, bool reprogram)
{
struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
struct hrtimer_clock_base *base = timer->base;
ktime_t expires = hrtimer_get_expires(timer);
WARN_ON_ONCE(expires < 0);
expires = ktime_sub(expires, base->offset);
/*
* CLOCK_REALTIME timer might be requested with an absolute
* expiry time which is less than base->offset. Set it to 0.
*/
if (expires < 0)
expires = 0;
if (timer->is_soft) {
/*
* soft hrtimer could be started on a remote CPU. In this
* case softirq_expires_next needs to be updated on the
* remote CPU. The soft hrtimer will not expire before the
* first hard hrtimer on the remote CPU -
* hrtimer_check_target() prevents this case.
*/
struct hrtimer_cpu_base *timer_cpu_base = base->cpu_base;
if (timer_cpu_base->softirq_activated)
return;
if (!ktime_before(expires, timer_cpu_base->softirq_expires_next))
return;
timer_cpu_base->softirq_next_timer = timer;
timer_cpu_base->softirq_expires_next = expires;
if (!ktime_before(expires, timer_cpu_base->expires_next) || !reprogram)
return;
}
/*
* If the timer is not on the current cpu, we cannot reprogram
* the other cpus clock event device.
*/
if (base->cpu_base != cpu_base)
return;
if (expires >= cpu_base->expires_next)
return;
/* If a deferred rearm is pending skip reprogramming the device */
if (cpu_base->deferred_rearm)
return;
cpu_base->next_timer = timer;
__hrtimer_reprogram(cpu_base, timer, expires);
}
static bool update_needs_ipi(struct hrtimer_cpu_base *cpu_base, unsigned int active)
{
struct hrtimer_clock_base *base;
unsigned int seq;
ktime_t expires;
/*
* Update the base offsets unconditionally so the following
* checks whether the SMP function call is required works.
*
* The update is safe even when the remote CPU is in the hrtimer
* interrupt or the hrtimer soft interrupt and expiring affected
* bases. Either it will see the update before handling a base or
* it will see it when it finishes the processing and reevaluates
* the next expiring timer.
*/
seq = cpu_base->clock_was_set_seq;
hrtimer_update_base(cpu_base);
/*
* If the sequence did not change over the update then the
* remote CPU already handled it.
*/
if (seq == cpu_base->clock_was_set_seq)
return false;
/* If a deferred rearm is pending the remote CPU will take care of it */
if (cpu_base->deferred_rearm) {
cpu_base->deferred_needs_update = true;
return false;
}
/*
* Walk the affected clock bases and check whether the first expiring
* timer in a clock base is moving ahead of the first expiring timer of
* @cpu_base. If so, the IPI must be invoked because per CPU clock
* event devices cannot be remotely reprogrammed.
*/
active &= cpu_base->active_bases;
for_each_active_base(base, cpu_base, active) {
struct timerqueue_linked_node *next;
next = timerqueue_linked_first(&base->active);
expires = ktime_sub(next->expires, base->offset);
if (expires < cpu_base->expires_next)
return true;
/* Extra check for softirq clock bases */
if (base->index < HRTIMER_BASE_MONOTONIC_SOFT)
continue;
if (cpu_base->softirq_activated)
continue;
if (expires < cpu_base->softirq_expires_next)
return true;
}
return false;
}
/*
* Clock was set. This might affect CLOCK_REALTIME, CLOCK_TAI and
* CLOCK_BOOTTIME (for late sleep time injection).
*
* This requires to update the offsets for these clocks
* vs. CLOCK_MONOTONIC. When high resolution timers are enabled, then this
* also requires to eventually reprogram the per CPU clock event devices
* when the change moves an affected timer ahead of the first expiring
* timer on that CPU. Obviously remote per CPU clock event devices cannot
* be reprogrammed. The other reason why an IPI has to be sent is when the
* system is in !HIGH_RES and NOHZ mode. The NOHZ mode updates the offsets
* in the tick, which obviously might be stopped, so this has to bring out
* the remote CPU which might sleep in idle to get this sorted.
*/
void clock_was_set(unsigned int bases)
{
cpumask_var_t mask;
if (!hrtimer_highres_enabled() && !tick_nohz_is_active())
goto out_timerfd;
if (!zalloc_cpumask_var(&mask, GFP_KERNEL)) {
on_each_cpu(retrigger_next_event, NULL, 1);
goto out_timerfd;
}
/* Avoid interrupting CPUs if possible */
scoped_guard(cpus_read_lock) {
int cpu;
for_each_online_cpu(cpu) {
struct hrtimer_cpu_base *cpu_base = &per_cpu(hrtimer_bases, cpu);
guard(raw_spinlock_irqsave)(&cpu_base->lock);
if (update_needs_ipi(cpu_base, bases))
cpumask_set_cpu(cpu, mask);
}
scoped_guard(preempt)
smp_call_function_many(mask, retrigger_next_event, NULL, 1);
}
free_cpumask_var(mask);
out_timerfd:
timerfd_clock_was_set();
}
static void clock_was_set_work(struct work_struct *work)
{
clock_was_set(CLOCK_SET_WALL);
}
static DECLARE_WORK(hrtimer_work, clock_was_set_work);
/*
* Called from timekeeping code to reprogram the hrtimer interrupt device
* on all cpus and to notify timerfd.
*/
void clock_was_set_delayed(void)
{
schedule_work(&hrtimer_work);
}
/*
* Called during resume either directly from via timekeeping_resume()
* or in the case of s2idle from tick_unfreeze() to ensure that the
* hrtimers are up to date.
*/
void hrtimers_resume_local(void)
{
lockdep_assert_irqs_disabled();
/* Retrigger on the local CPU */
retrigger_next_event(NULL);
}
/* Counterpart to lock_hrtimer_base above */
static inline void unlock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
__releases(&timer->base->cpu_base->lock)
{
raw_spin_unlock_irqrestore(&timer->base->cpu_base->lock, *flags);
}
/**
* hrtimer_forward() - forward the timer expiry
* @timer: hrtimer to forward
* @now: forward past this time
* @interval: the interval to forward
*
* Forward the timer expiry so it will expire in the future.
*
* .. note::
* This only updates the timer expiry value and does not requeue the timer.
*
* There is also a variant of this function: hrtimer_forward_now().
*
* Context: Can be safely called from the callback function of @timer. If called
* from other contexts @timer must neither be enqueued nor running the
* callback and the caller needs to take care of serialization.
*
* Return: The number of overruns are returned.
*/
u64 hrtimer_forward(struct hrtimer *timer, ktime_t now, ktime_t interval)
{
ktime_t delta;
u64 orun = 1;
delta = ktime_sub(now, hrtimer_get_expires(timer));
if (delta < 0)
return 0;
if (WARN_ON(timer->is_queued))
return 0;
if (interval < hrtimer_resolution)
interval = hrtimer_resolution;
if (unlikely(delta >= interval)) {
s64 incr = ktime_to_ns(interval);
orun = ktime_divns(delta, incr);
hrtimer_add_expires_ns(timer, incr * orun);
if (hrtimer_get_expires(timer) > now)
return orun;
/*
* This (and the ktime_add() below) is the
* correction for exact:
*/
orun++;
}
hrtimer_add_expires(timer, interval);
return orun;
}
EXPORT_SYMBOL_GPL(hrtimer_forward);
/*
* enqueue_hrtimer - internal function to (re)start a timer
*
* The timer is inserted in expiry order. Insertion into the
* red black tree is O(log(n)).
*
* Returns true when the new timer is the leftmost timer in the tree.
*/
static bool enqueue_hrtimer(struct hrtimer *timer, struct hrtimer_clock_base *base,
enum hrtimer_mode mode, bool was_armed)
{
lockdep_assert_held(&base->cpu_base->lock);
debug_activate(timer, mode, was_armed);
WARN_ON_ONCE(!base->cpu_base->online);
base->cpu_base->active_bases |= 1 << base->index;
/* Pairs with the lockless read in hrtimer_is_queued() */
WRITE_ONCE(timer->is_queued, HRTIMER_STATE_ENQUEUED);
if (!timerqueue_linked_add(&base->active, &timer->node))
return false;
base->expires_next = hrtimer_get_expires(timer);
return true;
}
static inline void base_update_next_timer(struct hrtimer_clock_base *base)
{
struct timerqueue_linked_node *next = timerqueue_linked_first(&base->active);
base->expires_next = next ? next->expires : KTIME_MAX;
}
/*
* __remove_hrtimer - internal function to remove a timer
*
* High resolution timer mode reprograms the clock event device when the
* timer is the one which expires next. The caller can disable this by setting
* reprogram to zero. This is useful, when the context does a reprogramming
* anyway (e.g. timer interrupt)
*/
static void __remove_hrtimer(struct hrtimer *timer, struct hrtimer_clock_base *base,
bool newstate, bool reprogram)
{
struct hrtimer_cpu_base *cpu_base = base->cpu_base;
bool was_first;
lockdep_assert_held(&cpu_base->lock);
if (!timer->is_queued)
return;
/* Pairs with the lockless read in hrtimer_is_queued() */
WRITE_ONCE(timer->is_queued, newstate);
was_first = !timerqueue_linked_prev(&timer->node);
if (!timerqueue_linked_del(&base->active, &timer->node))
cpu_base->active_bases &= ~(1 << base->index);
/* Nothing to update if this was not the first timer in the base */
if (!was_first)
return;
base_update_next_timer(base);
/*
* If reprogram is false don't update cpu_base->next_timer and do not
* touch the clock event device.
*
* This happens when removing the first timer on a remote CPU, which
* will be handled by the remote CPU's interrupt. It also happens when
* a local timer is removed to be immediately restarted. That's handled
* at the call site.
*/
if (!reprogram || timer != cpu_base->next_timer || timer->is_lazy)
return;
if (cpu_base->deferred_rearm)
cpu_base->deferred_needs_update = true;
else
hrtimer_force_reprogram(cpu_base, /* skip_equal */ true);
}
static inline bool remove_hrtimer(struct hrtimer *timer, struct hrtimer_clock_base *base,
bool newstate)
{
lockdep_assert_held(&base->cpu_base->lock);
if (timer->is_queued) {
bool reprogram;
debug_hrtimer_deactivate(timer);
/*
* Remove the timer and force reprogramming when high
* resolution mode is active and the timer is on the current
* CPU. If we remove a timer on another CPU, reprogramming is
* skipped. The interrupt event on this CPU is fired and
* reprogramming happens in the interrupt handler. This is a
* rare case and less expensive than a smp call.
*/
reprogram = base->cpu_base == this_cpu_ptr(&hrtimer_bases);
__remove_hrtimer(timer, base, newstate, reprogram);
return true;
}
return false;
}
/*
* Update in place has to retrieve the expiry times of the neighbour nodes
* if they exist. That is cache line neutral because the dequeue/enqueue
* operation is going to need the same cache lines. But there is a big win
* when the dequeue/enqueue can be avoided because the RB tree does not
* have to be rebalanced twice.
*/
static inline bool
hrtimer_can_update_in_place(struct hrtimer *timer, struct hrtimer_clock_base *base, ktime_t expires)
{
struct timerqueue_linked_node *next = timerqueue_linked_next(&timer->node);
struct timerqueue_linked_node *prev = timerqueue_linked_prev(&timer->node);
/* If the new expiry goes behind the next timer, requeue is required */
if (next && expires > next->expires)
return false;
/* If this is the first timer, update in place */
if (!prev)
return true;
/* Update in place when it does not go ahead of the previous one */
return expires >= prev->expires;
}
static inline bool
remove_and_enqueue_same_base(struct hrtimer *timer, struct hrtimer_clock_base *base,
const enum hrtimer_mode mode, ktime_t expires, u64 delta_ns)
{
bool was_first = false;
/* Remove it from the timer queue if active */
if (timer->is_queued) {
was_first = !timerqueue_linked_prev(&timer->node);
/* Try to update in place to avoid the de/enqueue dance */
if (hrtimer_can_update_in_place(timer, base, expires)) {
hrtimer_set_expires_range_ns(timer, expires, delta_ns);
trace_hrtimer_start(timer, mode, true);
if (was_first)
base->expires_next = expires;
return was_first;
}
debug_hrtimer_deactivate(timer);
timerqueue_linked_del(&base->active, &timer->node);
}
/* Set the new expiry time */
hrtimer_set_expires_range_ns(timer, expires, delta_ns);
debug_activate(timer, mode, timer->is_queued);
base->cpu_base->active_bases |= 1 << base->index;
/* Pairs with the lockless read in hrtimer_is_queued() */
WRITE_ONCE(timer->is_queued, HRTIMER_STATE_ENQUEUED);
/* If it's the first expiring timer now or again, update base */
if (timerqueue_linked_add(&base->active, &timer->node)) {
base->expires_next = expires;
return true;
}
if (was_first)
base_update_next_timer(base);
return false;
}
static inline ktime_t hrtimer_update_lowres(struct hrtimer *timer, ktime_t tim,
const enum hrtimer_mode mode)
{
#ifdef CONFIG_TIME_LOW_RES
/*
* CONFIG_TIME_LOW_RES indicates that the system has no way to return
* granular time values. For relative timers we add hrtimer_resolution
* (i.e. one jiffy) to prevent short timeouts.
*/
timer->is_rel = mode & HRTIMER_MODE_REL;
if (timer->is_rel)
tim = ktime_add_safe(tim, hrtimer_resolution);
#endif
return tim;
}
static void hrtimer_update_softirq_timer(struct hrtimer_cpu_base *cpu_base, bool reprogram)
{
ktime_t expires = __hrtimer_get_next_event(cpu_base, HRTIMER_ACTIVE_SOFT);
/*
* Reprogramming needs to be triggered, even if the next soft
* hrtimer expires at the same time as the next hard
* hrtimer. cpu_base->softirq_expires_next needs to be updated!
*/
if (expires == KTIME_MAX)
return;
/*
* cpu_base->next_timer is recomputed by __hrtimer_get_next_event()
* cpu_base->expires_next is only set by hrtimer_reprogram()
*/
hrtimer_reprogram(cpu_base->softirq_next_timer, reprogram);
}
#if defined(CONFIG_SMP) && defined(CONFIG_NO_HZ_COMMON)
static __always_inline bool hrtimer_prefer_local(bool is_local, bool is_first, bool is_pinned)
{
if (static_branch_likely(&timers_migration_enabled)) {
/*
* If it is local and the first expiring timer keep it on the local
* CPU to optimize reprogramming of the clockevent device. Also
* avoid switch_hrtimer_base() overhead when local and pinned.
*/
if (!is_local)
return false;
if (is_first || is_pinned)
return true;
/* Honour the NOHZ full restrictions */
if (!housekeeping_cpu(smp_processor_id(), HK_TYPE_KERNEL_NOISE))
return false;
/*
* If the tick is not stopped or need_resched() is set, then
* there is no point in moving the timer somewhere else.
*/
return !tick_nohz_tick_stopped() || need_resched();
}
return is_local;
}
#else
static __always_inline bool hrtimer_prefer_local(bool is_local, bool is_first, bool is_pinned)
{
return is_local;
}
#endif
static inline bool hrtimer_keep_base(struct hrtimer *timer, bool is_local, bool is_first,
bool is_pinned)
{
/* If the timer is running the callback it has to stay on its CPU base. */
if (unlikely(timer->base->running == timer))
return true;
return hrtimer_prefer_local(is_local, is_first, is_pinned);
}
static bool __hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim, u64 delta_ns,
const enum hrtimer_mode mode, struct hrtimer_clock_base *base)
{
struct hrtimer_cpu_base *this_cpu_base = this_cpu_ptr(&hrtimer_bases);
bool is_pinned, first, was_first, keep_base = false;
struct hrtimer_cpu_base *cpu_base = base->cpu_base;
was_first = cpu_base->next_timer == timer;
is_pinned = !!(mode & HRTIMER_MODE_PINNED);
/*
* Don't keep it local if this enqueue happens on a unplugged CPU
* after hrtimer_cpu_dying() has been invoked.
*/
if (likely(this_cpu_base->online)) {
bool is_local = cpu_base == this_cpu_base;
keep_base = hrtimer_keep_base(timer, is_local, was_first, is_pinned);
}
/* Calculate absolute expiry time for relative timers */
if (mode & HRTIMER_MODE_REL)
tim = ktime_add_safe(tim, __hrtimer_cb_get_time(base->clockid));
/* Compensate for low resolution granularity */
tim = hrtimer_update_lowres(timer, tim, mode);
/*
* Remove an active timer from the queue. In case it is not queued
* on the current CPU, make sure that remove_hrtimer() updates the
* remote data correctly.
*
* If it's on the current CPU and the first expiring timer, then
* skip reprogramming, keep the timer local and enforce
* reprogramming later if it was the first expiring timer. This
* avoids programming the underlying clock event twice (once at
* removal and once after enqueue).
*
* @keep_base is also true if the timer callback is running on a
* remote CPU and for local pinned timers.
*/
if (likely(keep_base)) {
first = remove_and_enqueue_same_base(timer, base, mode, tim, delta_ns);
} else {
/* Keep the ENQUEUED state in case it is queued */
bool was_armed = remove_hrtimer(timer, base, HRTIMER_STATE_ENQUEUED);
hrtimer_set_expires_range_ns(timer, tim, delta_ns);
/* Switch the timer base, if necessary: */
base = switch_hrtimer_base(timer, base, is_pinned);
cpu_base = base->cpu_base;
first = enqueue_hrtimer(timer, base, mode, was_armed);
}
/* If a deferred rearm is pending skip reprogramming the device */
if (cpu_base->deferred_rearm) {
cpu_base->deferred_needs_update = true;
return false;
}
if (!was_first || cpu_base != this_cpu_base) {
/*
* If the current CPU base is online, then the timer is never
* queued on a remote CPU if it would be the first expiring
* timer there unless the timer callback is currently executed
* on the remote CPU. In the latter case the remote CPU will
* re-evaluate the first expiring timer after completing the
* callbacks.
*/
if (likely(hrtimer_base_is_online(this_cpu_base)))
return first;
/*
* Timer was enqueued remote because the current base is
* already offline. If the timer is the first to expire,
* kick the remote CPU to reprogram the clock event.
*/
if (first)
smp_call_function_single_async(cpu_base->cpu, &cpu_base->csd);
return false;
}
/*
* Special case for the HRTICK timer. It is frequently rearmed and most
* of the time moves the expiry into the future. That's expensive in
* virtual machines and it's better to take the pointless already armed
* interrupt than reprogramming the hardware on every context switch.
*
* If the new expiry is before the armed time, then reprogramming is
* required.
*/
if (timer->is_lazy) {
if (cpu_base->expires_next <= hrtimer_get_expires(timer))
return false;
}
/*
* Timer was the first expiring timer and forced to stay on the
* current CPU to avoid reprogramming on removal and enqueue. Force
* reprogram the hardware by evaluating the new first expiring
* timer.
*/
hrtimer_force_reprogram(cpu_base, /* skip_equal */ true);
return false;
}
/**
* hrtimer_start_range_ns - (re)start an hrtimer
* @timer: the timer to be added
* @tim: expiry time
* @delta_ns: "slack" range for the timer
* @mode: timer mode: absolute (HRTIMER_MODE_ABS) or
* relative (HRTIMER_MODE_REL), and pinned (HRTIMER_MODE_PINNED);
* softirq based mode is considered for debug purpose only!
*/
void hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim, u64 delta_ns,
const enum hrtimer_mode mode)
{
struct hrtimer_clock_base *base;
unsigned long flags;
debug_hrtimer_assert_init(timer);
/*
* Check whether the HRTIMER_MODE_SOFT bit and hrtimer.is_soft
* match on CONFIG_PREEMPT_RT = n. With PREEMPT_RT check the hard
* expiry mode because unmarked timers are moved to softirq expiry.
*/
if (!IS_ENABLED(CONFIG_PREEMPT_RT))
WARN_ON_ONCE(!(mode & HRTIMER_MODE_SOFT) ^ !timer->is_soft);
else
WARN_ON_ONCE(!(mode & HRTIMER_MODE_HARD) ^ !timer->is_hard);
base = lock_hrtimer_base(timer, &flags);
if (__hrtimer_start_range_ns(timer, tim, delta_ns, mode, base))
hrtimer_reprogram(timer, true);
unlock_hrtimer_base(timer, &flags);
}
EXPORT_SYMBOL_GPL(hrtimer_start_range_ns);
/**
* hrtimer_try_to_cancel - try to deactivate a timer
* @timer: hrtimer to stop
*
* Returns:
*
* * 0 when the timer was not active
* * 1 when the timer was active
* * -1 when the timer is currently executing the callback function and
* cannot be stopped
*/
int hrtimer_try_to_cancel(struct hrtimer *timer)
{
struct hrtimer_clock_base *base;
unsigned long flags;
int ret = -1;
/*
* Check lockless first. If the timer is not active (neither
* enqueued nor running the callback, nothing to do here. The
* base lock does not serialize against a concurrent enqueue,
* so we can avoid taking it.
*/
if (!hrtimer_active(timer))
return 0;
base = lock_hrtimer_base(timer, &flags);
if (!hrtimer_callback_running(timer)) {
ret = remove_hrtimer(timer, base, HRTIMER_STATE_INACTIVE);
if (ret)
trace_hrtimer_cancel(timer);
}
unlock_hrtimer_base(timer, &flags);
return ret;
}
EXPORT_SYMBOL_GPL(hrtimer_try_to_cancel);
#ifdef CONFIG_PREEMPT_RT
static void hrtimer_cpu_base_init_expiry_lock(struct hrtimer_cpu_base *base)
{
spin_lock_init(&base->softirq_expiry_lock);
}
static void hrtimer_cpu_base_lock_expiry(struct hrtimer_cpu_base *base)
__acquires(&base->softirq_expiry_lock)
{
spin_lock(&base->softirq_expiry_lock);
}
static void hrtimer_cpu_base_unlock_expiry(struct hrtimer_cpu_base *base)
__releases(&base->softirq_expiry_lock)
{
spin_unlock(&base->softirq_expiry_lock);
}
/*
* The counterpart to hrtimer_cancel_wait_running().
*
* If there is a waiter for cpu_base->expiry_lock, then it was waiting for
* the timer callback to finish. Drop expiry_lock and reacquire it. That
* allows the waiter to acquire the lock and make progress.
*/
static void hrtimer_sync_wait_running(struct hrtimer_cpu_base *cpu_base, unsigned long flags)
{
if (atomic_read(&cpu_base->timer_waiters)) {
raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
spin_unlock(&cpu_base->softirq_expiry_lock);
spin_lock(&cpu_base->softirq_expiry_lock);
raw_spin_lock_irq(&cpu_base->lock);
}
}
#ifdef CONFIG_SMP
static __always_inline bool is_migration_base(struct hrtimer_clock_base *base)
{
return base == &migration_base;
}
#else
static __always_inline bool is_migration_base(struct hrtimer_clock_base *base)
{
return false;
}
#endif
/*
* This function is called on PREEMPT_RT kernels when the fast path
* deletion of a timer failed because the timer callback function was
* running.
*
* This prevents priority inversion: if the soft irq thread is preempted
* in the middle of a timer callback, then calling hrtimer_cancel() can
* lead to two issues:
*
* - If the caller is on a remote CPU then it has to spin wait for the timer
* handler to complete. This can result in unbound priority inversion.
*
* - If the caller originates from the task which preempted the timer
* handler on the same CPU, then spin waiting for the timer handler to
* complete is never going to end.
*/
void hrtimer_cancel_wait_running(const struct hrtimer *timer)
{
/* Lockless read. Prevent the compiler from reloading it below */
struct hrtimer_clock_base *base = READ_ONCE(timer->base);
/*
* Just relax if the timer expires in hard interrupt context or if
* it is currently on the migration base.
*/
if (!timer->is_soft || is_migration_base(base)) {
cpu_relax();
return;
}
/*
* Mark the base as contended and grab the expiry lock, which is
* held by the softirq across the timer callback. Drop the lock
* immediately so the softirq can expire the next timer. In theory
* the timer could already be running again, but that's more than
* unlikely and just causes another wait loop.
*/
atomic_inc(&base->cpu_base->timer_waiters);
spin_lock_bh(&base->cpu_base->softirq_expiry_lock);
atomic_dec(&base->cpu_base->timer_waiters);
spin_unlock_bh(&base->cpu_base->softirq_expiry_lock);
}
#else
static inline void hrtimer_cpu_base_init_expiry_lock(struct hrtimer_cpu_base *base) { }
static inline void hrtimer_cpu_base_lock_expiry(struct hrtimer_cpu_base *base) { }
static inline void hrtimer_cpu_base_unlock_expiry(struct hrtimer_cpu_base *base) { }
static inline void hrtimer_sync_wait_running(struct hrtimer_cpu_base *base, unsigned long fl) { }
#endif
/**
* hrtimer_cancel - cancel a timer and wait for the handler to finish.
* @timer: the timer to be cancelled
*
* Returns:
* 0 when the timer was not active
* 1 when the timer was active
*/
int hrtimer_cancel(struct hrtimer *timer)
{
int ret;
do {
ret = hrtimer_try_to_cancel(timer);
if (ret < 0)
hrtimer_cancel_wait_running(timer);
} while (ret < 0);
return ret;
}
EXPORT_SYMBOL_GPL(hrtimer_cancel);
/**
* __hrtimer_get_remaining - get remaining time for the timer
* @timer: the timer to read
* @adjust: adjust relative timers when CONFIG_TIME_LOW_RES=y
*/
ktime_t __hrtimer_get_remaining(const struct hrtimer *timer, bool adjust)
{
unsigned long flags;
ktime_t rem;
lock_hrtimer_base(timer, &flags);
if (IS_ENABLED(CONFIG_TIME_LOW_RES) && adjust)
rem = hrtimer_expires_remaining_adjusted(timer);
else
rem = hrtimer_expires_remaining(timer);
unlock_hrtimer_base(timer, &flags);
return rem;
}
EXPORT_SYMBOL_GPL(__hrtimer_get_remaining);
#ifdef CONFIG_NO_HZ_COMMON
/**
* hrtimer_get_next_event - get the time until next expiry event
*
* Returns the next expiry time or KTIME_MAX if no timer is pending.
*/
u64 hrtimer_get_next_event(void)
{
struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
u64 expires = KTIME_MAX;
guard(raw_spinlock_irqsave)(&cpu_base->lock);
if (!hrtimer_hres_active(cpu_base))
expires = __hrtimer_get_next_event(cpu_base, HRTIMER_ACTIVE_ALL);
return expires;
}
/**
* hrtimer_next_event_without - time until next expiry event w/o one timer
* @exclude: timer to exclude
*
* Returns the next expiry time over all timers except for the @exclude one or
* KTIME_MAX if none of them is pending.
*/
u64 hrtimer_next_event_without(const struct hrtimer *exclude)
{
struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
u64 expires = KTIME_MAX;
unsigned int active;
guard(raw_spinlock_irqsave)(&cpu_base->lock);
if (!hrtimer_hres_active(cpu_base))
return expires;
active = cpu_base->active_bases & HRTIMER_ACTIVE_SOFT;
if (active && !cpu_base->softirq_activated)
expires = hrtimer_bases_next_event_without(cpu_base, exclude, active, KTIME_MAX);
active = cpu_base->active_bases & HRTIMER_ACTIVE_HARD;
if (!active)
return expires;
return hrtimer_bases_next_event_without(cpu_base, exclude, active, expires);
}
#endif
static inline int hrtimer_clockid_to_base(clockid_t clock_id)
{
switch (clock_id) {
case CLOCK_MONOTONIC:
return HRTIMER_BASE_MONOTONIC;
case CLOCK_REALTIME:
return HRTIMER_BASE_REALTIME;
case CLOCK_BOOTTIME:
return HRTIMER_BASE_BOOTTIME;
case CLOCK_TAI:
return HRTIMER_BASE_TAI;
default:
WARN(1, "Invalid clockid %d. Using MONOTONIC\n", clock_id);
return HRTIMER_BASE_MONOTONIC;
}
}
static ktime_t __hrtimer_cb_get_time(clockid_t clock_id)
{
switch (clock_id) {
case CLOCK_MONOTONIC:
return ktime_get();
case CLOCK_REALTIME:
return ktime_get_real();
case CLOCK_BOOTTIME:
return ktime_get_boottime();
case CLOCK_TAI:
return ktime_get_clocktai();
default:
WARN(1, "Invalid clockid %d. Using MONOTONIC\n", clock_id);
return ktime_get();
}
}
ktime_t hrtimer_cb_get_time(const struct hrtimer *timer)
{
return __hrtimer_cb_get_time(timer->base->clockid);
}
EXPORT_SYMBOL_GPL(hrtimer_cb_get_time);
static void __hrtimer_setup(struct hrtimer *timer, enum hrtimer_restart (*fn)(struct hrtimer *),
clockid_t clock_id, enum hrtimer_mode mode)
{
bool softtimer = !!(mode & HRTIMER_MODE_SOFT);
struct hrtimer_cpu_base *cpu_base;
int base;
/*
* On PREEMPT_RT enabled kernels hrtimers which are not explicitly
* marked for hard interrupt expiry mode are moved into soft
* interrupt context for latency reasons and because the callbacks
* can invoke functions which might sleep on RT, e.g. spin_lock().
*/
if (IS_ENABLED(CONFIG_PREEMPT_RT) && !(mode & HRTIMER_MODE_HARD))
softtimer = true;
memset(timer, 0, sizeof(struct hrtimer));
cpu_base = raw_cpu_ptr(&hrtimer_bases);
/*
* POSIX magic: Relative CLOCK_REALTIME timers are not affected by
* clock modifications, so they needs to become CLOCK_MONOTONIC to
* ensure POSIX compliance.
*/
if (clock_id == CLOCK_REALTIME && mode & HRTIMER_MODE_REL)
clock_id = CLOCK_MONOTONIC;
base = softtimer ? HRTIMER_MAX_CLOCK_BASES / 2 : 0;
base += hrtimer_clockid_to_base(clock_id);
timer->is_soft = softtimer;
timer->is_hard = !!(mode & HRTIMER_MODE_HARD);
timer->is_lazy = !!(mode & HRTIMER_MODE_LAZY_REARM);
timer->base = &cpu_base->clock_base[base];
timerqueue_linked_init(&timer->node);
if (WARN_ON_ONCE(!fn))
ACCESS_PRIVATE(timer, function) = hrtimer_dummy_timeout;
else
ACCESS_PRIVATE(timer, function) = fn;
}
/**
* hrtimer_setup - initialize a timer to the given clock
* @timer: the timer to be initialized
* @function: the callback function
* @clock_id: the clock to be used
* @mode: The modes which are relevant for initialization:
* HRTIMER_MODE_ABS, HRTIMER_MODE_REL, HRTIMER_MODE_ABS_SOFT,
* HRTIMER_MODE_REL_SOFT
*
* The PINNED variants of the above can be handed in,
* but the PINNED bit is ignored as pinning happens
* when the hrtimer is started
*/
void hrtimer_setup(struct hrtimer *timer, enum hrtimer_restart (*function)(struct hrtimer *),
clockid_t clock_id, enum hrtimer_mode mode)
{
debug_setup(timer, clock_id, mode);
__hrtimer_setup(timer, function, clock_id, mode);
}
EXPORT_SYMBOL_GPL(hrtimer_setup);
/**
* hrtimer_setup_on_stack - initialize a timer on stack memory
* @timer: The timer to be initialized
* @function: the callback function
* @clock_id: The clock to be used
* @mode: The timer mode
*
* Similar to hrtimer_setup(), except that this one must be used if struct hrtimer is in stack
* memory.
*/
void hrtimer_setup_on_stack(struct hrtimer *timer,
enum hrtimer_restart (*function)(struct hrtimer *),
clockid_t clock_id, enum hrtimer_mode mode)
{
debug_setup_on_stack(timer, clock_id, mode);
__hrtimer_setup(timer, function, clock_id, mode);
}
EXPORT_SYMBOL_GPL(hrtimer_setup_on_stack);
/*
* A timer is active, when it is enqueued into the rbtree or the
* callback function is running or it's in the state of being migrated
* to another cpu.
*
* It is important for this function to not return a false negative.
*/
bool hrtimer_active(const struct hrtimer *timer)
{
struct hrtimer_clock_base *base;
unsigned int seq;
do {
base = READ_ONCE(timer->base);
seq = raw_read_seqcount_begin(&base->seq);
if (timer->is_queued || base->running == timer)
return true;
} while (read_seqcount_retry(&base->seq, seq) || base != READ_ONCE(timer->base));
return false;
}
EXPORT_SYMBOL_GPL(hrtimer_active);
/*
* The write_seqcount_barrier()s in __run_hrtimer() split the thing into 3
* distinct sections:
*
* - queued: the timer is queued
* - callback: the timer is being ran
* - post: the timer is inactive or (re)queued
*
* On the read side we ensure we observe timer->is_queued and cpu_base->running
* from the same section, if anything changed while we looked at it, we retry.
* This includes timer->base changing because sequence numbers alone are
* insufficient for that.
*
* The sequence numbers are required because otherwise we could still observe
* a false negative if the read side got smeared over multiple consecutive
* __run_hrtimer() invocations.
*/
static void __run_hrtimer(struct hrtimer_cpu_base *cpu_base, struct hrtimer_clock_base *base,
struct hrtimer *timer, ktime_t now, unsigned long flags)
__must_hold(&cpu_base->lock)
{
enum hrtimer_restart (*fn)(struct hrtimer *);
bool expires_in_hardirq;
int restart;
lockdep_assert_held(&cpu_base->lock);
debug_hrtimer_deactivate(timer);
base->running = timer;
/*
* Separate the ->running assignment from the ->is_queued assignment.
*
* As with a regular write barrier, this ensures the read side in
* hrtimer_active() cannot observe base->running == NULL &&
* timer->is_queued == INACTIVE.
*/
raw_write_seqcount_barrier(&base->seq);
__remove_hrtimer(timer, base, HRTIMER_STATE_INACTIVE, false);
fn = ACCESS_PRIVATE(timer, function);
/*
* Clear the 'is relative' flag for the TIME_LOW_RES case. If the
* timer is restarted with a period then it becomes an absolute
* timer. If its not restarted it does not matter.
*/
if (IS_ENABLED(CONFIG_TIME_LOW_RES))
timer->is_rel = false;
/*
* The timer is marked as running in the CPU base, so it is
* protected against migration to a different CPU even if the lock
* is dropped.
*/
raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
trace_hrtimer_expire_entry(timer, now);
expires_in_hardirq = lockdep_hrtimer_enter(timer);
restart = fn(timer);
lockdep_hrtimer_exit(expires_in_hardirq);
trace_hrtimer_expire_exit(timer);
raw_spin_lock_irq(&cpu_base->lock);
/*
* Note: We clear the running state after enqueue_hrtimer and
* we do not reprogram the event hardware. Happens either in
* hrtimer_start_range_ns() or in hrtimer_interrupt()
*
* Note: Because we dropped the cpu_base->lock above,
* hrtimer_start_range_ns() can have popped in and enqueued the timer
* for us already.
*/
if (restart == HRTIMER_RESTART && !timer->is_queued)
enqueue_hrtimer(timer, base, HRTIMER_MODE_ABS, false);
/*
* Separate the ->running assignment from the ->is_queued assignment.
*
* As with a regular write barrier, this ensures the read side in
* hrtimer_active() cannot observe base->running.timer == NULL &&
* timer->is_queued == INACTIVE.
*/
raw_write_seqcount_barrier(&base->seq);
WARN_ON_ONCE(base->running != timer);
base->running = NULL;
}
static __always_inline struct hrtimer *clock_base_next_timer_safe(struct hrtimer_clock_base *base)
{
struct timerqueue_linked_node *next = timerqueue_linked_first(&base->active);
return next ? hrtimer_from_timerqueue_node(next) : NULL;
}
static void __hrtimer_run_queues(struct hrtimer_cpu_base *cpu_base, ktime_t now,
unsigned long flags, unsigned int active_mask)
{
unsigned int active = cpu_base->active_bases & active_mask;
struct hrtimer_clock_base *base;
for_each_active_base(base, cpu_base, active) {
ktime_t basenow = ktime_add(now, base->offset);
struct hrtimer *timer;
while ((timer = clock_base_next_timer(base))) {
/*
* The immediate goal for using the softexpires is
* minimizing wakeups, not running timers at the
* earliest interrupt after their soft expiration.
* This allows us to avoid using a Priority Search
* Tree, which can answer a stabbing query for
* overlapping intervals and instead use the simple
* BST we already have.
* We don't add extra wakeups by delaying timers that
* are right-of a not yet expired timer, because that
* timer will have to trigger a wakeup anyway.
*/
if (basenow < hrtimer_get_softexpires(timer))
break;
__run_hrtimer(cpu_base, base, timer, basenow, flags);
if (active_mask == HRTIMER_ACTIVE_SOFT)
hrtimer_sync_wait_running(cpu_base, flags);
}
}
}
static __latent_entropy void hrtimer_run_softirq(void)
{
struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
unsigned long flags;
ktime_t now;
hrtimer_cpu_base_lock_expiry(cpu_base);
raw_spin_lock_irqsave(&cpu_base->lock, flags);
now = hrtimer_update_base(cpu_base);
__hrtimer_run_queues(cpu_base, now, flags, HRTIMER_ACTIVE_SOFT);
cpu_base->softirq_activated = false;
hrtimer_update_softirq_timer(cpu_base, true);
raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
hrtimer_cpu_base_unlock_expiry(cpu_base);
}
#ifdef CONFIG_HIGH_RES_TIMERS
/*
* Very similar to hrtimer_force_reprogram(), except it deals with
* deferred_rearm and hang_detected.
*/
static void hrtimer_rearm(struct hrtimer_cpu_base *cpu_base, ktime_t expires_next, bool deferred)
{
cpu_base->expires_next = expires_next;
cpu_base->deferred_rearm = false;
if (unlikely(cpu_base->hang_detected)) {
/*
* Give the system a chance to do something else than looping
* on hrtimer interrupts.
*/
expires_next = ktime_add_ns(ktime_get(),
min(100 * NSEC_PER_MSEC, cpu_base->max_hang_time));
}
hrtimer_rearm_event(expires_next, deferred);
}
#ifdef CONFIG_HRTIMER_REARM_DEFERRED
void __hrtimer_rearm_deferred(void)
{
struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
ktime_t expires_next;
if (!cpu_base->deferred_rearm)
return;
guard(raw_spinlock)(&cpu_base->lock);
if (cpu_base->deferred_needs_update) {
hrtimer_update_base(cpu_base);
expires_next = hrtimer_update_next_event(cpu_base);
} else {
/* No timer added/removed. Use the cached value */
expires_next = cpu_base->deferred_expires_next;
}
hrtimer_rearm(cpu_base, expires_next, true);
}
static __always_inline void
hrtimer_interrupt_rearm(struct hrtimer_cpu_base *cpu_base, ktime_t expires_next)
{
/* hrtimer_interrupt() just re-evaluated the first expiring timer */
cpu_base->deferred_needs_update = false;
/* Cache the expiry time */
cpu_base->deferred_expires_next = expires_next;
set_thread_flag(TIF_HRTIMER_REARM);
}
#else /* CONFIG_HRTIMER_REARM_DEFERRED */
static __always_inline void
hrtimer_interrupt_rearm(struct hrtimer_cpu_base *cpu_base, ktime_t expires_next)
{
hrtimer_rearm(cpu_base, expires_next, false);
}
#endif /* !CONFIG_HRTIMER_REARM_DEFERRED */
/*
* High resolution timer interrupt
* Called with interrupts disabled
*/
void hrtimer_interrupt(struct clock_event_device *dev)
{
struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
ktime_t expires_next, now, entry_time, delta;
unsigned long flags;
int retries = 0;
BUG_ON(!cpu_base->hres_active);
cpu_base->nr_events++;
dev->next_event = KTIME_MAX;
dev->next_event_forced = 0;
raw_spin_lock_irqsave(&cpu_base->lock, flags);
entry_time = now = hrtimer_update_base(cpu_base);
retry:
cpu_base->deferred_rearm = true;
/*
* Set expires_next to KTIME_MAX, which prevents that remote CPUs queue
* timers while __hrtimer_run_queues() is expiring the clock bases.
* Timers which are re/enqueued on the local CPU are not affected by
* this.
*/
cpu_base->expires_next = KTIME_MAX;
if (!ktime_before(now, cpu_base->softirq_expires_next)) {
cpu_base->softirq_expires_next = KTIME_MAX;
cpu_base->softirq_activated = true;
raise_timer_softirq(HRTIMER_SOFTIRQ);
}
__hrtimer_run_queues(cpu_base, now, flags, HRTIMER_ACTIVE_HARD);
/*
* The next timer was already expired due to:
* - tracing
* - long lasting callbacks
* - being scheduled away when running in a VM
*
* We need to prevent that we loop forever in the hrtiner interrupt
* routine. We give it 3 attempts to avoid overreacting on some
* spurious event.
*/
now = hrtimer_update_base(cpu_base);
expires_next = hrtimer_update_next_event(cpu_base);
cpu_base->hang_detected = false;
if (expires_next < now) {
if (++retries < 3)
goto retry;
delta = ktime_sub(now, entry_time);
cpu_base->max_hang_time = max_t(unsigned int, cpu_base->max_hang_time, delta);
cpu_base->nr_hangs++;
cpu_base->hang_detected = true;
}
hrtimer_interrupt_rearm(cpu_base, expires_next);
raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
}
#endif /* !CONFIG_HIGH_RES_TIMERS */
/*
* Called from run_local_timers in hardirq context every jiffy
*/
void hrtimer_run_queues(void)
{
struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
unsigned long flags;
ktime_t now;
if (hrtimer_hres_active(cpu_base))
return;
/*
* This _is_ ugly: We have to check periodically, whether we
* can switch to highres and / or nohz mode. The clocksource
* switch happens with xtime_lock held. Notification from
* there only sets the check bit in the tick_oneshot code,
* otherwise we might deadlock vs. xtime_lock.
*/
if (tick_check_oneshot_change(!hrtimer_is_hres_enabled())) {
hrtimer_switch_to_hres();
return;
}
raw_spin_lock_irqsave(&cpu_base->lock, flags);
now = hrtimer_update_base(cpu_base);
if (!ktime_before(now, cpu_base->softirq_expires_next)) {
cpu_base->softirq_expires_next = KTIME_MAX;
cpu_base->softirq_activated = true;
raise_timer_softirq(HRTIMER_SOFTIRQ);
}
__hrtimer_run_queues(cpu_base, now, flags, HRTIMER_ACTIVE_HARD);
raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
}
/*
* Sleep related functions:
*/
static enum hrtimer_restart hrtimer_wakeup(struct hrtimer *timer)
{
struct hrtimer_sleeper *t = container_of(timer, struct hrtimer_sleeper, timer);
struct task_struct *task = t->task;
t->task = NULL;
if (task)
wake_up_process(task);
return HRTIMER_NORESTART;
}
/**
* hrtimer_sleeper_start_expires - Start a hrtimer sleeper timer
* @sl: sleeper to be started
* @mode: timer mode abs/rel
*
* Wrapper around hrtimer_start_expires() for hrtimer_sleeper based timers
* to allow PREEMPT_RT to tweak the delivery mode (soft/hardirq context)
*/
void hrtimer_sleeper_start_expires(struct hrtimer_sleeper *sl, enum hrtimer_mode mode)
{
/*
* Make the enqueue delivery mode check work on RT. If the sleeper
* was initialized for hard interrupt delivery, force the mode bit.
* This is a special case for hrtimer_sleepers because
* __hrtimer_setup_sleeper() determines the delivery mode on RT so the
* fiddling with this decision is avoided at the call sites.
*/
if (IS_ENABLED(CONFIG_PREEMPT_RT) && sl->timer.is_hard)
mode |= HRTIMER_MODE_HARD;
hrtimer_start_expires(&sl->timer, mode);
}
EXPORT_SYMBOL_GPL(hrtimer_sleeper_start_expires);
static void __hrtimer_setup_sleeper(struct hrtimer_sleeper *sl, clockid_t clock_id,
enum hrtimer_mode mode)
{
/*
* On PREEMPT_RT enabled kernels hrtimers which are not explicitly
* marked for hard interrupt expiry mode are moved into soft
* interrupt context either for latency reasons or because the
* hrtimer callback takes regular spinlocks or invokes other
* functions which are not suitable for hard interrupt context on
* PREEMPT_RT.
*
* The hrtimer_sleeper callback is RT compatible in hard interrupt
* context, but there is a latency concern: Untrusted userspace can
* spawn many threads which arm timers for the same expiry time on
* the same CPU. That causes a latency spike due to the wakeup of
* a gazillion threads.
*
* OTOH, privileged real-time user space applications rely on the
* low latency of hard interrupt wakeups. If the current task is in
* a real-time scheduling class, mark the mode for hard interrupt
* expiry.
*/
if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
if (rt_or_dl_task_policy(current) && !(mode & HRTIMER_MODE_SOFT))
mode |= HRTIMER_MODE_HARD;
}
__hrtimer_setup(&sl->timer, hrtimer_wakeup, clock_id, mode);
sl->task = current;
}
/**
* hrtimer_setup_sleeper_on_stack - initialize a sleeper in stack memory
* @sl: sleeper to be initialized
* @clock_id: the clock to be used
* @mode: timer mode abs/rel
*/
void hrtimer_setup_sleeper_on_stack(struct hrtimer_sleeper *sl, clockid_t clock_id,
enum hrtimer_mode mode)
{
debug_setup_on_stack(&sl->timer, clock_id, mode);
__hrtimer_setup_sleeper(sl, clock_id, mode);
}
EXPORT_SYMBOL_GPL(hrtimer_setup_sleeper_on_stack);
int nanosleep_copyout(struct restart_block *restart, struct timespec64 *ts)
{
switch(restart->nanosleep.type) {
#ifdef CONFIG_COMPAT_32BIT_TIME
case TT_COMPAT:
if (put_old_timespec32(ts, restart->nanosleep.compat_rmtp))
return -EFAULT;
break;
#endif
case TT_NATIVE:
if (put_timespec64(ts, restart->nanosleep.rmtp))
return -EFAULT;
break;
default:
BUG();
}
return -ERESTART_RESTARTBLOCK;
}
static int __sched do_nanosleep(struct hrtimer_sleeper *t, enum hrtimer_mode mode)
{
struct restart_block *restart;
do {
set_current_state(TASK_INTERRUPTIBLE|TASK_FREEZABLE);
hrtimer_sleeper_start_expires(t, mode);
if (likely(t->task))
schedule();
hrtimer_cancel(&t->timer);
mode = HRTIMER_MODE_ABS;
} while (t->task && !signal_pending(current));
__set_current_state(TASK_RUNNING);
if (!t->task)
return 0;
restart = ¤t->restart_block;
if (restart->nanosleep.type != TT_NONE) {
ktime_t rem = hrtimer_expires_remaining(&t->timer);
struct timespec64 rmt;
if (rem <= 0)
return 0;
rmt = ktime_to_timespec64(rem);
return nanosleep_copyout(restart, &rmt);
}
return -ERESTART_RESTARTBLOCK;
}
static long __sched hrtimer_nanosleep_restart(struct restart_block *restart)
{
struct hrtimer_sleeper t;
int ret;
hrtimer_setup_sleeper_on_stack(&t, restart->nanosleep.clockid, HRTIMER_MODE_ABS);
hrtimer_set_expires(&t.timer, restart->nanosleep.expires);
ret = do_nanosleep(&t, HRTIMER_MODE_ABS);
destroy_hrtimer_on_stack(&t.timer);
return ret;
}
long hrtimer_nanosleep(ktime_t rqtp, const enum hrtimer_mode mode, const clockid_t clockid)
{
struct restart_block *restart;
struct hrtimer_sleeper t;
int ret;
hrtimer_setup_sleeper_on_stack(&t, clockid, mode);
hrtimer_set_expires_range_ns(&t.timer, rqtp, current->timer_slack_ns);
ret = do_nanosleep(&t, mode);
if (ret != -ERESTART_RESTARTBLOCK)
goto out;
/* Absolute timers do not update the rmtp value and restart: */
if (mode == HRTIMER_MODE_ABS) {
ret = -ERESTARTNOHAND;
goto out;
}
restart = ¤t->restart_block;
restart->nanosleep.clockid = t.timer.base->clockid;
restart->nanosleep.expires = hrtimer_get_expires(&t.timer);
set_restart_fn(restart, hrtimer_nanosleep_restart);
out:
destroy_hrtimer_on_stack(&t.timer);
return ret;
}
#ifdef CONFIG_64BIT
SYSCALL_DEFINE2(nanosleep, struct __kernel_timespec __user *, rqtp,
struct __kernel_timespec __user *, rmtp)
{
struct timespec64 tu;
if (get_timespec64(&tu, rqtp))
return -EFAULT;
if (!timespec64_valid(&tu))
return -EINVAL;
current->restart_block.fn = do_no_restart_syscall;
current->restart_block.nanosleep.type = rmtp ? TT_NATIVE : TT_NONE;
current->restart_block.nanosleep.rmtp = rmtp;
return hrtimer_nanosleep(timespec64_to_ktime(tu), HRTIMER_MODE_REL, CLOCK_MONOTONIC);
}
#endif
#ifdef CONFIG_COMPAT_32BIT_TIME
SYSCALL_DEFINE2(nanosleep_time32, struct old_timespec32 __user *, rqtp,
struct old_timespec32 __user *, rmtp)
{
struct timespec64 tu;
if (get_old_timespec32(&tu, rqtp))
return -EFAULT;
if (!timespec64_valid(&tu))
return -EINVAL;
current->restart_block.fn = do_no_restart_syscall;
current->restart_block.nanosleep.type = rmtp ? TT_COMPAT : TT_NONE;
current->restart_block.nanosleep.compat_rmtp = rmtp;
return hrtimer_nanosleep(timespec64_to_ktime(tu), HRTIMER_MODE_REL, CLOCK_MONOTONIC);
}
#endif
/*
* Functions related to boot-time initialization:
*/
int hrtimers_prepare_cpu(unsigned int cpu)
{
struct hrtimer_cpu_base *cpu_base = &per_cpu(hrtimer_bases, cpu);
for (int i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
struct hrtimer_clock_base *clock_b = &cpu_base->clock_base[i];
clock_b->cpu_base = cpu_base;
seqcount_raw_spinlock_init(&clock_b->seq, &cpu_base->lock);
timerqueue_linked_init_head(&clock_b->active);
}
cpu_base->cpu = cpu;
hrtimer_cpu_base_init_expiry_lock(cpu_base);
return 0;
}
int hrtimers_cpu_starting(unsigned int cpu)
{
struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
/* Clear out any left over state from a CPU down operation */
cpu_base->active_bases = 0;
cpu_base->hres_active = false;
cpu_base->hang_detected = false;
cpu_base->next_timer = NULL;
cpu_base->softirq_next_timer = NULL;
cpu_base->expires_next = KTIME_MAX;
cpu_base->softirq_expires_next = KTIME_MAX;
cpu_base->softirq_activated = false;
cpu_base->online = true;
return 0;
}
#ifdef CONFIG_HOTPLUG_CPU
static void migrate_hrtimer_list(struct hrtimer_clock_base *old_base,
struct hrtimer_clock_base *new_base)
{
struct timerqueue_linked_node *node;
struct hrtimer *timer;
while ((node = timerqueue_linked_first(&old_base->active))) {
timer = hrtimer_from_timerqueue_node(node);
BUG_ON(hrtimer_callback_running(timer));
debug_hrtimer_deactivate(timer);
/*
* Mark it as ENQUEUED not INACTIVE otherwise the
* timer could be seen as !active and just vanish away
* under us on another CPU
*/
__remove_hrtimer(timer, old_base, HRTIMER_STATE_ENQUEUED, false);
timer->base = new_base;
/*
* Enqueue the timers on the new cpu. This does not
* reprogram the event device in case the timer
* expires before the earliest on this CPU, but we run
* hrtimer_interrupt after we migrated everything to
* sort out already expired timers and reprogram the
* event device.
*/
enqueue_hrtimer(timer, new_base, HRTIMER_MODE_ABS, true);
}
}
int hrtimers_cpu_dying(unsigned int dying_cpu)
{
int ncpu = cpumask_any_and(cpu_active_mask, housekeeping_cpumask(HK_TYPE_TIMER));
struct hrtimer_cpu_base *old_base, *new_base;
old_base = this_cpu_ptr(&hrtimer_bases);
new_base = &per_cpu(hrtimer_bases, ncpu);
/*
* The caller is globally serialized and nobody else
* takes two locks at once, deadlock is not possible.
*/
raw_spin_lock(&old_base->lock);
raw_spin_lock_nested(&new_base->lock, SINGLE_DEPTH_NESTING);
for (int i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++)
migrate_hrtimer_list(&old_base->clock_base[i], &new_base->clock_base[i]);
/* Tell the other CPU to retrigger the next event */
smp_call_function_single(ncpu, retrigger_next_event, NULL, 0);
raw_spin_unlock(&new_base->lock);
old_base->online = false;
raw_spin_unlock(&old_base->lock);
return 0;
}
#endif /* CONFIG_HOTPLUG_CPU */
void __init hrtimers_init(void)
{
hrtimers_prepare_cpu(smp_processor_id());
hrtimers_cpu_starting(smp_processor_id());
open_softirq(HRTIMER_SOFTIRQ, hrtimer_run_softirq);
}
]
|
| 12/2 |
2026/05/25 17:31 |
llm |
expert |
0m
Model:
Tokens:
input: 41341
output: 42
thoughts: 298
Thoughts: **Analyzing the High-Resolution Timer Interrupt**
Okay, so the report points me to `kernel/time/hrtimer.c:2092`. Let's jump right to that line. I'm seeing it's inside `hrtimer_interrupt`, and at line 2092, we have: `dev->next_event_forced = 0;`. Ah, so that's where the write is occurring. Now, the question is what's being written to that field. From the context, it looks like it's clearing the `next_event_forced` field of `dev`. Hmmm, I wonder if that's a bitfield. I'm going to quickly look up `struct clock_event_device` to see what's in there. I'm thinking I've probably seen this before. It might be a flag to force the next event, maybe? I need to check the definition to be sure.
|
| 13/2 |
2026/05/25 17:32 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/time/hrtimer.c IncludeLines:true Name:clock_event_device]
Results: map[SourceCode: 70: /**
71: * struct clock_event_device - clock event device descriptor
72: * @event_handler: Assigned by the framework to be called by the low
73: * level handler of the event source
74: * @set_next_event: set next event function using a clocksource delta
75: * @set_next_ktime: set next event function using a direct ktime value
76: * @set_next_coupled: set next event function for clocksource coupled mode
77: * @next_event: local storage for the next event in oneshot mode
78: * @max_delta_ns: maximum delta value in ns
79: * @min_delta_ns: minimum delta value in ns
80: * @mult: nanosecond to cycles multiplier
81: * @shift: nanoseconds to cycles divisor (power of two)
82: * @state_use_accessors:current state of the device, assigned by the core code
83: * @features: features
84: * @cs_id: Clocksource ID to denote the clocksource for coupled mode
85: * @next_event_forced: True if the last programming was a forced event
86: * @retries: number of forced programming retries
87: * @set_state_periodic: switch state to periodic
88: * @set_state_oneshot: switch state to oneshot
89: * @set_state_oneshot_stopped: switch state to oneshot_stopped
90: * @set_state_shutdown: switch state to shutdown
91: * @tick_resume: resume clkevt device
92: * @broadcast: function to broadcast events
93: * @min_delta_ticks: minimum delta value in ticks stored for reconfiguration
94: * @max_delta_ticks: maximum delta value in ticks stored for reconfiguration
95: * @name: ptr to clock event name
96: * @rating: variable to rate clock event devices
97: * @irq: IRQ number (only for non CPU local devices)
98: * @bound_on: Bound on CPU
99: * @cpumask: cpumask to indicate for which CPUs this device works
100: * @list: list head for the management code
101: * @owner: module reference
102: */
103: struct clock_event_device {
104: void (*event_handler)(struct clock_event_device *);
105: int (*set_next_event)(unsigned long evt, struct clock_event_device *);
106: int (*set_next_ktime)(ktime_t expires, struct clock_event_device *);
107: void (*set_next_coupled)(u64 cycles, struct clock_event_device *);
108: ktime_t next_event;
109: u64 max_delta_ns;
110: u64 min_delta_ns;
111: u32 mult;
112: u32 shift;
113: enum clock_event_state state_use_accessors;
114: unsigned int features;
115: enum clocksource_ids cs_id;
116: unsigned int next_event_forced;
117: unsigned long retries;
118:
119: int (*set_state_periodic)(struct clock_event_device *);
120: int (*set_state_oneshot)(struct clock_event_device *);
121: int (*set_state_oneshot_stopped)(struct clock_event_device *);
122: int (*set_state_shutdown)(struct clock_event_device *);
123: int (*tick_resume)(struct clock_event_device *);
124:
125: void (*broadcast)(const struct cpumask *mask);
126: void (*suspend)(struct clock_event_device *);
127: void (*resume)(struct clock_event_device *);
128: unsigned long min_delta_ticks;
129: unsigned long max_delta_ticks;
130:
131: const char *name;
132: int rating;
133: int irq;
134: int bound_on;
135: const struct cpumask *cpumask;
136: struct list_head list;
137: struct module *owner;
138: } ____cacheline_aligned;
SourceFile:include/linux/clockchips.h]
|
| 14/2 |
2026/05/25 17:32 |
llm |
expert |
0m
Model:
Tokens:
input: 43166
output: 18
thoughts: 45
Thoughts: **Analyzing Timer Event Handling**
Okay, so I'm looking at this code and I need to understand how timer events are handled. My initial focus is on this variable, `next_event_forced`. It's defined as an `unsigned int` and appears to be located at an offset after `cs_id`. I need to understand its role. To get a handle on this, I'm going to jump into the `kernel/time/timer_list.c` file and specifically line 204. That should give me the context I need around this `next_event_forced` variable and how it's used within the broader timer framework. I'm expecting this will illuminate its meaning and significance within the context of the timer list and event scheduling.
|
| 15/2 |
2026/05/25 17:32 |
tool |
grepper |
0m
Args: map[Expression:print_tickdevice]
Results: map[Output:kernel/time/timer_list.c=177=static void
kernel/time/timer_list.c:178:print_tickdevice(struct seq_file *m, struct tick_device *td, int cpu)
kernel/time/timer_list.c-179-{
--
kernel/time/timer_list.c=242=static void timer_list_show_tickdevices_header(struct seq_file *m)
--
kernel/time/timer_list.c-244-#ifdef CONFIG_GENERIC_CLOCKEVENTS_BROADCAST
kernel/time/timer_list.c:245: print_tickdevice(m, tick_get_broadcast_device(), -1);
kernel/time/timer_list.c-246- SEQ_printf(m, "tick_broadcast_mask: %*pb\n",
--
kernel/time/timer_list.c=265=void sysrq_timer_list_show(void)
--
kernel/time/timer_list.c-277- for_each_online_cpu(cpu)
kernel/time/timer_list.c:278: print_tickdevice(NULL, tick_get_device(cpu), cpu);
kernel/time/timer_list.c-279-#endif
--
kernel/time/timer_list.c=284=static int timer_list_show(struct seq_file *m, void *v)
--
kernel/time/timer_list.c-295- else
kernel/time/timer_list.c:296: print_tickdevice(m, tick_get_device(iter->cpu), iter->cpu);
kernel/time/timer_list.c-297-#endif
--
scripts/gdb/linux/timerlist.py=66=def print_cpu(hrtimer_bases, cpu, max_clock_bases):
--
scripts/gdb/linux/timerlist.py-110-
scripts/gdb/linux/timerlist.py:111:def print_tickdevice(td, cpu):
scripts/gdb/linux/timerlist.py-112- dev = td['evtdev']
--
scripts/gdb/linux/timerlist.py=179=class LxTimerList(gdb.Command):
--
scripts/gdb/linux/timerlist.py-199- bc_dev = gdb.parse_and_eval("&tick_broadcast_device")
scripts/gdb/linux/timerlist.py:200: text += print_tickdevice(bc_dev, -1)
scripts/gdb/linux/timerlist.py-201- text += "\n"
--
scripts/gdb/linux/timerlist.py-213- tick_dev = cpus.per_cpu(tick_cpu_devices, cpu)
scripts/gdb/linux/timerlist.py:214: text += print_tickdevice(tick_dev, cpu)
scripts/gdb/linux/timerlist.py-215- text += "\n"
]
|
| 16/2 |
2026/05/25 17:32 |
llm |
expert |
0m
Model:
Tokens:
input: 44147
output: 24
thoughts: 22
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Diving into Timer Implementation**
Alright, let's zero in on the kernel's timer implementation, specifically `kernel/time/timer_list.c`. I'm going to start around line 204. That's usually where the core data structures and perhaps the initial initialization or insertion logic for timers will be. I need to refresh my memory on the critical path, the `timer_list` itself, and how those timers are linked and processed. I want to see how the kernel handles the timing wheel, any intricacies in the interrupt handling, and if there are any subtle race conditions I should be aware of. I'll need to focus on what happens during insertion, deletion, and expiry to see if there are any gotchas in those common operations. Considering this module, I wonder if there have been any recent perf improvements I should make myself aware of as well.
|
| 17/2 |
2026/05/25 17:32 |
tool |
read-file |
0m
Args: map[File:kernel/time/timer_list.c]
Results: map[Contents:// SPDX-License-Identifier: GPL-2.0
/*
* List pending timers
*
* Copyright(C) 2006, Red Hat, Inc., Ingo Molnar
*/
#include <linux/proc_fs.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/sched.h>
#include <linux/seq_file.h>
#include <linux/kallsyms.h>
#include <linux/nmi.h>
#include <linux/uaccess.h>
#include "tick-internal.h"
struct timer_list_iter {
int cpu;
bool second_pass;
u64 now;
};
/*
* This allows printing both to /proc/timer_list and
* to the console (on SysRq-Q):
*/
__printf(2, 3)
static void SEQ_printf(struct seq_file *m, const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
if (m)
seq_vprintf(m, fmt, args);
else
vprintk(fmt, args);
va_end(args);
}
static void
print_timer(struct seq_file *m, struct hrtimer *taddr, struct hrtimer *timer,
int idx, u64 now)
{
SEQ_printf(m, " #%d: <%p>, %ps", idx, taddr, ACCESS_PRIVATE(timer, function));
SEQ_printf(m, ", S:%02x", timer->is_queued);
SEQ_printf(m, "\n");
SEQ_printf(m, " # expires at %Lu-%Lu nsecs [in %Ld to %Ld nsecs]\n",
(unsigned long long)ktime_to_ns(hrtimer_get_softexpires(timer)),
(unsigned long long)ktime_to_ns(hrtimer_get_expires(timer)),
(long long)(ktime_to_ns(hrtimer_get_softexpires(timer)) - now),
(long long)(ktime_to_ns(hrtimer_get_expires(timer)) - now));
}
static void print_active_timers(struct seq_file *m, struct hrtimer_clock_base *base, u64 now)
{
struct timerqueue_linked_node *curr;
struct hrtimer *timer, tmp;
unsigned long next = 0, i;
unsigned long flags;
next_one:
i = 0;
touch_nmi_watchdog();
raw_spin_lock_irqsave(&base->cpu_base->lock, flags);
curr = timerqueue_linked_first(&base->active);
/*
* Crude but we have to do this O(N*N) thing, because
* we have to unlock the base when printing:
*/
while (curr && i < next) {
curr = timerqueue_linked_next(curr);
i++;
}
if (curr) {
timer = container_of(curr, struct hrtimer, node);
tmp = *timer;
raw_spin_unlock_irqrestore(&base->cpu_base->lock, flags);
print_timer(m, timer, &tmp, i, now);
next++;
goto next_one;
}
raw_spin_unlock_irqrestore(&base->cpu_base->lock, flags);
}
static void
print_base(struct seq_file *m, struct hrtimer_clock_base *base, u64 now)
{
SEQ_printf(m, " .base: %p\n", base);
SEQ_printf(m, " .index: %d\n", base->index);
SEQ_printf(m, " .resolution: %u nsecs\n", hrtimer_resolution);
#ifdef CONFIG_HIGH_RES_TIMERS
SEQ_printf(m, " .offset: %Ld nsecs\n",
(long long) base->offset);
#endif
SEQ_printf(m, "active timers:\n");
print_active_timers(m, base, now + ktime_to_ns(base->offset));
}
static void print_cpu(struct seq_file *m, int cpu, u64 now)
{
struct hrtimer_cpu_base *cpu_base = &per_cpu(hrtimer_bases, cpu);
int i;
SEQ_printf(m, "cpu: %d\n", cpu);
for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
SEQ_printf(m, " clock %d:\n", i);
print_base(m, cpu_base->clock_base + i, now);
}
#define P(x) \
SEQ_printf(m, " .%-15s: %Lu\n", #x, \
(unsigned long long)(cpu_base->x))
#define P_ns(x) \
SEQ_printf(m, " .%-15s: %Lu nsecs\n", #x, \
(unsigned long long)(ktime_to_ns(cpu_base->x)))
#ifdef CONFIG_HIGH_RES_TIMERS
P_ns(expires_next);
P(hres_active);
P(nr_events);
P(nr_retries);
P(nr_hangs);
P(max_hang_time);
#endif
#undef P
#undef P_ns
#ifdef CONFIG_TICK_ONESHOT
# define P(x) \
SEQ_printf(m, " .%-15s: %Lu\n", #x, \
(unsigned long long)(ts->x))
# define P_ns(x) \
SEQ_printf(m, " .%-15s: %Lu nsecs\n", #x, \
(unsigned long long)(ktime_to_ns(ts->x)))
# define P_flag(x, f) \
SEQ_printf(m, " .%-15s: %d\n", #x, !!(ts->flags & (f)))
{
struct tick_sched *ts = tick_get_tick_sched(cpu);
P_flag(nohz, TS_FLAG_NOHZ);
P_flag(highres, TS_FLAG_HIGHRES);
P_ns(last_tick);
P_flag(tick_stopped, TS_FLAG_STOPPED);
P(idle_jiffies);
P(idle_calls);
P(idle_sleeps);
P_ns(idle_entrytime);
P_ns(idle_waketime);
P_ns(idle_exittime);
P_ns(idle_sleeptime);
P_ns(iowait_sleeptime);
P(last_jiffies);
P(next_timer);
P_ns(idle_expires);
SEQ_printf(m, "jiffies: %Lu\n",
(unsigned long long)jiffies);
}
#endif
#undef P
#undef P_ns
SEQ_printf(m, "\n");
}
#ifdef CONFIG_GENERIC_CLOCKEVENTS
static void
print_tickdevice(struct seq_file *m, struct tick_device *td, int cpu)
{
struct clock_event_device *dev = td->evtdev;
touch_nmi_watchdog();
SEQ_printf(m, "Tick Device: mode: %d\n", td->mode);
if (cpu < 0)
SEQ_printf(m, "Broadcast device\n");
else
SEQ_printf(m, "Per CPU device: %d\n", cpu);
SEQ_printf(m, "Clock Event Device: ");
if (!dev) {
SEQ_printf(m, "<NULL>\n");
return;
}
SEQ_printf(m, "%s\n", dev->name);
SEQ_printf(m, " max_delta_ns: %llu\n",
(unsigned long long) dev->max_delta_ns);
SEQ_printf(m, " min_delta_ns: %llu\n",
(unsigned long long) dev->min_delta_ns);
SEQ_printf(m, " mult: %u\n", dev->mult);
SEQ_printf(m, " shift: %u\n", dev->shift);
SEQ_printf(m, " mode: %d\n", clockevent_get_state(dev));
SEQ_printf(m, " next_event: %Ld nsecs\n",
(unsigned long long) ktime_to_ns(dev->next_event));
SEQ_printf(m, " set_next_event: %ps\n", dev->set_next_event);
if (dev->set_state_shutdown)
SEQ_printf(m, " shutdown: %ps\n",
dev->set_state_shutdown);
if (dev->set_state_periodic)
SEQ_printf(m, " periodic: %ps\n",
dev->set_state_periodic);
if (dev->set_state_oneshot)
SEQ_printf(m, " oneshot: %ps\n",
dev->set_state_oneshot);
if (dev->set_state_oneshot_stopped)
SEQ_printf(m, " oneshot stopped: %ps\n",
dev->set_state_oneshot_stopped);
if (dev->tick_resume)
SEQ_printf(m, " resume: %ps\n",
dev->tick_resume);
SEQ_printf(m, " event_handler: %ps\n", dev->event_handler);
SEQ_printf(m, "\n");
SEQ_printf(m, " retries: %lu\n", dev->retries);
#ifdef CONFIG_GENERIC_CLOCKEVENTS_BROADCAST
if (cpu >= 0) {
const struct clock_event_device *wd = tick_get_wakeup_device(cpu);
SEQ_printf(m, "Wakeup Device: %s\n", wd ? wd->name : "<NULL>");
}
#endif
SEQ_printf(m, "\n");
}
static void timer_list_show_tickdevices_header(struct seq_file *m)
{
#ifdef CONFIG_GENERIC_CLOCKEVENTS_BROADCAST
print_tickdevice(m, tick_get_broadcast_device(), -1);
SEQ_printf(m, "tick_broadcast_mask: %*pb\n",
cpumask_pr_args(tick_get_broadcast_mask()));
#ifdef CONFIG_TICK_ONESHOT
SEQ_printf(m, "tick_broadcast_oneshot_mask: %*pb\n",
cpumask_pr_args(tick_get_broadcast_oneshot_mask()));
#endif
SEQ_printf(m, "\n");
#endif
}
#endif
static inline void timer_list_header(struct seq_file *m, u64 now)
{
SEQ_printf(m, "Timer List Version: v0.10\n");
SEQ_printf(m, "HRTIMER_MAX_CLOCK_BASES: %d\n", HRTIMER_MAX_CLOCK_BASES);
SEQ_printf(m, "now at %Ld nsecs\n", (unsigned long long)now);
SEQ_printf(m, "\n");
}
void sysrq_timer_list_show(void)
{
u64 now = ktime_to_ns(ktime_get());
int cpu;
timer_list_header(NULL, now);
for_each_online_cpu(cpu)
print_cpu(NULL, cpu, now);
#ifdef CONFIG_GENERIC_CLOCKEVENTS
timer_list_show_tickdevices_header(NULL);
for_each_online_cpu(cpu)
print_tickdevice(NULL, tick_get_device(cpu), cpu);
#endif
return;
}
#ifdef CONFIG_PROC_FS
static int timer_list_show(struct seq_file *m, void *v)
{
struct timer_list_iter *iter = v;
if (iter->cpu == -1 && !iter->second_pass)
timer_list_header(m, iter->now);
else if (!iter->second_pass)
print_cpu(m, iter->cpu, iter->now);
#ifdef CONFIG_GENERIC_CLOCKEVENTS
else if (iter->cpu == -1 && iter->second_pass)
timer_list_show_tickdevices_header(m);
else
print_tickdevice(m, tick_get_device(iter->cpu), iter->cpu);
#endif
return 0;
}
static void *move_iter(struct timer_list_iter *iter, loff_t offset)
{
for (; offset; offset--) {
iter->cpu = cpumask_next(iter->cpu, cpu_online_mask);
if (iter->cpu >= nr_cpu_ids) {
#ifdef CONFIG_GENERIC_CLOCKEVENTS
if (!iter->second_pass) {
iter->cpu = -1;
iter->second_pass = true;
} else
return NULL;
#else
return NULL;
#endif
}
}
return iter;
}
static void *timer_list_start(struct seq_file *file, loff_t *offset)
{
struct timer_list_iter *iter = file->private;
if (!*offset)
iter->now = ktime_to_ns(ktime_get());
iter->cpu = -1;
iter->second_pass = false;
return move_iter(iter, *offset);
}
static void *timer_list_next(struct seq_file *file, void *v, loff_t *offset)
{
struct timer_list_iter *iter = file->private;
++*offset;
return move_iter(iter, 1);
}
static void timer_list_stop(struct seq_file *seq, void *v)
{
}
static const struct seq_operations timer_list_sops = {
.start = timer_list_start,
.next = timer_list_next,
.stop = timer_list_stop,
.show = timer_list_show,
};
static int __init init_timer_list_procfs(void)
{
struct proc_dir_entry *pe;
pe = proc_create_seq_private("timer_list", 0400, NULL, &timer_list_sops,
sizeof(struct timer_list_iter), NULL);
if (!pe)
return -ENOMEM;
return 0;
}
__initcall(init_timer_list_procfs);
#endif
]
|
| 18/2 |
2026/05/25 17:32 |
llm |
expert |
0m
Model:
Tokens:
input: 48076
output: 23
thoughts: 476
Thoughts: **Analyzing a Potential Timer Issue**
Okay, so I'm looking at `kernel/time/timer_list.c:204` and trying to understand a possible problem. I see that line 204 is printing `dev->retries`, which is an `unsigned long`. I also see that `dev->next_event_forced = 0;` is written at `kernel/time/hrtimer.c:2092`. I quickly double-checked the `struct clock_event_device` definition. My gut feeling is telling me something is wrong with how these fields are being accessed.
I remember that `next_event_forced` is an `unsigned int` (4 bytes) and `retries` is an `unsigned long` (8 bytes). I also see that there's a write happening to `0xffff888237d17ba0` of 8 bytes, which seems to coincide with the size of an unsigned long. But line 2091 sets `dev->next_event = KTIME_MAX;`, which is also 8 bytes, and `next_event` is also a `ktime_t`.
The write could be overwriting `next_event_forced`, or it's not and the read is to `dev->retries`! Now I have to go check the offsets within the struct to confirm where `next_event`, `next_event_forced`, and `retries` actually reside relative to one another. I need to make sure I am not missing a data race or a memory corruption!
|
| 19/2 |
2026/05/25 17:32 |
tool |
codesearch-struct-layout |
0m
Args: map[Name:clock_event_device]
Results: map[Fields:[map[Name:event_handler OffsetBits:0 SizeBits:64] map[Name:set_next_event OffsetBits:64 SizeBits:64] map[Name:set_next_ktime OffsetBits:128 SizeBits:64] map[Name:set_next_coupled OffsetBits:192 SizeBits:64] map[Name:next_event OffsetBits:256 SizeBits:64] map[Name:max_delta_ns OffsetBits:320 SizeBits:64] map[Name:min_delta_ns OffsetBits:384 SizeBits:64] map[Name:mult OffsetBits:448 SizeBits:32] map[Name:shift OffsetBits:480 SizeBits:32] map[Name:state_use_accessors OffsetBits:512 SizeBits:32] map[Name:features OffsetBits:544 SizeBits:32] map[Name:cs_id OffsetBits:576 SizeBits:32] map[Name:next_event_forced OffsetBits:608 SizeBits:32] map[Name:retries OffsetBits:640 SizeBits:64] map[Name:set_state_periodic OffsetBits:704 SizeBits:64] map[Name:set_state_oneshot OffsetBits:768 SizeBits:64] map[Name:set_state_oneshot_stopped OffsetBits:832 SizeBits:64] map[Name:set_state_shutdown OffsetBits:896 SizeBits:64] map[Name:tick_resume OffsetBits:960 SizeBits:64] map[Name:broadcast OffsetBits:1024 SizeBits:64] map[Name:suspend OffsetBits:1088 SizeBits:64] map[Name:resume OffsetBits:1152 SizeBits:64] map[Name:min_delta_ticks OffsetBits:1216 SizeBits:64] map[Name:max_delta_ticks OffsetBits:1280 SizeBits:64] map[Name:name OffsetBits:1344 SizeBits:64] map[Name:rating OffsetBits:1408 SizeBits:32] map[Name:irq OffsetBits:1440 SizeBits:32] map[Name:bound_on OffsetBits:1472 SizeBits:32] map[Name:cpumask OffsetBits:1536 SizeBits:64] map[Name:list OffsetBits:1600 SizeBits:128] map[Name:owner OffsetBits:1728 SizeBits:64]]]
|
| 20/2 |
2026/05/25 17:32 |
llm |
expert |
0m
Model:
Tokens:
input: 49600
output: 20
thoughts: 1880
Thoughts: **Analyzing a Suspected Timing Issue**
Okay, so I'm looking at a write at `hrtimer_interrupt` and a read at `print_tickdevice`, both to the same address. The write is supposedly 8 bytes, but at line 2092, I see `dev->next_event_forced = 0;`, which is just 4 bytes, so something doesn't add up. Initially, I thought perhaps the compiler was merging writes, maybe to `cs_id` or `retries`. However, `cs_id` is nearby, but is an enum, and should not be cleared. And I ruled out `retries` as being written to here. I considered `dev->next_event = KTIME_MAX;` at line 2091, as that *is* an 8-byte write.
The read is definitely to `dev->retries` in `print_tickdevice`, line 204. But the write doesn't seem to be writing to `retries` in the interrupt handler.
I checked the offsets. `next_event_forced` is at offset 76 bytes and `retries` is at offset 80 bytes. They are adjacent! But the write is still to 4 bytes.
So, could the compiler be optimizing the zeroing of *both* `next_event_forced` and something else? No, `retries` is not set to zero here either.
Then I had a breakthrough: the value being written is a `ktime_t`! The value changing is not the max value, but a valid `ktime_t` value. It seems that the address is a valid kernel address that is used as a `ktime_t` value. However, `dev->next_event` is set to `KTIME_MAX` not a smaller value in the function that appears to contain the write.
Aha! `dev->next_event` is updated by `clockevents_program_event`! I need to check that function. Maybe the apparent write is to `dev->next_event` *through* some optimization or other means, even if the line number is slightly off.
|
| 21/2 |
2026/05/25 17:32 |
tool |
grepper |
0m
Args: map[Expression:clockevents_program_event]
Results: map[Output:Documentation/trace/ftrace.rst=1761=was over.
--
Documentation/trace/ftrace.rst-1798- [...]
Documentation/trace/ftrace.rst:1799: bash-1994 1d.h1 35us : lapic_next_event <-clockevents_program_event
Documentation/trace/ftrace.rst-1800- bash-1994 1d.h1 35us : irq_exit <-smp_apic_timer_interrupt
--
Documentation/trace/ftrace.rst=2160=Doing the same with chrt -r 5 and function-trace set.
--
Documentation/trace/ftrace.rst-2196- <idle>-0 3dNh1 7us : tick_program_event <-hrtimer_interrupt
Documentation/trace/ftrace.rst:2197: <idle>-0 3dNh1 7us : clockevents_program_event <-tick_program_event
Documentation/trace/ftrace.rst:2198: <idle>-0 3dNh1 8us : ktime_get <-clockevents_program_event
Documentation/trace/ftrace.rst:2199: <idle>-0 3dNh1 8us : lapic_next_event <-clockevents_program_event
Documentation/trace/ftrace.rst-2200- <idle>-0 3dNh1 8us : irq_exit <-smp_apic_timer_interrupt
--
Documentation/trace/ftrace.rst-2228- <idle>-0 3dN.2 17us : tick_program_event <-hrtimer_force_reprogram
Documentation/trace/ftrace.rst:2229: <idle>-0 3dN.2 18us : clockevents_program_event <-tick_program_event
Documentation/trace/ftrace.rst:2230: <idle>-0 3dN.2 18us : ktime_get <-clockevents_program_event
Documentation/trace/ftrace.rst:2231: <idle>-0 3dN.2 18us : lapic_next_event <-clockevents_program_event
Documentation/trace/ftrace.rst-2232- <idle>-0 3dN.2 19us : _raw_spin_unlock_irqrestore <-hrtimer_try_to_cancel
--
Documentation/trace/ftrace.rst-2244- <idle>-0 3dN.2 22us : tick_program_event <-__hrtimer_start_range_ns
Documentation/trace/ftrace.rst:2245: <idle>-0 3dN.2 23us : clockevents_program_event <-tick_program_event
Documentation/trace/ftrace.rst:2246: <idle>-0 3dN.2 23us : ktime_get <-clockevents_program_event
Documentation/trace/ftrace.rst:2247: <idle>-0 3dN.2 23us : lapic_next_event <-clockevents_program_event
Documentation/trace/ftrace.rst-2248- <idle>-0 3dN.2 24us : _raw_spin_unlock_irqrestore <-__hrtimer_start_range_ns
--
kernel/time/clockevents.c=325=static inline bool clockevent_set_next_coupled(struct clock_event_device *dev, ktime_t expires)
--
kernel/time/clockevents.c-331-/**
kernel/time/clockevents.c:332: * clockevents_program_event - Reprogram the clock event device.
kernel/time/clockevents.c-333- * @dev: device to program
--
kernel/time/clockevents.c-338- */
kernel/time/clockevents.c:339:int clockevents_program_event(struct clock_event_device *dev, ktime_t expires, bool force)
kernel/time/clockevents.c-340-{
--
kernel/time/clockevents.c=573=int __clockevents_update_freq(struct clock_event_device *dev, u32 freq)
--
kernel/time/clockevents.c-577- if (clockevent_state_oneshot(dev))
kernel/time/clockevents.c:578: return clockevents_program_event(dev, dev->next_event, false);
kernel/time/clockevents.c-579-
--
kernel/time/tick-broadcast.c=403=static void tick_handle_periodic_broadcast(struct clock_event_device *dev)
--
kernel/time/tick-broadcast.c-421-
kernel/time/tick-broadcast.c:422: clockevents_program_event(dev, next, true);
kernel/time/tick-broadcast.c-423- }
--
kernel/time/tick-broadcast.c=655=static void tick_broadcast_set_event(struct clock_event_device *bc, int cpu,
--
kernel/time/tick-broadcast.c-660-
kernel/time/tick-broadcast.c:661: clockevents_program_event(bc, expires, 1);
kernel/time/tick-broadcast.c-662- tick_broadcast_set_affinity(bc, cpumask_of(cpu));
--
kernel/time/tick-broadcast.c=939=static int tick_oneshot_wakeup_control(enum tick_broadcast_state state,
--
kernel/time/tick-broadcast.c-956- clockevents_switch_state(wd, CLOCK_EVT_STATE_ONESHOT);
kernel/time/tick-broadcast.c:957: clockevents_program_event(wd, dev->next_event, 1);
kernel/time/tick-broadcast.c-958- break;
--
kernel/time/tick-broadcast.c=1150=void hotplug_cpu__broadcast_tick_pull(int deadcpu)
--
kernel/time/tick-broadcast.c-1184- bc->next_event_forced = 0;
kernel/time/tick-broadcast.c:1185: clockevents_program_event(bc, bc->next_event, 1);
kernel/time/tick-broadcast.c-1186- }
--
kernel/time/tick-common.c=108=void tick_handle_periodic(struct clock_event_device *dev)
--
kernel/time/tick-common.c-132-
kernel/time/tick-common.c:133: if (!clockevents_program_event(dev, next, false))
kernel/time/tick-common.c-134- return;
--
kernel/time/tick-common.c=152=void tick_setup_periodic(struct clock_event_device *dev, int broadcast)
--
kernel/time/tick-common.c-174- for (;;) {
kernel/time/tick-common.c:175: if (!clockevents_program_event(dev, next, false))
kernel/time/tick-common.c-176- return;
--
kernel/time/tick-internal.h=59=extern void clockevents_switch_state(struct clock_event_device *dev,
kernel/time/tick-internal.h-60- enum clock_event_state state);
kernel/time/tick-internal.h:61:extern int clockevents_program_event(struct clock_event_device *dev,
kernel/time/tick-internal.h-62- ktime_t expires, bool force);
--
kernel/time/tick-oneshot.c=27=int tick_program_event(ktime_t expires, int force)
--
kernel/time/tick-oneshot.c-47-
kernel/time/tick-oneshot.c:48: return clockevents_program_event(dev, expires, force);
kernel/time/tick-oneshot.c-49-}
--
kernel/time/tick-oneshot.c=54=void tick_resume_oneshot(void)
--
kernel/time/tick-oneshot.c-58- clockevents_switch_state(dev, CLOCK_EVT_STATE_ONESHOT);
kernel/time/tick-oneshot.c:59: clockevents_program_event(dev, ktime_get(), true);
kernel/time/tick-oneshot.c-60-}
--
kernel/time/tick-oneshot.c=72=void tick_setup_oneshot(struct clock_event_device *newdev,
--
kernel/time/tick-oneshot.c-77- clockevents_switch_state(newdev, CLOCK_EVT_STATE_ONESHOT);
kernel/time/tick-oneshot.c:78: clockevents_program_event(newdev, next_event, true);
kernel/time/tick-oneshot.c-79-}
--
kernel/time/timekeeping.c=841=static void timekeeping_forward_now(struct timekeeper *tk)
--
kernel/time/timekeeping.c-877- * Utilizing this avoids two clocksource reads for such devices, the
kernel/time/timekeeping.c:878: * ktime_get() in clockevents_program_event() to calculate the delta expiry
kernel/time/timekeeping.c-879- * value and the readout in the device::set_next_event() callback to
--
tools/perf/Documentation/perf-intel-pt.txt=1365=perf script can be used to provide an instruction trace
--
tools/perf/Documentation/perf-intel-pt.txt-1384- :1440 1440 ffffffffbb66664b lapic_next_deadline+0x2b ([guest.kernel.kallsyms]) retq IPC: 0.16 (4/25)
tools/perf/Documentation/perf-intel-pt.txt:1385: :1440 1440 ffffffffbb74607f clockevents_program_event+0x8f ([guest.kernel.kallsyms]) test %eax, %eax
tools/perf/Documentation/perf-intel-pt.txt:1386: :1440 1440 ffffffffbb746081 clockevents_program_event+0x91 ([guest.kernel.kallsyms]) jz 0xffffffffbb74603c IPC: 0.06 (2/30)
tools/perf/Documentation/perf-intel-pt.txt:1387: :1440 1440 ffffffffbb74603c clockevents_program_event+0x4c ([guest.kernel.kallsyms]) popq %rbx
tools/perf/Documentation/perf-intel-pt.txt:1388: :1440 1440 ffffffffbb74603d clockevents_program_event+0x4d ([guest.kernel.kallsyms]) popq %r12
tools/perf/Documentation/perf-intel-pt.txt-1389-
]
|
| 22/2 |
2026/05/25 17:32 |
llm |
expert |
0m
Model:
Tokens:
input: 54763
output: 23
thoughts: 21
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Diving into the Clockevents Implementation**
Alright, let's zero in on `kernel/time/clockevents.c` around line 339. I'm specifically interested in understanding how the clock event device handling is structured at this point in the code. I anticipate that this section is likely dealing with interrupt handling or registration of the clockevent device, perhaps the initialization path related to the underlying hardware timer. I want to see how the kernel interacts with the hardware, how it handles the interrupts generated by the timer, and how those interrupts eventually propagate to the scheduler. Looking for the core logic around enabling, disabling, and scheduling the clock events. It's likely that I'll find the interface definitions used to set the rate, read the current value of the timer, or set an expected future event. I'll be looking to see if it makes use of any of the generic timer infrastructure as well. I'm expecting to find either a hardware-specific implementation or a hardware-abstraction layer dealing with how interrupts are delivered to the system. Understanding this is key to performance and low-latency scheduling. Time to get to it.
|
| 23/2 |
2026/05/25 17:32 |
tool |
read-file |
0m
Args: map[File:kernel/time/clockevents.c]
Results: map[Contents:// SPDX-License-Identifier: GPL-2.0
/*
* This file contains functions which manage clock event devices.
*
* Copyright(C) 2005-2006, Linutronix GmbH, Thomas Gleixner <tglx@kernel.org>
* Copyright(C) 2005-2007, Red Hat, Inc., Ingo Molnar
* Copyright(C) 2006-2007, Timesys Corp., Thomas Gleixner
*/
#include <linux/clockchips.h>
#include <linux/hrtimer.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/smp.h>
#include <linux/device.h>
#include "tick-internal.h"
/* The registered clock event devices */
static LIST_HEAD(clockevent_devices);
static LIST_HEAD(clockevents_released);
/* Protection for the above */
static DEFINE_RAW_SPINLOCK(clockevents_lock);
/* Protection for unbind operations */
static DEFINE_MUTEX(clockevents_mutex);
struct ce_unbind {
struct clock_event_device *ce;
int res;
};
static u64 cev_delta2ns(unsigned long latch, struct clock_event_device *evt,
bool ismax)
{
u64 clc = (u64) latch << evt->shift;
u64 rnd;
if (WARN_ON(!evt->mult))
evt->mult = 1;
rnd = (u64) evt->mult - 1;
/*
* Upper bound sanity check. If the backwards conversion is
* not equal latch, we know that the above shift overflowed.
*/
if ((clc >> evt->shift) != (u64)latch)
clc = ~0ULL;
/*
* Scaled math oddities:
*
* For mult <= (1 << shift) we can safely add mult - 1 to
* prevent integer rounding loss. So the backwards conversion
* from nsec to device ticks will be correct.
*
* For mult > (1 << shift), i.e. device frequency is > 1GHz we
* need to be careful. Adding mult - 1 will result in a value
* which when converted back to device ticks can be larger
* than latch by up to (mult - 1) >> shift. For the min_delta
* calculation we still want to apply this in order to stay
* above the minimum device ticks limit. For the upper limit
* we would end up with a latch value larger than the upper
* limit of the device, so we omit the add to stay below the
* device upper boundary.
*
* Also omit the add if it would overflow the u64 boundary.
*/
if ((~0ULL - clc > rnd) &&
(!ismax || evt->mult <= (1ULL << evt->shift)))
clc += rnd;
do_div(clc, evt->mult);
/* Deltas less than 1usec are pointless noise */
return clc > 1000 ? clc : 1000;
}
/**
* clockevent_delta2ns - Convert a latch value (device ticks) to nanoseconds
* @latch: value to convert
* @evt: pointer to clock event device descriptor
*
* Math helper, returns latch value converted to nanoseconds (bound checked)
*/
u64 clockevent_delta2ns(unsigned long latch, struct clock_event_device *evt)
{
return cev_delta2ns(latch, evt, false);
}
EXPORT_SYMBOL_GPL(clockevent_delta2ns);
static int __clockevents_switch_state(struct clock_event_device *dev,
enum clock_event_state state)
{
if (dev->features & CLOCK_EVT_FEAT_DUMMY)
return 0;
/* On state transitions clear the forced flag unconditionally */
dev->next_event_forced = 0;
/* Transition with new state-specific callbacks */
switch (state) {
case CLOCK_EVT_STATE_DETACHED:
/* The clockevent device is getting replaced. Shut it down. */
case CLOCK_EVT_STATE_SHUTDOWN:
if (dev->set_state_shutdown)
return dev->set_state_shutdown(dev);
return 0;
case CLOCK_EVT_STATE_PERIODIC:
/* Core internal bug */
if (!(dev->features & CLOCK_EVT_FEAT_PERIODIC))
return -ENOSYS;
if (dev->set_state_periodic)
return dev->set_state_periodic(dev);
return 0;
case CLOCK_EVT_STATE_ONESHOT:
/* Core internal bug */
if (!(dev->features & CLOCK_EVT_FEAT_ONESHOT))
return -ENOSYS;
if (dev->set_state_oneshot)
return dev->set_state_oneshot(dev);
return 0;
case CLOCK_EVT_STATE_ONESHOT_STOPPED:
/* Core internal bug */
if (WARN_ONCE(!clockevent_state_oneshot(dev),
"Current state: %d\n",
clockevent_get_state(dev)))
return -EINVAL;
if (dev->set_state_oneshot_stopped)
return dev->set_state_oneshot_stopped(dev);
else
return -ENOSYS;
default:
return -ENOSYS;
}
}
/**
* clockevents_switch_state - set the operating state of a clock event device
* @dev: device to modify
* @state: new state
*
* Must be called with interrupts disabled !
*/
void clockevents_switch_state(struct clock_event_device *dev,
enum clock_event_state state)
{
if (clockevent_get_state(dev) != state) {
if (__clockevents_switch_state(dev, state))
return;
clockevent_set_state(dev, state);
/*
* A nsec2cyc multiplicator of 0 is invalid and we'd crash
* on it, so fix it up and emit a warning:
*/
if (clockevent_state_oneshot(dev)) {
if (WARN_ON(!dev->mult))
dev->mult = 1;
}
}
}
/**
* clockevents_shutdown - shutdown the device and clear next_event
* @dev: device to shutdown
*/
void clockevents_shutdown(struct clock_event_device *dev)
{
clockevents_switch_state(dev, CLOCK_EVT_STATE_SHUTDOWN);
dev->next_event = KTIME_MAX;
dev->next_event_forced = 0;
}
/**
* clockevents_tick_resume - Resume the tick device before using it again
* @dev: device to resume
*/
int clockevents_tick_resume(struct clock_event_device *dev)
{
int ret = 0;
if (dev->tick_resume)
ret = dev->tick_resume(dev);
return ret;
}
#ifdef CONFIG_GENERIC_CLOCKEVENTS_MIN_ADJUST
/* Limit min_delta to a jiffy */
#define MIN_DELTA_LIMIT (NSEC_PER_SEC / HZ)
/**
* clockevents_increase_min_delta - raise minimum delta of a clock event device
* @dev: device to increase the minimum delta
*
* Returns 0 on success, -ETIME when the minimum delta reached the limit.
*/
static int clockevents_increase_min_delta(struct clock_event_device *dev)
{
/* Nothing to do if we already reached the limit */
if (dev->min_delta_ns >= MIN_DELTA_LIMIT) {
printk_deferred(KERN_WARNING
"CE: Reprogramming failure. Giving up\n");
dev->next_event = KTIME_MAX;
return -ETIME;
}
if (dev->min_delta_ns < 5000)
dev->min_delta_ns = 5000;
else
dev->min_delta_ns += dev->min_delta_ns >> 1;
if (dev->min_delta_ns > MIN_DELTA_LIMIT)
dev->min_delta_ns = MIN_DELTA_LIMIT;
printk_deferred(KERN_WARNING
"CE: %s increased min_delta_ns to %llu nsec\n",
dev->name ? dev->name : "?",
(unsigned long long) dev->min_delta_ns);
return 0;
}
/**
* clockevents_program_min_delta - Set clock event device to the minimum delay.
* @dev: device to program
*
* Returns 0 on success, -ETIME when the retry loop failed.
*/
static int clockevents_program_min_delta(struct clock_event_device *dev)
{
unsigned long long clc;
int64_t delta;
int i;
for (i = 0;;) {
delta = dev->min_delta_ns;
dev->next_event = ktime_add_ns(ktime_get(), delta);
if (clockevent_state_shutdown(dev))
return 0;
dev->retries++;
clc = ((unsigned long long) delta * dev->mult) >> dev->shift;
if (dev->set_next_event((unsigned long) clc, dev) == 0)
return 0;
if (++i > 2) {
/*
* We tried 3 times to program the device with the
* given min_delta_ns. Try to increase the minimum
* delta, if that fails as well get out of here.
*/
if (clockevents_increase_min_delta(dev))
return -ETIME;
i = 0;
}
}
}
#else /* CONFIG_GENERIC_CLOCKEVENTS_MIN_ADJUST */
/**
* clockevents_program_min_delta - Set clock event device to the minimum delay.
* @dev: device to program
*
* Returns 0 on success, -ETIME when the retry loop failed.
*/
static int clockevents_program_min_delta(struct clock_event_device *dev)
{
unsigned long long clc;
int64_t delta = 0;
int i;
for (i = 0; i < 10; i++) {
delta += dev->min_delta_ns;
dev->next_event = ktime_add_ns(ktime_get(), delta);
if (clockevent_state_shutdown(dev))
return 0;
dev->retries++;
clc = ((unsigned long long) delta * dev->mult) >> dev->shift;
if (dev->set_next_event((unsigned long) clc, dev) == 0)
return 0;
}
return -ETIME;
}
#endif /* CONFIG_GENERIC_CLOCKEVENTS_MIN_ADJUST */
#ifdef CONFIG_GENERIC_CLOCKEVENTS_COUPLED
#ifdef CONFIG_GENERIC_CLOCKEVENTS_COUPLED_INLINE
#include <asm/clock_inlined.h>
#else
static __always_inline void
arch_inlined_clockevent_set_next_coupled(u64 u64 cycles, struct clock_event_device *dev) { }
#endif
static inline bool clockevent_set_next_coupled(struct clock_event_device *dev, ktime_t expires)
{
u64 cycles;
if (unlikely(!(dev->features & CLOCK_EVT_FEAT_CLOCKSOURCE_COUPLED)))
return false;
if (unlikely(!ktime_expiry_to_cycles(dev->cs_id, expires, &cycles)))
return false;
if (IS_ENABLED(CONFIG_GENERIC_CLOCKEVENTS_COUPLED_INLINE))
arch_inlined_clockevent_set_next_coupled(cycles, dev);
else
dev->set_next_coupled(cycles, dev);
return true;
}
#else
static inline bool clockevent_set_next_coupled(struct clock_event_device *dev, ktime_t expires)
{
return false;
}
#endif
/**
* clockevents_program_event - Reprogram the clock event device.
* @dev: device to program
* @expires: absolute expiry time (monotonic clock)
* @force: program minimum delay if expires can not be set
*
* Returns 0 on success, -ETIME when the event is in the past.
*/
int clockevents_program_event(struct clock_event_device *dev, ktime_t expires, bool force)
{
int64_t delta;
u64 cycles;
if (WARN_ON_ONCE(expires < 0))
return -ETIME;
dev->next_event = expires;
if (clockevent_state_shutdown(dev))
return 0;
/* We must be in ONESHOT state here */
WARN_ONCE(!clockevent_state_oneshot(dev), "Current state: %d\n",
clockevent_get_state(dev));
/* ktime_t based reprogramming for the broadcast hrtimer device */
if (unlikely(dev->features & CLOCK_EVT_FEAT_HRTIMER))
return dev->set_next_ktime(expires, dev);
if (likely(clockevent_set_next_coupled(dev, expires)))
return 0;
delta = ktime_to_ns(ktime_sub(expires, ktime_get()));
/* Required for tick_periodic() during early boot */
if (delta <= 0 && !force)
return -ETIME;
if (delta > (int64_t)dev->min_delta_ns) {
delta = min(delta, (int64_t) dev->max_delta_ns);
cycles = ((u64)delta * dev->mult) >> dev->shift;
if (!dev->set_next_event((unsigned long) cycles, dev)) {
dev->next_event_forced = 0;
return 0;
}
}
if (dev->next_event_forced)
return 0;
if (dev->set_next_event(dev->min_delta_ticks, dev)) {
if (!force || clockevents_program_min_delta(dev))
return -ETIME;
}
dev->next_event_forced = 1;
return 0;
}
/*
* Called after a clockevent has been added which might
* have replaced a current regular or broadcast device. A
* released normal device might be a suitable replacement
* for the current broadcast device. Similarly a released
* broadcast device might be a suitable replacement for a
* normal device.
*/
static void clockevents_notify_released(void)
{
struct clock_event_device *dev;
/*
* Keep iterating as long as tick_check_new_device()
* replaces a device.
*/
while (!list_empty(&clockevents_released)) {
dev = list_entry(clockevents_released.next,
struct clock_event_device, list);
list_move(&dev->list, &clockevent_devices);
tick_check_new_device(dev);
}
}
/*
* Try to install a replacement clock event device
*/
static int clockevents_replace(struct clock_event_device *ced)
{
struct clock_event_device *dev, *newdev = NULL;
list_for_each_entry(dev, &clockevent_devices, list) {
if (dev == ced || !clockevent_state_detached(dev))
continue;
if (!tick_check_replacement(newdev, dev))
continue;
if (!try_module_get(dev->owner))
continue;
if (newdev)
module_put(newdev->owner);
newdev = dev;
}
if (newdev) {
tick_install_replacement(newdev);
list_del_init(&ced->list);
}
return newdev ? 0 : -EBUSY;
}
/*
* Called with clockevents_mutex and clockevents_lock held
*/
static int __clockevents_try_unbind(struct clock_event_device *ced, int cpu)
{
/* Fast track. Device is unused */
if (clockevent_state_detached(ced)) {
list_del_init(&ced->list);
return 0;
}
return ced == per_cpu(tick_cpu_device, cpu).evtdev ? -EAGAIN : -EBUSY;
}
/*
* SMP function call to unbind a device
*/
static void __clockevents_unbind(void *arg)
{
struct ce_unbind *cu = arg;
int res;
raw_spin_lock(&clockevents_lock);
res = __clockevents_try_unbind(cu->ce, smp_processor_id());
if (res == -EAGAIN)
res = clockevents_replace(cu->ce);
cu->res = res;
raw_spin_unlock(&clockevents_lock);
}
/*
* Issues smp function call to unbind a per cpu device. Called with
* clockevents_mutex held.
*/
static int clockevents_unbind(struct clock_event_device *ced, int cpu)
{
struct ce_unbind cu = { .ce = ced, .res = -ENODEV };
smp_call_function_single(cpu, __clockevents_unbind, &cu, 1);
return cu.res;
}
/*
* Unbind a clockevents device.
*/
int clockevents_unbind_device(struct clock_event_device *ced, int cpu)
{
int ret;
mutex_lock(&clockevents_mutex);
ret = clockevents_unbind(ced, cpu);
mutex_unlock(&clockevents_mutex);
return ret;
}
EXPORT_SYMBOL_GPL(clockevents_unbind_device);
/**
* clockevents_register_device - register a clock event device
* @dev: device to register
*/
void clockevents_register_device(struct clock_event_device *dev)
{
unsigned long flags;
/* Initialize state to DETACHED */
clockevent_set_state(dev, CLOCK_EVT_STATE_DETACHED);
if (!dev->cpumask) {
WARN_ON(num_possible_cpus() > 1);
dev->cpumask = cpumask_of(smp_processor_id());
}
if (dev->cpumask == cpu_all_mask) {
WARN(1, "%s cpumask == cpu_all_mask, using cpu_possible_mask instead\n",
dev->name);
dev->cpumask = cpu_possible_mask;
}
raw_spin_lock_irqsave(&clockevents_lock, flags);
list_add(&dev->list, &clockevent_devices);
tick_check_new_device(dev);
clockevents_notify_released();
raw_spin_unlock_irqrestore(&clockevents_lock, flags);
}
EXPORT_SYMBOL_GPL(clockevents_register_device);
static void clockevents_config(struct clock_event_device *dev, u32 freq)
{
u64 sec;
if (!(dev->features & CLOCK_EVT_FEAT_ONESHOT))
return;
/*
* Calculate the maximum number of seconds we can sleep. Limit
* to 10 minutes for hardware which can program more than
* 32bit ticks so we still get reasonable conversion values.
*/
sec = dev->max_delta_ticks;
do_div(sec, freq);
if (!sec)
sec = 1;
else if (sec > 600 && dev->max_delta_ticks > UINT_MAX)
sec = 600;
clockevents_calc_mult_shift(dev, freq, sec);
dev->min_delta_ns = cev_delta2ns(dev->min_delta_ticks, dev, false);
dev->max_delta_ns = cev_delta2ns(dev->max_delta_ticks, dev, true);
}
/**
* clockevents_config_and_register - Configure and register a clock event device
* @dev: device to register
* @freq: The clock frequency
* @min_delta: The minimum clock ticks to program in oneshot mode
* @max_delta: The maximum clock ticks to program in oneshot mode
*
* min/max_delta can be 0 for devices which do not support oneshot mode.
*/
void clockevents_config_and_register(struct clock_event_device *dev,
u32 freq, unsigned long min_delta,
unsigned long max_delta)
{
dev->min_delta_ticks = min_delta;
dev->max_delta_ticks = max_delta;
clockevents_config(dev, freq);
clockevents_register_device(dev);
}
EXPORT_SYMBOL_GPL(clockevents_config_and_register);
int __clockevents_update_freq(struct clock_event_device *dev, u32 freq)
{
clockevents_config(dev, freq);
if (clockevent_state_oneshot(dev))
return clockevents_program_event(dev, dev->next_event, false);
if (clockevent_state_periodic(dev))
return __clockevents_switch_state(dev, CLOCK_EVT_STATE_PERIODIC);
return 0;
}
/**
* clockevents_update_freq - Update frequency and reprogram a clock event device.
* @dev: device to modify
* @freq: new device frequency
*
* Reconfigure and reprogram a clock event device in oneshot
* mode. Must be called on the cpu for which the device delivers per
* cpu timer events. If called for the broadcast device the core takes
* care of serialization.
*
* Returns 0 on success, -ETIME when the event is in the past.
*/
int clockevents_update_freq(struct clock_event_device *dev, u32 freq)
{
unsigned long flags;
int ret;
local_irq_save(flags);
ret = tick_broadcast_update_freq(dev, freq);
if (ret == -ENODEV)
ret = __clockevents_update_freq(dev, freq);
local_irq_restore(flags);
return ret;
}
/*
* Noop handler when we shut down an event device
*/
void clockevents_handle_noop(struct clock_event_device *dev)
{
}
/**
* clockevents_exchange_device - release and request clock devices
* @old: device to release (can be NULL)
* @new: device to request (can be NULL)
*
* Called from various tick functions with clockevents_lock held and
* interrupts disabled.
*/
void clockevents_exchange_device(struct clock_event_device *old,
struct clock_event_device *new)
{
/*
* Caller releases a clock event device. We queue it into the
* released list and do a notify add later.
*/
if (old) {
module_put(old->owner);
clockevents_switch_state(old, CLOCK_EVT_STATE_DETACHED);
list_move(&old->list, &clockevents_released);
}
if (new) {
BUG_ON(!clockevent_state_detached(new));
clockevents_shutdown(new);
}
}
/**
* clockevents_suspend - suspend clock devices
*/
void clockevents_suspend(void)
{
struct clock_event_device *dev;
list_for_each_entry_reverse(dev, &clockevent_devices, list)
if (dev->suspend && !clockevent_state_detached(dev))
dev->suspend(dev);
}
/**
* clockevents_resume - resume clock devices
*/
void clockevents_resume(void)
{
struct clock_event_device *dev;
list_for_each_entry(dev, &clockevent_devices, list)
if (dev->resume && !clockevent_state_detached(dev))
dev->resume(dev);
}
#ifdef CONFIG_HOTPLUG_CPU
/**
* tick_offline_cpu - Shutdown all clock events related
* to this CPU and take it out of the
* broadcast mechanism.
* @cpu: The outgoing CPU
*
* Called by the dying CPU during teardown.
*/
void tick_offline_cpu(unsigned int cpu)
{
struct clock_event_device *dev, *tmp;
raw_spin_lock(&clockevents_lock);
tick_broadcast_offline(cpu);
tick_shutdown();
/*
* Unregister the clock event devices which were
* released above.
*/
list_for_each_entry_safe(dev, tmp, &clockevents_released, list)
list_del(&dev->list);
/*
* Now check whether the CPU has left unused per cpu devices
*/
list_for_each_entry_safe(dev, tmp, &clockevent_devices, list) {
if (cpumask_test_cpu(cpu, dev->cpumask) &&
cpumask_weight(dev->cpumask) == 1 &&
!tick_is_broadcast_device(dev)) {
BUG_ON(!clockevent_state_detached(dev));
list_del(&dev->list);
}
}
raw_spin_unlock(&clockevents_lock);
}
#endif
#ifdef CONFIG_SYSFS
static const struct bus_type clockevents_subsys = {
.name = "clockevents",
.dev_name = "clockevent",
};
static DEFINE_PER_CPU(struct device, tick_percpu_dev);
static struct tick_device *tick_get_tick_dev(struct device *dev);
static ssize_t current_device_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct tick_device *td;
ssize_t count = 0;
raw_spin_lock_irq(&clockevents_lock);
td = tick_get_tick_dev(dev);
if (td && td->evtdev)
count = sysfs_emit(buf, "%s\n", td->evtdev->name);
raw_spin_unlock_irq(&clockevents_lock);
return count;
}
static DEVICE_ATTR_RO(current_device);
/* We don't support the abomination of removable broadcast devices */
static ssize_t unbind_device_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
char name[CS_NAME_LEN];
ssize_t ret = sysfs_get_uname(buf, name, count);
struct clock_event_device *ce = NULL, *iter;
if (ret < 0)
return ret;
ret = -ENODEV;
mutex_lock(&clockevents_mutex);
raw_spin_lock_irq(&clockevents_lock);
list_for_each_entry(iter, &clockevent_devices, list) {
if (!strcmp(iter->name, name)) {
ret = __clockevents_try_unbind(iter, dev->id);
ce = iter;
break;
}
}
raw_spin_unlock_irq(&clockevents_lock);
/*
* We hold clockevents_mutex, so ce can't go away
*/
if (ret == -EAGAIN)
ret = clockevents_unbind(ce, dev->id);
mutex_unlock(&clockevents_mutex);
return ret ? ret : count;
}
static DEVICE_ATTR_WO(unbind_device);
#ifdef CONFIG_GENERIC_CLOCKEVENTS_BROADCAST
static struct device tick_bc_dev = {
.init_name = "broadcast",
.id = 0,
.bus = &clockevents_subsys,
};
static struct tick_device *tick_get_tick_dev(struct device *dev)
{
return dev == &tick_bc_dev ? tick_get_broadcast_device() :
&per_cpu(tick_cpu_device, dev->id);
}
static __init int tick_broadcast_init_sysfs(void)
{
int err = device_register(&tick_bc_dev);
if (!err)
err = device_create_file(&tick_bc_dev, &dev_attr_current_device);
return err;
}
#else
static struct tick_device *tick_get_tick_dev(struct device *dev)
{
return &per_cpu(tick_cpu_device, dev->id);
}
static inline int tick_broadcast_init_sysfs(void) { return 0; }
#endif
static int __init tick_init_sysfs(void)
{
int cpu;
for_each_possible_cpu(cpu) {
struct device *dev = &per_cpu(tick_percpu_dev, cpu);
int err;
dev->id = cpu;
dev->bus = &clockevents_subsys;
err = device_register(dev);
if (!err)
err = device_create_file(dev, &dev_attr_current_device);
if (!err)
err = device_create_file(dev, &dev_attr_unbind_device);
if (err)
return err;
}
return tick_broadcast_init_sysfs();
}
static int __init clockevents_init_sysfs(void)
{
int err = subsys_system_register(&clockevents_subsys, NULL);
if (!err)
err = tick_init_sysfs();
return err;
}
device_initcall(clockevents_init_sysfs);
#endif /* SYSFS */
]
|
| 24/2 |
2026/05/25 17:32 |
llm |
expert |
0m
Model:
Tokens:
input: 62467
output: 24
thoughts: 1313
Thoughts: **Data Race Analysis: hrtimer_interrupt**
Okay, so I'm looking at this KCSAN report, and it screams data race, specifically involving `hrtimer_interrupt`. The report points to a write of 8 bytes to `0xffff888237d17ba0` happening in `hrtimer_interrupt` at line 2092 of `kernel/time/hrtimer.c`. That line is `dev->next_event_forced = 0;`, so that's a 4-byte write. But the trace says 8 bytes were written... That must be `dev->next_event = KTIME_MAX;`, which is line 2091!
But wait a minute... the value *changed* from `0x0000001e0bd33790` to `0x0000001e0bfaba80`. That's *not* `KTIME_MAX` which is `0x7fffffffffffffff`. Okay, so `dev->next_event` *is* set to `KTIME_MAX` at line 2091. Then `hrtimer_interrupt` calls a bunch of functions ending in `clockevents_program_event` which sets `dev->next_event` to a *new* expiry time, an 8-byte write!
The crucial thing is that `clockevents_program_event` *isn't* at line 2092. The stack trace shows the write *starts* from line 2092, but goes further. The value change reported by KCSAN means the *before* value was the first number, and the *after* value the second. If the interrupt handler writes `KTIME_MAX` initially *and* then later writes a *different* value (the `expires_next` time), KCSAN's watchpoint would catch it, reporting the initial and final values. Okay, so that must be it.
The report says it saw the value change from what it was *before* the interrupt, to what it was *after*. And it's an 8-byte write. I'm focusing in on line 2090 `cpu_base->nr_events++`. Is it possible that the write is incrementing `cpu_base->nr_events`, but the stack trace says otherwise. Checking the code confirms it. So the write is *definitely* to `dev->next_event`.
So, it's clear: the race is between the initial `dev->next_event = KTIME_MAX` write and the subsequent `clockevents_program_event` call which programs the device with a new `expires`. KCSAN is showing that the read is happening between those two writes within the same interrupt handler, which is why it captures the change from the old value to the new.
|
| 25/2 |
2026/05/25 17:33 |
tool |
codesearch-struct-layout |
0m
Args: map[Name:hrtimer_cpu_base]
Results: map[Fields:[map[Name:lock OffsetBits:0 SizeBits:32] map[Name:cpu OffsetBits:32 SizeBits:32] map[Name:active_bases OffsetBits:64 SizeBits:32] map[Name:clock_was_set_seq OffsetBits:96 SizeBits:32] map[Name:hres_active OffsetBits:128 SizeBits:8] map[Name:deferred_rearm OffsetBits:136 SizeBits:8] map[Name:deferred_needs_update OffsetBits:144 SizeBits:8] map[Name:hang_detected OffsetBits:152 SizeBits:8] map[Name:softirq_activated OffsetBits:160 SizeBits:8] map[Name:online OffsetBits:168 SizeBits:8] map[Name:nr_events OffsetBits:192 SizeBits:32] map[Name:nr_retries OffsetBits:224 SizeBits:16] map[Name:nr_hangs OffsetBits:240 SizeBits:16] map[Name:max_hang_time OffsetBits:256 SizeBits:32] map[Name:expires_next OffsetBits:320 SizeBits:64] map[Name:next_timer OffsetBits:384 SizeBits:64] map[Name:softirq_expires_next OffsetBits:448 SizeBits:64] map[Name:softirq_next_timer OffsetBits:512 SizeBits:64] map[Name:deferred_expires_next OffsetBits:576 SizeBits:64] map[Name:clock_base OffsetBits:1024 SizeBits:4096] map[Name:csd OffsetBits:5120 SizeBits:256]]]
|
| 26/2 |
2026/05/25 17:33 |
llm |
expert |
0m
Model:
Tokens:
input: 64900
output: 21
thoughts: 3177
Thoughts: **Data Race Analysis: `dev->next_event` in `hrtimer_interrupt` and `/proc/timer_list`**
Okay, so KCSAN flagged a data race. My first thought was the usual suspects: `nr_events` and the write size versus the read size. But, that quickly went off the rails. It seems `print_tickdevice` (which is what `/proc/timer_list` is calling), is reading something at `timer_list.c:204` but that line is definitely about `dev->retries`. This doesn't make sense since `hrtimer_interrupt` shouldn't be writing to that.
Okay, let's step back and look at the layout of `clock_event_device`. Ah, `next_event` is at offset 32 bytes and `retries` is at 80. Then, there's `next_event_forced` at offset 76. The KCSAN report says there's a 8-byte write. Could it be an optimization that writes both `next_event_forced` (4 bytes) and `retries` (8 bytes) at the same time? Nope, they are in different 8-byte aligned words.
Wait, is the problem the line number? Is the read *actually* `dev->retries`, as the report indicates, or is the line numbers slightly wrong? The KCSAN report shows an 8-byte write, but a *different* 8-byte read location. Hmmm. Let's look at `print_tickdevice` again. Okay, line 191 is:
`SEQ_printf(m, " next_event: %Ld nsecs\n", (unsigned long long) ktime_to_ns(dev->next_event));`
Yes, `ktime_to_ns` is the important bit. Line 191 is definitely reading `dev->next_event`, but KCSAN insists it is at `timer_list.c:204`, which is `dev->retries`. Something seems off with the line number reporting.
Okay, let's look at the assembly. `hrtimer_interrupt` is the write, that much is certain. It writes `dev->next_event = KTIME_MAX;` at line 2092. The KCSAN report shows the value changed from 130s to 130.002s. If the write is indeed `dev->next_event = KTIME_MAX;`, this would indicate that the write did not *finish* before the other read. Okay, KCSAN's magic means the watchpoint is likely removed AFTER the write by `hrtimer_interrupt` and that would be consistent with the timing of the race.
Aha! `hrtimer_interrupt` first sets `dev->next_event = KTIME_MAX`, then calls `hrtimer_interrupt_rearm`, which ultimately calls `clockevents_program_event`. This later call then sets `dev->next_event` to the *actual* expiry time. So, KCSAN would have captured the value after it was *re-set* by `clockevents_program_event`, after the interrupt handler had already run.
So the race is definitely on `dev->next_event`, and I think I've figured out why the changed value reported by KCSAN might make sense.
Now, is this a problem? Let's verify that the read in `print_tickdevice` doesn't use locks. It's called from `timer_list_show` which reads `dev->next_event` and `dev->retries` (and other bits of the tick device) without any explicit locking to synchronize with the `hrtimer_interrupt`. Yes, it's a data race.
But, is it exploitable? `print_tickdevice` is just printing to `/proc/timer_list`. So the worst case is a garbage value being printed due to a torn read. It *doesn't* impact control flow or memory safety. The read is just an information leak of a corrupted timestamp. It's harmless. And I think `/proc/timer_list` requires root access, which makes it even less dangerous.
Even better, on an x86-64 machine, the read and write of a single 64-bit value should be atomic, especially if the `ktime_t` is aligned, so it's probably *already* benign. I'll double check that `ktime_t` is 8-byte aligned.
Yup, it is aligned. So the read and write are atomic. Even if they weren't, the worst-case is just a garbage value
|
| 27/2 |
2026/05/25 17:33 |
tool |
grepper |
0m
Args: map[Expression:proc_create.*timer_list]
Results: map[Output:kernel/time/timer_list.c=349=static int __init init_timer_list_procfs(void)
--
kernel/time/timer_list.c-352-
kernel/time/timer_list.c:353: pe = proc_create_seq_private("timer_list", 0400, NULL, &timer_list_sops,
kernel/time/timer_list.c-354- sizeof(struct timer_list_iter), NULL);
]
|
| 28/2 |
2026/05/25 17:33 |
llm |
expert |
0m
Model:
Tokens:
input: 69255
output: 66
thoughts: 3127
Thoughts: **Analysis of the Timer List Data Race**
Okay, so let's break this down systematically. We're looking at a potential data race within the timer mechanism, specifically related to `/proc/timer_list`. First, the permissions on `/proc/timer_list` are `0400`, meaning only the root user can read it. This immediately limits its exposure to unprivileged processes and user namespaces, as only the global root can access the file.
The trace indicates a write to `dev->next_event` in `hrtimer_interrupt`, likely setting it to `KTIME_MAX`. The read happens during the generation of the `/proc/timer_list` output, specifically within `print_tickdevice`. The stack trace confirms this: the data is being read from the `/proc/timer_list` file when being output.
Syzkaller triggered this and it's running as root, so this aligns perfectly with the fact that only root can read `/proc/timer_list`. Now, the crucial question is the race. The code shows the following sequence of events: in the `hrtimer_interrupt` handler the `dev->next_event` is written: `dev->next_event = KTIME_MAX;` at line 2092 (or 2091 depending on debug info). The read is later during the printing of information, specifically at line 204 or line 190.
I've checked the different possible avenues for a data race. There are other reads to `dev->next_event`, but they are protected by locks (either per-CPU locks or broadcast locks, or disabling interrupts in the case of `__clockevents_update_freq` and `tick_oneshot_wakeup_control`), ruling out any possible race. In fact, `print_tickdevice` seems to be the only code that reads `dev->next_event` that isn't locked.
Now, let's consider the details of the possible race on `dev->next_event`. It's a timestamp, not a retry counter, the values of `0x0000001e0bd33790 -> 0x0000001e0bfaba80` are the values of the `next_event` field. This confirms it is a timestamp value and it being read unlocked confirms the data race. The write is in an interrupt handler on one CPU (or broadcast), and the read is from a process reading the proc file. There's no mechanism to synchronize these processes on reading that specific value.
The impact is, at worst, a slightly incorrect value being displayed in `/proc/timer_list`. This is an informational data race, and it is a read-only process, which means it will never corrupt the value read. Because this is a read-only, informational data race accessible only to root, it's not remotely exploitable, it's not a denial-of-service, and it can't be triggered remotely. It is an extremely low-severity, benign data race and does not have any security implications. I've double checked the line numbers, and it's a completely benign data race.
|
| 29/2 |
2026/05/25 17:34 |
tool |
set-results |
0m
Args: map[DenialOfService:false Exploitable:false FilesystemTrigger:false NetworkTrigger:false PeripheralTrigger:false RemoteTrigger:false Unprivileged:false UserNamespace:false VMGuestTrigger:false VMHostTrigger:false]
Results: map[DenialOfService:false Exploitable:false FilesystemTrigger:false NetworkTrigger:false PeripheralTrigger:false RemoteTrigger:false Unprivileged:false UserNamespace:false VMGuestTrigger:false VMHostTrigger:false]
|
| 30/2 |
2026/05/25 17:34 |
llm |
expert |
0m
Model:
Tokens:
input: 73193
output: 474
thoughts: 331
Thoughts: **Final Response: KCSAN Data-Race Analysis**
Okay, the analysis is complete, and it's time to craft the final response. Let me recap my thinking. The KCSAN report pinpoints a data race between `hrtimer_interrupt` and `print_tickdevice`. The write operation, as the report indicates, happens within `hrtimer_interrupt`, specifically around line 2092, where `dev->next_event` is updated. That's the critical bit; `dev->next_event = KTIME_MAX;` seems to be the culprit.
On the read side, `print_tickdevice`, part of `kernel/time/timer_list.c`, is the function that's being invoked. As I understand it, `print_tickdevice` is called when someone reads `/proc/timer_list`. And the value KCSAN reported, `0x0000001e0bd33790`, it's clear as day; that translates to roughly 130 seconds in nanoseconds. That confirms the race involves the `ktime_t next_event` timestamp.
Now, as far as impact goes, I've got to classify this as a benign data race. The read is only used to format information and present it in `/proc/timer_list`, a debug interface. A torn read, or seeing an intermediate value, will just cause a garbage timestamp to be displayed. Crucially, it won't affect the kernel's control flow, memory safety, or trigger any crashes or resource leaks.
Also, it's worth mentioning that `/proc/timer_list` has `0400` permissions and is owned by global root. This means unprivileged users, or even users within a user namespace, can't even access it.
Therefore, given the nature of the data race and the restrictions on access, this bug has no security impact. I'm ready to write the conclusion.
|
| 31/1 |
2026/05/25 17:34 |
action |
format-explanation |
0m
Results: map[Explanation:Based on the analysis of the provided KCSAN data-race report and the kernel
source code, here is the assessment of the bug:
**Bug Mechanism:**
The report indicates a data race on an 8-byte memory location.
- The **write** occurs in `hrtimer_interrupt()` (in `kernel/time/hrtimer.c`),
which updates the clock event device's state. The line number in the report
points to `dev->next_event_forced = 0;`, but the 8-byte write and the values
involved (`0x0000001e0bd33790`, which is ~130 seconds in nanoseconds) confirm
that the actual raced variable is the adjacent `dev->next_event` timestamp
(which is set to `KTIME_MAX` right above it and later reprogrammed).
- The **read** occurs in `print_tickdevice()` (in `kernel/time/timer_list.c`),
which is invoked when user-space reads the `/proc/timer_list` file. It reads
`dev->next_event` locklessly to print the scheduled next event time for
debugging/informational purposes.
**Security Impact:**
1. **Not Exploitable & No Denial of Service:** This is a completely benign data
race. The lockless read is only used to format a string for the
`/proc/timer_list` output. If a race occurs, the worst-case scenario is that a
torn or intermediate timestamp value is printed to the proc file. It does not
corrupt kernel memory, alter control flow, or cause any crashes/hangs.
2. **Not Accessible to Unprivileged Users:** The `/proc/timer_list` file is
created with strict `0400` permissions (read-only for the global root user).
Unprivileged processes cannot open or read this file.
3. **Not Accessible in User Namespaces:** Because `/proc/timer_list` is a global
procfs entry owned by the global root, a process inside a user namespace (even
with namespace-root privileges) cannot bypass the DAC checks to read it.
In conclusion, this is a harmless informational data race restricted to the
global root user, posing no security risk.]
|