wangchdo commented on code in PR #17573:
URL: https://github.com/apache/nuttx/pull/17573#discussion_r2654993377
##########
sched/hrtimer/hrtimer_process.c:
##########
@@ -99,28 +98,70 @@ void hrtimer_process(uint64_t now)
DEBUGASSERT(hrtimer->func != NULL);
hrtimer->state = HRTIMER_STATE_RUNNING;
+ hrtimer->cpus++;
- spin_unlock_irqrestore(&g_hrtimer_spinlock, flags);
+ /* cpus is a running reference counter and must never wrap */
- /* Invoke the timer callback */
+ DEBUGASSERT(hrtimer->cpus != 0);
+
+ /* Leave critical section before invoking the callback */
+
+ write_sequnlock_irqrestore(&g_hrtimer_spinlock, flags);
+
+ /* Execute the timer callback */
period = hrtimer->func(hrtimer);
- flags = spin_lock_irqsave(&g_hrtimer_spinlock);
+ /* Re-enter critical section to update timer state */
- if ((hrtimer->state == HRTIMER_STATE_CANCELED) || (period == 0))
- {
- /* Timer is canceled or one-shot; mark it inactive */
+ flags = write_seqlock_irqsave(&g_hrtimer_spinlock);
- hrtimer->state = HRTIMER_STATE_INACTIVE;
- }
- else
- {
- /* Restart the periodic timer */
+ hrtimer->cpus--;
- hrtimer->expired += period;
- hrtimer->state = HRTIMER_STATE_ARMED;
- RB_INSERT(hrtimer_tree_s, &g_hrtimer_tree, &hrtimer->node);
+ switch (hrtimer->state)
+ {
+ case HRTIMER_STATE_RUNNING:
+ {
+ /* Timer callback completed normally */
+
+ if (period > 0)
+ {
+ /* Periodic timer: re-arm with the next expiration */
+
+ hrtimer->expired += period;
Review Comment:
Fixed.
By the way, I think the violation of the ownership invariant is very much
unlikely to happen, as long as users only use the APIs I provided.
In my implementation, the hrtimer APIs are intentionally kept simple:
```
void hrtimer_init(FAR hrtimer_t *hrtimer, hrtimer_cb func, FAR void *arg);
int hrtimer_cancel(FAR hrtimer_t *hrtimer);
int hrtimer_cancel_sync(FAR hrtimer_t *hrtimer);
int hrtimer_start(FAR hrtimer_t *hrtimer, uint64_t ns,
enum hrtimer_mode_e mode);
```
`hrtimer_start()` is only responsible for updating the expiration time of an
already initialized hrtimer. It does not modify the callback or its arguments,
and therefore it can be safely called in all cases without introducing issues.
I think this design keeps the hrtimer APIs easy to understand, ensures
deterministic behavior in hrtimer processing, and at the same time improves the
overall efficiency of hrtimer handling.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]