-
Notifications
You must be signed in to change notification settings - Fork 1.4k
sched: Introduce High-resolution Timer. #17556
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Conversation
|
You don’t need to make such extensive changes to the kernel just to add hrtimer support, and when you claim that the tests have passed, you should also include the corresponding test cases,test logs |
| flags = spin_lock_irqsave(&g_wdspinlock); | ||
| if (wdog != NULL) | ||
| { | ||
| sched_note_wdog(NOTE_WDOG_CANCEL, (FAR void *)wdog->func, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This PR contains many of redundant modifications unrelated to hrtimers. In particular, the optimizations for the clock subsystem need to be separated and merged independently. From the perspective of hrtimer implementation details, I do not observe any significant differences; instead, your commits include extensive code for ticks/counter conversion.
I recommend merging #17517 first, as this implementation serves as an optional hrtimer configuration for the system and does not alter the underlying clock system implementation. If your implementation is deemed superior, optimizations can be developed based on #17517
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Most of the changes prepared for hrtimer are general and can simplify kernel implementation and reduce kernel latency even without the introduction of hrtimer. I am going to split them into several parts.
I do not support the merging of #17517. I believe the design of that HRTimer is completely flawed and lacks corresponding performance and parallel correctness tests.
This HRTimer design is entirely different from #17517, and there is no basis for the claim that it is an improvement upon it.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not sure if you have taken note of the implementation of hrtimers in HaloOS. In particular, the core logic of the hrtimer_queue component is actually similar to that in HaloOS in terms of both naming and implementation:
https://gitee.com/haloos/vcos_kernel_nuttx/blob/master/sched/hrtimer/hrtimer_queue.h
This naming convention is not commonly adopted—for instance, the Linux kernel uses a different naming approach for equivalent functionality:
https://github.com/torvalds/linux/blob/master/include/linux/hrtimer.h
Additionally, I noticed your first commit was on December 1st, while @wangchdo commit was earlier, right?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not sure if you have taken note of the implementation of hrtimers in HaloOS. In particular, the core logic of the hrtimer_queue component is actually similar to that in HaloOS in terms of both naming and implementation:
https://gitee.com/haloos/vcos_kernel_nuttx/blob/master/sched/hrtimer/hrtimer_queue.h
This naming convention is not commonly adopted—for instance, the Linux kernel uses a different naming approach for equivalent functionality:
https://github.com/torvalds/linux/blob/master/include/linux/hrtimer.h
Additionally, I noticed your first commit was on December 1st, while @wangchdo commit was earlier, right?
![]()
The HRTimer Queue is a zero-performance-overhead, composable, and customizable abstraction that provides only asynchronous-style interfaces:
- hrtimer_queue_start(queue, timer): Asynchronously sends an HRTimer to HRTimer queue.
- hrtimer_queue_async_cancel(queue, timer): Asynchronously cancels an HRTimer and returns the current reference count of the timer.
- hrtimer_queue_wait(queue, timer): Waits for the release of all references to the HRTimer to obtain ownership of the HRTimer data structure.
https://gitee.com/haloos/vcos_kernel_nuttx/blob/master/sched/hrtimer/hrtimer_queue.h This appears to be a implementation of a literal queue based on a heap.
I don't think these two hrtimer_queue have anything in common except for their names.
Parallel test cases added. |
|
By the way, I think your implementation largely builds on the ideas and implementation from the PR I submitted two months ago (such as the RT-tree, the queue abstraction, and the overall motivation): In addition, the state machine design is very similar to the one in the PR I submitted four days ago: |
|
This commit removed nxsched_alarm_tick_expiration to simplify the timer expiration. Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
This commit removed nxsched_alarm_expiration to simplify the timer expiration. Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
This commit moved the g_wdtimernested to sched_timerexpiration, since wdog and hrtimer can share it. Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
Do you think this is a game? Are robustness and performance really the only criteria? Or do you seriously believe my implementation cannot be optimized further? |
Talk is cheap, show me the code/data. |
The current wdog implementation is buggy. This patch primarily makes the following changes:
1. Revert the spinlock to critical_section.
If the wdog use the fine-grained spin-lock, and allow the callback
execution without the lock held, there will be incorrect synchronization.
E.g.
The first `nxsem_timeout` callback function caused the second semaphore wait to fail.
Core 0 [nxsem_clockwait] | Core 1
enter_critical_section() | ...
wd_start(nxsem_timeout) | ...
nxsem_wait(sem) | wd_expiration() --> nxsem_timeout
wd_cancel(&rtcb->waitdog) | enter_critical_section()
leave_critical_section() | Waiting...
....nxsem_clockwait | Waiting...
enter_critical_section() | Waiting...
wd_start(nxsem_timeout) | Waiting...
nxsem_wait(sem) | Core 1 enter the critical section
| nxsem_wait_irq(wtcb, ETIMEDOUT) incorrectly wake-up the rtcb.
2. Simplify the expiration.
Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
This commit removed incorrect hrtimer implementation. This implementation can not work well for SMP systems. Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
VELAPLATFO-78974 This commit introduced hrtimer_queue, a resuable component to generate user-defined hrtimer implementation. Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
This commit introduced the high-resolution timer abstraction. The hrtimer design features including: Use a strict state machine: an active timer can not be directly restarted, simplifying the implementation. Abstract the sorted queue for flexibility, allowing different data structures for various use cases. Execute callbacks with interrupts enabled, using hazard pointers to manage references. Clear ownership transfer: callbacks return the next expiration time for periodic timers, and the thread executing the callback is responsible for restarting or releasing the timer. Non-blocking restart: allow restarting a timer even if its callback is still running, requiring proper synchronization in the callback function. Starvation-free cancellation: use hazard pointers to avoid starvation and ensure safe memory reclamation. Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
This commit supported wdog/scheduler hrtimer with tickless enabled. Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
|
Guys, instead of compete to see who implemented first or which implementation has best performance, it is better to work together to get best part of each implementation and contribute a better solution to NuttX. This features is very important to everyone using NuttX (not only LiAuto or Xiaomi). @Fix-Point and @anchao please align between you both how to integrate it in a way that the best interest is the project quality, not individual ego. |
I aready submitted the test code in apps ostest two days ago, don't let me tell you how to check PR, the test checks the precison exactly as 1 nsec, not like your test code allowing margin. |
I agree. The main problem is that NuttX should consider all application scenarios, including IoT devices, automotive, multi-core embedded devices, and etc. But, @wangchdo only considered his I believe the community should encourage better implementations, rather than more meaningless, performance-inefficient, and product-specific implementations. For the HRtimer, I believe my implementation is better in performance, composability and general. So I insist this hrtimer is a better implementation, not just "a optimization for their hrtimer". I suggest they added optimization on this implementation, that's my opinion. By the way, It is so funny that every time @wangchdo claims all I have done looks like his work, although these are completely different things.
|
|
@Fix-Point could you separate the non hrtimer patch to the new pr? |
I am splitting these patches into several parts. |
I don't think it is polite to attack other personally, i am just a personal contributor, not a team working on nuttx, and contribute PRs using my personal time, and they got merged only when are approved by committers or PMC. If you think they are ugly, inefficient or meaningless,you are welcome to provide comments I have merged more than 110 commits (timer or tricore arch related are only a small part of them) without receiving any of your comments |
I have no intention of arguing with anyone. My only hope is for NuttX to become faster and more reliable—nothing more. I respect and understand all community developers because it is their efforts that drive the progress of NuttX. My concern is that you have repeatedly accused me, without any evidence, of making my implementation similar to yours and implied that I used your ideas. This is deeply disrespectful to me. Therefore, I would like to clarify a few facts to show that I did not use your ideas at all, hoping to clear up any misunderstandings.
I believe it is entirely reasonable to replace your implementation with a better one (or refactor it, if that term makes you feel more comfortable). I do not understand why @anchao has been siding with you while ignoring the facts, which has left me disappointed with the community. |
You should use |
Please see this #17567 (comment). The question is we can not sleep or spin in the critical section. We must allow the timer restarting without waiting it finished. |
Can you check this bug-fix PR: #17570, looks like a simple change can fix the issue |
Please pay more respect to parallel programming. It does not look like a simple change can fix this at all. See #17570 (comment). I think you should seriously consider refactoring hrtimer you merged based on this implementation instead of wasting both of our time on a flawed design. |

Summary
High-resolution Timer (HRTimer) is a timer abstraction capable of achieving nanosecond-level timing precision, primarily used in scenarios requiring high-precision clock events. With the advancement of integrated circuit technology, modern high-precision timer hardware (such as the typical x86 HPET) can already meet sub-nanosecond timing requirements and offer femtosecond-level jitter control.
Although the current timer abstraction in the NuttX kernel already supports nanosecond-level timing, its software timer abstraction, wdog, and the timer timeout interrupt handling process remain at microsecond-level (tick) precision, which falls short of high-precision timing demands. Therefore, it is necessary to implement a new timer abstraction—HRTimer, to address the precision limitations of wdog. HRTimer primarily provides the following functional interfaces:
Design
The new NuttX HRTimer is designed to address the issues of insufficient precision and excessively long blocking times in the current NuttX wdog. It draws on the strengths of the Linux HRTimer design while improving upon its weaknesses. The HRTimer design is divided into two parts: the
HRTimer Queueand theHRTimer. TheHRTimer Queueis a reusable component that allows users to freely customize their ownHRTimerinterface by pairing it with a private timer driver, without needing to modify the kernel code.API Design
The HRTimer Queue is a zero-performance-overhead, composable, and customizable abstraction that provides only asynchronous-style interfaces:
All other user interfaces can be composed based on these three interfaces.
On top of the HRTimer Queue, users only need to implement the following interfaces to customize their own HRTimer implementation:
After implementing the above three interfaces, users can use the
HRTIMER_QUEUE_GENERATEtemplate macro to combine and generate their own hrtimer implementation, which mainly includes the following interfaces:try_to_cancel. It ensures that the timer can definitely be canceled successfully, but may need to wait for its callback function to finish execution.The design characteristics of HRTimer are as follows:
Strict and Simplified HRTimer State Machine: In the old wdog design, wdog could be reset in any state, which introduced unnecessary complexity to certain function implementations. For example,
wd_starthad to account for the possibility of restarting. In the new HRTimer design, an HRTimer that has already been started and not canceled cannot be started again.Abstracted Sorting Queue: Since no single design can be optimal for all application scenarios, HRTimer abstracts interfaces for inserting and deleting nodes in the sorting queue. This allows for different data structure implementations to be configured for different application scenarios, as shown in Table 1.
Table 1: Comparison of Several Sorting Queue Implementations
Callback Execution Without Lock Held: HRTimer implements callback execution without lock held, ensuring that the system's blocking time is not limited by the user's callback function. However, this introduces additional states and waits, where waiting for reference release is primarily implemented using hazard pointers. This will be explained in detail in the subsequent state transition diagram.
Clear HRTimer Object Ownership Transfer Path: In the wdog implementation, the wdog callback function could restart the current timer directly without regard to ownership, potentially causing concurrency issues. In the new implementation, the HRTimer callback function cannot restart itself. Instead, inspired by Linux's design, the callback function returns whether a restart is needed. If a restart is required, the thread executing the callback function re-enqueues it; otherwise, the thread releases ownership. This change ensures a clear ownership transfer path for the HRTimer object.
Non-blocking Timer Restart: To address the issue in Linux where restarting a timer must wait for an already-started callback function to finish, which reduces the real-time performance, the new HRTimer implements a non-blocking timer restart mechanism. This mechanism reuses the last bit of the hazard pointer to mark whether the thread executing the callback has lost write ownership of the HRTimer object. After
hrtimer_async_cancelis called, other threads executing callbacks will lose write ownership of the HRTimer (though their callback functions may still be executing). This means the HRTimer can be restarted and repurposed for other callbacks without waiting for the callback function to complete. However, note that the callback function might still be executing, requiring users to consider this concurrency and implement proper synchronization mechanisms within their callback functions. To explicitly remind users of this concurrency, an HRTimer whose callback function has not yet completed execution must be restarted usinghrtimer_restart. This function relaxes the state checks on the HRTimer, allowing a timer with the callback running to be started.Deterministic Timer Cancellation: To address the starvation issue present in Linux's timer cancellation, the new HRTimer implementation sets a cancellation state via
hrtimer_async_cancel. This cancellation state has a unique and deterministic state transition, eliminating starvation. Memory reclamation is performed through hazard pointer checking loops. Hazard pointer checking ensures that all threads finish executing the callback function and release read ownership (reference release) of the specified HRTimer object.The valid state transitions of an HRTimer object are shown in Figure 2. States are represented using a simplified notation of
State|Ownership, such asHRTIMER_PENDING|shared. The meanings of the simplified ownership markers are as follows:Ownership Markers
|privateindicates that the resource is exclusively owned by a specific threadt. Only the owning threadtcan read from or write to this resource.|sharedindicates that the resource is globally shared and can be read by any thread. However, only the threadtthat holds the global lockl(t = Owned(l)) can obtain write ownership of this resource.|half_sharedindicates that the resource may be accessed by multiple threads, but only the thread that calledasync_cancelholds write ownership of this resource. Modifications to it by threads executing callback functions are prevented.The resource ownership here uses a simplified notation. In actual static analysis or formal verification processes, more complex abstractions such as resource algebra might be employed.
All state transitions not described in the diagram must return failure. For example, a timer in the
HRTIMER_PENDINGstate cannot be started (start) again. Note that there is one exception: a thread that is already in theHRTIMER_CANCELEDstate can legally callhrtimer_async_cancelagain, and the state remains unchanged.To avoid the overhead caused by threads waiting for callback functions to finish executing, HRTimer adds a
restartinterface. Under normal circumstances, thestartinterface cannot start a timer that is already in thecanceledstate. Only when the user uses thisrestartinterface can a timer whose callback function has not yet completed be started normally. Using this interface serves to explicitly remind users to pay attention to concurrency within their callback functions. Furthermore, when concurrency issues arise with HRTimer, it helps in pinpointing the source of the problem—issues can only originate from callback functions whererestartwas used to restart the timer.%%{ init: { 'theme': 'base', 'themeVariables': { 'primaryColor': '#FFFFFF', 'primaryTextColor' : '#000000', 'mermiad-container': "#FFFFFF", 'primaryBorderColor': '#000000', 'lineColor': '#000000', 'secondaryColor': '#FFFFFF', 'tertiaryColor': '#000000' }, 'sequence': { 'mirrorActors': false } } }%% stateDiagram-v2 HRTIMER_COMPLETED|private --> HRTIMER_PENDING|shared : hrtimer_start HRTIMER_PENDING|shared --> HRTIMER_COMPLETED|private : hrtimer callback return 0 in hrtimer_expiry HRTIMER_PENDING|shared --> HRTIMER_PENDING|shared : hrtimer callback return non-zero in hrtimer_expiry HRTIMER_PENDING|shared --> HRTIMER_CANCELED|half_shared : hrtimer_async_cancel HRTIMER_CANCELED|half_shared --> HRTIMER_CANCELED|private : hrtimer_cancel wait all cores release the references to the timer. HRTIMER_CANCELED|half_shared --> HRTIMER_PENDING|shared : hrtimer_restart HRTIMER_CANCELED|private --> HRTIMER_COMPLETED|private : Complete the cancelFigure 2 HRTimer State Transition Diagram
Performance Evaluation
We conducted 1 million interface calls on the

intel64:nsh(Intel 12700) platform and measured their average execution CPU cycles, as shown in the Figure 3 below. It can be observed that the overhead for starting and asynchronously canceling timers is significantly reduced compared to wdog. Additionally, after enabling hrtimer, wdog processing is treated as an hrtimer timer, which lowers the overhead of the wdog interface.Figure 3 HRtimer API Latency Test
Plan
The merge plan for this PR is as follows:
Impact
HRTimer currently is disabled by default, so it has no effect on system.
Testing
Tested on
intel64:nsh,rv-virt:smp,qemu-armv8a:smp,ostestpassed. The hrtimer parallel stress test ran for over 72 hours without errors. The parallel stress test cases is showed in Appendix.Discussion
This hrtimer is a completely different design from #17517. I believe that the hrtimer in this PR is better than the implementation in #17517 in terms of code reusability, customizability, scalability, performance, memory overhead, reliability, integrity, and MIRSA-C compatibility.
Appendix
The hrtimer parallel stress test cases: