Debian Codegraph @

libgo/go/runtime/time.go

raw
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Time-related runtime and pieces of package time.
6
7 package runtime
8
9 import (
10 "runtime/internal/atomic"
11 "unsafe"
12 )
13
14 // Package time knows the layout of this structure.
15 // If this struct changes, adjust ../time/sleep.go:/runtimeTimer.
16 type timer struct {
17 // If this timer is on a heap, which P's heap it is on.
18 // puintptr rather than *p to match uintptr in the versions
19 // of this struct defined in other packages.
20 pp puintptr
21
22 // Timer wakes up at when, and then at when+period, ... (period > 0 only)
23 // each time calling f(arg, now) in the timer goroutine, so f must be
24 // a well-behaved function and not block.
25 //
26 // when must be positive on an active timer.
27 when int64
28 period int64
29 f func(any, uintptr)
30 arg any
31 seq uintptr
32
33 // What to set the when field to in timerModifiedXX status.
34 nextwhen int64
35
36 // The status field holds one of the values below.
37 status uint32
38 }
39
40 // Code outside this file has to be careful in using a timer value.
41 //
42 // The pp, status, and nextwhen fields may only be used by code in this file.
43 //
44 // Code that creates a new timer value can set the when, period, f,
45 // arg, and seq fields.
46 // A new timer value may be passed to addtimer (called by time.startTimer).
47 // After doing that no fields may be touched.
48 //
49 // An active timer (one that has been passed to addtimer) may be
50 // passed to deltimer (time.stopTimer), after which it is no longer an
51 // active timer. It is an inactive timer.
52 // In an inactive timer the period, f, arg, and seq fields may be modified,
53 // but not the when field.
54 // It's OK to just drop an inactive timer and let the GC collect it.
55 // It's not OK to pass an inactive timer to addtimer.
56 // Only newly allocated timer values may be passed to addtimer.
57 //
58 // An active timer may be passed to modtimer. No fields may be touched.
59 // It remains an active timer.
60 //
61 // An inactive timer may be passed to resettimer to turn into an
62 // active timer with an updated when field.
63 // It's OK to pass a newly allocated timer value to resettimer.
64 //
65 // Timer operations are addtimer, deltimer, modtimer, resettimer,
66 // cleantimers, adjusttimers, and runtimer.
67 //
68 // We don't permit calling addtimer/deltimer/modtimer/resettimer simultaneously,
69 // but adjusttimers and runtimer can be called at the same time as any of those.
70 //
71 // Active timers live in heaps attached to P, in the timers field.
72 // Inactive timers live there too temporarily, until they are removed.
73 //
74 // addtimer:
75 // timerNoStatus -> timerWaiting
76 // anything else -> panic: invalid value
77 // deltimer:
78 // timerWaiting -> timerModifying -> timerDeleted
79 // timerModifiedEarlier -> timerModifying -> timerDeleted
80 // timerModifiedLater -> timerModifying -> timerDeleted
81 // timerNoStatus -> do nothing
82 // timerDeleted -> do nothing
83 // timerRemoving -> do nothing
84 // timerRemoved -> do nothing
85 // timerRunning -> wait until status changes
86 // timerMoving -> wait until status changes
87 // timerModifying -> wait until status changes
88 // modtimer:
89 // timerWaiting -> timerModifying -> timerModifiedXX
90 // timerModifiedXX -> timerModifying -> timerModifiedYY
91 // timerNoStatus -> timerModifying -> timerWaiting
92 // timerRemoved -> timerModifying -> timerWaiting
93 // timerDeleted -> timerModifying -> timerModifiedXX
94 // timerRunning -> wait until status changes
95 // timerMoving -> wait until status changes
96 // timerRemoving -> wait until status changes
97 // timerModifying -> wait until status changes
98 // cleantimers (looks in P's timer heap):
99 // timerDeleted -> timerRemoving -> timerRemoved
100 // timerModifiedXX -> timerMoving -> timerWaiting
101 // adjusttimers (looks in P's timer heap):
102 // timerDeleted -> timerRemoving -> timerRemoved
103 // timerModifiedXX -> timerMoving -> timerWaiting
104 // runtimer (looks in P's timer heap):
105 // timerNoStatus -> panic: uninitialized timer
106 // timerWaiting -> timerWaiting or
107 // timerWaiting -> timerRunning -> timerNoStatus or
108 // timerWaiting -> timerRunning -> timerWaiting
109 // timerModifying -> wait until status changes
110 // timerModifiedXX -> timerMoving -> timerWaiting
111 // timerDeleted -> timerRemoving -> timerRemoved
112 // timerRunning -> panic: concurrent runtimer calls
113 // timerRemoved -> panic: inconsistent timer heap
114 // timerRemoving -> panic: inconsistent timer heap
115 // timerMoving -> panic: inconsistent timer heap
116
117 // Values for the timer status field.
118 const (
119 // Timer has no status set yet.
120 timerNoStatus = iota
121
122 // Waiting for timer to fire.
123 // The timer is in some P's heap.
124 timerWaiting
125
126 // Running the timer function.
127 // A timer will only have this status briefly.
128 timerRunning
129
130 // The timer is deleted and should be removed.
131 // It should not be run, but it is still in some P's heap.
132 timerDeleted
133
134 // The timer is being removed.
135 // The timer will only have this status briefly.
136 timerRemoving
137
138 // The timer has been stopped.
139 // It is not in any P's heap.
140 timerRemoved
141
142 // The timer is being modified.
143 // The timer will only have this status briefly.
144 timerModifying
145
146 // The timer has been modified to an earlier time.
147 // The new when value is in the nextwhen field.
148 // The timer is in some P's heap, possibly in the wrong place.
149 timerModifiedEarlier
150
151 // The timer has been modified to the same or a later time.
152 // The new when value is in the nextwhen field.
153 // The timer is in some P's heap, possibly in the wrong place.
154 timerModifiedLater
155
156 // The timer has been modified and is being moved.
157 // The timer will only have this status briefly.
158 timerMoving
159 )
160
161 // maxWhen is the maximum value for timer's when field.
162 const maxWhen = 1<<63 - 1
163
164 // verifyTimers can be set to true to add debugging checks that the
165 // timer heaps are valid.
166 const verifyTimers = false
167
168 // Package time APIs.
169 // Godoc uses the comments in package time, not these.
170
171 // time.now is implemented in assembly.
172
173 // timeSleep puts the current goroutine to sleep for at least ns nanoseconds.
174 //go:linkname timeSleep time.Sleep
175 func timeSleep(ns int64) {
176 if ns <= 0 {
177 return
178 }
179
180 gp := getg()
181 t := gp.timer
182 if t == nil {
183 t = new(timer)
184 gp.timer = t
185 }
186 t.f = goroutineReady
187 t.arg = gp
188 t.nextwhen = nanotime() + ns
189 if t.nextwhen < 0 { // check for overflow.
190 t.nextwhen = maxWhen
191 }
192 gopark(resetForSleep, unsafe.Pointer(t), waitReasonSleep, traceEvGoSleep, 1)
193 }
194
195 // resetForSleep is called after the goroutine is parked for timeSleep.
196 // We can't call resettimer in timeSleep itself because if this is a short
197 // sleep and there are many goroutines then the P can wind up running the
198 // timer function, goroutineReady, before the goroutine has been parked.
199 func resetForSleep(gp *g, ut unsafe.Pointer) bool {
200 t := (*timer)(ut)
201 resettimer(t, t.nextwhen)
202 return true
203 }
204
205 // startTimer adds t to the timer heap.
206 //go:linkname startTimer time.startTimer
207 func startTimer(t *timer) {
208 if raceenabled {
209 racerelease(unsafe.Pointer(t))
210 }
211 addtimer(t)
212 }
213
214 // stopTimer stops a timer.
215 // It reports whether t was stopped before being run.
216 //go:linkname stopTimer time.stopTimer
217 func stopTimer(t *timer) bool {
218 return deltimer(t)
219 }
220
221 // resetTimer resets an inactive timer, adding it to the heap.
222 //go:linkname resetTimer time.resetTimer
223 // Reports whether the timer was modified before it was run.
224 func resetTimer(t *timer, when int64) bool {
225 if raceenabled {
226 racerelease(unsafe.Pointer(t))
227 }
228 return resettimer(t, when)
229 }
230
231 // modTimer modifies an existing timer.
232 //go:linkname modTimer time.modTimer
233 func modTimer(t *timer, when, period int64, f func(any, uintptr), arg any, seq uintptr) {
234 modtimer(t, when, period, f, arg, seq)
235 }
236
237 // Go runtime.
238
239 // Ready the goroutine arg.
240 func goroutineReady(arg any, seq uintptr) {
241 goready(arg.(*g), 0)
242 }
243
244 // addtimer adds a timer to the current P.
245 // This should only be called with a newly created timer.
246 // That avoids the risk of changing the when field of a timer in some P's heap,
247 // which could cause the heap to become unsorted.
248 func addtimer(t *timer) {
249 // when must be positive. A negative value will cause runtimer to
250 // overflow during its delta calculation and never expire other runtime
251 // timers. Zero will cause checkTimers to fail to notice the timer.
252 if t.when <= 0 {
253 throw("timer when must be positive")
254 }
255 if t.period < 0 {
256 throw("timer period must be non-negative")
257 }
258 if t.status != timerNoStatus {
259 throw("addtimer called with initialized timer")
260 }
261 t.status = timerWaiting
262
263 when := t.when
264
265 // Disable preemption while using pp to avoid changing another P's heap.
266 mp := acquirem()
267
268 pp := getg().m.p.ptr()
269 lock(&pp.timersLock)
270 cleantimers(pp)
271 doaddtimer(pp, t)
272 unlock(&pp.timersLock)
273
274 wakeNetPoller(when)
275
276 releasem(mp)
277 }
278
279 // doaddtimer adds t to the current P's heap.
280 // The caller must have locked the timers for pp.
281 func doaddtimer(pp *p, t *timer) {
282 // Timers rely on the network poller, so make sure the poller
283 // has started.
284 if netpollInited == 0 {
285 netpollGenericInit()
286 }
287
288 if t.pp != 0 {
289 throw("doaddtimer: P already set in timer")
290 }
291 t.pp.set(pp)
292 i := len(pp.timers)
293 pp.timers = append(pp.timers, t)
294 siftupTimer(pp.timers, i)
295 if t == pp.timers[0] {
296 atomic.Store64(&pp.timer0When, uint64(t.when))
297 }
298 atomic.Xadd(&pp.numTimers, 1)
299 }
300
301 // deltimer deletes the timer t. It may be on some other P, so we can't
302 // actually remove it from the timers heap. We can only mark it as deleted.
303 // It will be removed in due course by the P whose heap it is on.
304 // Reports whether the timer was removed before it was run.
305 func deltimer(t *timer) bool {
306 for {
307 switch s := atomic.Load(&t.status); s {
308 case timerWaiting, timerModifiedLater:
309 // Prevent preemption while the timer is in timerModifying.
310 // This could lead to a self-deadlock. See #38070.
311 mp := acquirem()
312 if atomic.Cas(&t.status, s, timerModifying) {
313 // Must fetch t.pp before changing status,
314 // as cleantimers in another goroutine
315 // can clear t.pp of a timerDeleted timer.
316 tpp := t.pp.ptr()
317 if !atomic.Cas(&t.status, timerModifying, timerDeleted) {
318 badTimer()
319 }
320 releasem(mp)
321 atomic.Xadd(&tpp.deletedTimers, 1)
322 // Timer was not yet run.
323 return true
324 } else {
325 releasem(mp)
326 }
327 case timerModifiedEarlier:
328 // Prevent preemption while the timer is in timerModifying.
329 // This could lead to a self-deadlock. See #38070.
330 mp := acquirem()
331 if atomic.Cas(&t.status, s, timerModifying) {
332 // Must fetch t.pp before setting status
333 // to timerDeleted.
334 tpp := t.pp.ptr()
335 if !atomic.Cas(&t.status, timerModifying, timerDeleted) {
336 badTimer()
337 }
338 releasem(mp)
339 atomic.Xadd(&tpp.deletedTimers, 1)
340 // Timer was not yet run.
341 return true
342 } else {
343 releasem(mp)
344 }
345 case timerDeleted, timerRemoving, timerRemoved:
346 // Timer was already run.
347 return false
348 case timerRunning, timerMoving:
349 // The timer is being run or moved, by a different P.
350 // Wait for it to complete.
351 osyield()
352 case timerNoStatus:
353 // Removing timer that was never added or
354 // has already been run. Also see issue 21874.
355 return false
356 case timerModifying:
357 // Simultaneous calls to deltimer and modtimer.
358 // Wait for the other call to complete.
359 osyield()
360 default:
361 badTimer()
362 }
363 }
364 }
365
366 // dodeltimer removes timer i from the current P's heap.
367 // We are locked on the P when this is called.
368 // It returns the smallest changed index in pp.timers.
369 // The caller must have locked the timers for pp.
370 func dodeltimer(pp *p, i int) int {
371 if t := pp.timers[i]; t.pp.ptr() != pp {
372 throw("dodeltimer: wrong P")
373 } else {
374 t.pp = 0
375 }
376 last := len(pp.timers) - 1
377 if i != last {
378 pp.timers[i] = pp.timers[last]
379 }
380 pp.timers[last] = nil
381 pp.timers = pp.timers[:last]
382 smallestChanged := i
383 if i != last {
384 // Moving to i may have moved the last timer to a new parent,
385 // so sift up to preserve the heap guarantee.
386 smallestChanged = siftupTimer(pp.timers, i)
387 siftdownTimer(pp.timers, i)
388 }
389 if i == 0 {
390 updateTimer0When(pp)
391 }
392 atomic.Xadd(&pp.numTimers, -1)
393 return smallestChanged
394 }
395
396 // dodeltimer0 removes timer 0 from the current P's heap.
397 // We are locked on the P when this is called.
398 // It reports whether it saw no problems due to races.
399 // The caller must have locked the timers for pp.
400 func dodeltimer0(pp *p) {
401 if t := pp.timers[0]; t.pp.ptr() != pp {
402 throw("dodeltimer0: wrong P")
403 } else {
404 t.pp = 0
405 }
406 last := len(pp.timers) - 1
407 if last > 0 {
408 pp.timers[0] = pp.timers[last]
409 }
410 pp.timers[last] = nil
411 pp.timers = pp.timers[:last]
412 if last > 0 {
413 siftdownTimer(pp.timers, 0)
414 }
415 updateTimer0When(pp)
416 atomic.Xadd(&pp.numTimers, -1)
417 }
418
419 // modtimer modifies an existing timer.
420 // This is called by the netpoll code or time.Ticker.Reset or time.Timer.Reset.
421 // Reports whether the timer was modified before it was run.
422 func modtimer(t *timer, when, period int64, f func(any, uintptr), arg any, seq uintptr) bool {
423 if when <= 0 {
424 throw("timer when must be positive")
425 }
426 if period < 0 {
427 throw("timer period must be non-negative")
428 }
429
430 status := uint32(timerNoStatus)
431 wasRemoved := false
432 var pending bool
433 var mp *m
434 loop:
435 for {
436 switch status = atomic.Load(&t.status); status {
437 case timerWaiting, timerModifiedEarlier, timerModifiedLater:
438 // Prevent preemption while the timer is in timerModifying.
439 // This could lead to a self-deadlock. See #38070.
440 mp = acquirem()
441 if atomic.Cas(&t.status, status, timerModifying) {
442 pending = true // timer not yet run
443 break loop
444 }
445 releasem(mp)
446 case timerNoStatus, timerRemoved:
447 // Prevent preemption while the timer is in timerModifying.
448 // This could lead to a self-deadlock. See #38070.
449 mp = acquirem()
450
451 // Timer was already run and t is no longer in a heap.
452 // Act like addtimer.
453 if atomic.Cas(&t.status, status, timerModifying) {
454 wasRemoved = true
455 pending = false // timer already run or stopped
456 break loop
457 }
458 releasem(mp)
459 case timerDeleted:
460 // Prevent preemption while the timer is in timerModifying.
461 // This could lead to a self-deadlock. See #38070.
462 mp = acquirem()
463 if atomic.Cas(&t.status, status, timerModifying) {
464 atomic.Xadd(&t.pp.ptr().deletedTimers, -1)
465 pending = false // timer already stopped
466 break loop
467 }
468 releasem(mp)
469 case timerRunning, timerRemoving, timerMoving:
470 // The timer is being run or moved, by a different P.
471 // Wait for it to complete.
472 osyield()
473 case timerModifying:
474 // Multiple simultaneous calls to modtimer.
475 // Wait for the other call to complete.
476 osyield()
477 default:
478 badTimer()
479 }
480 }
481
482 t.period = period
483 t.f = f
484 t.arg = arg
485 t.seq = seq
486
487 if wasRemoved {
488 t.when = when
489 pp := getg().m.p.ptr()
490 lock(&pp.timersLock)
491 doaddtimer(pp, t)
492 unlock(&pp.timersLock)
493 if !atomic.Cas(&t.status, timerModifying, timerWaiting) {
494 badTimer()
495 }
496 releasem(mp)
497 wakeNetPoller(when)
498 } else {
499 // The timer is in some other P's heap, so we can't change
500 // the when field. If we did, the other P's heap would
501 // be out of order. So we put the new when value in the
502 // nextwhen field, and let the other P set the when field
503 // when it is prepared to resort the heap.
504 t.nextwhen = when
505
506 newStatus := uint32(timerModifiedLater)
507 if when < t.when {
508 newStatus = timerModifiedEarlier
509 }
510
511 tpp := t.pp.ptr()
512
513 if newStatus == timerModifiedEarlier {
514 updateTimerModifiedEarliest(tpp, when)
515 }
516
517 // Set the new status of the timer.
518 if !atomic.Cas(&t.status, timerModifying, newStatus) {
519 badTimer()
520 }
521 releasem(mp)
522
523 // If the new status is earlier, wake up the poller.
524 if newStatus == timerModifiedEarlier {
525 wakeNetPoller(when)
526 }
527 }
528
529 return pending
530 }
531
532 // resettimer resets the time when a timer should fire.
533 // If used for an inactive timer, the timer will become active.
534 // This should be called instead of addtimer if the timer value has been,
535 // or may have been, used previously.
536 // Reports whether the timer was modified before it was run.
537 func resettimer(t *timer, when int64) bool {
538 return modtimer(t, when, t.period, t.f, t.arg, t.seq)
539 }
540
541 // cleantimers cleans up the head of the timer queue. This speeds up
542 // programs that create and delete timers; leaving them in the heap
543 // slows down addtimer. Reports whether no timer problems were found.
544 // The caller must have locked the timers for pp.
545 func cleantimers(pp *p) {
546 gp := getg()
547 for {
548 if len(pp.timers) == 0 {
549 return
550 }
551
552 // This loop can theoretically run for a while, and because
553 // it is holding timersLock it cannot be preempted.
554 // If someone is trying to preempt us, just return.
555 // We can clean the timers later.
556 if gp.preemptStop {
557 return
558 }
559
560 t := pp.timers[0]
561 if t.pp.ptr() != pp {
562 throw("cleantimers: bad p")
563 }
564 switch s := atomic.Load(&t.status); s {
565 case timerDeleted:
566 if !atomic.Cas(&t.status, s, timerRemoving) {
567 continue
568 }
569 dodeltimer0(pp)
570 if !atomic.Cas(&t.status, timerRemoving, timerRemoved) {
571 badTimer()
572 }
573 atomic.Xadd(&pp.deletedTimers, -1)
574 case timerModifiedEarlier, timerModifiedLater:
575 if !atomic.Cas(&t.status, s, timerMoving) {
576 continue
577 }
578 // Now we can change the when field.
579 t.when = t.nextwhen
580 // Move t to the right position.
581 dodeltimer0(pp)
582 doaddtimer(pp, t)
583 if !atomic.Cas(&t.status, timerMoving, timerWaiting) {
584 badTimer()
585 }
586 default:
587 // Head of timers does not need adjustment.
588 return
589 }
590 }
591 }
592
593 // moveTimers moves a slice of timers to pp. The slice has been taken
594 // from a different P.
595 // This is currently called when the world is stopped, but the caller
596 // is expected to have locked the timers for pp.
597 func moveTimers(pp *p, timers []*timer) {
598 for _, t := range timers {
599 loop:
600 for {
601 switch s := atomic.Load(&t.status); s {
602 case timerWaiting:
603 if !atomic.Cas(&t.status, s, timerMoving) {
604 continue
605 }
606 t.pp = 0
607 doaddtimer(pp, t)
608 if !atomic.Cas(&t.status, timerMoving, timerWaiting) {
609 badTimer()
610 }
611 break loop
612 case timerModifiedEarlier, timerModifiedLater:
613 if !atomic.Cas(&t.status, s, timerMoving) {
614 continue
615 }
616 t.when = t.nextwhen
617 t.pp = 0
618 doaddtimer(pp, t)
619 if !atomic.Cas(&t.status, timerMoving, timerWaiting) {
620 badTimer()
621 }
622 break loop
623 case timerDeleted:
624 if !atomic.Cas(&t.status, s, timerRemoved) {
625 continue
626 }
627 t.pp = 0
628 // We no longer need this timer in the heap.
629 break loop
630 case timerModifying:
631 // Loop until the modification is complete.
632 osyield()
633 case timerNoStatus, timerRemoved:
634 // We should not see these status values in a timers heap.
635 badTimer()
636 case timerRunning, timerRemoving, timerMoving:
637 // Some other P thinks it owns this timer,
638 // which should not happen.
639 badTimer()
640 default:
641 badTimer()
642 }
643 }
644 }
645 }
646
647 // adjusttimers looks through the timers in the current P's heap for
648 // any timers that have been modified to run earlier, and puts them in
649 // the correct place in the heap. While looking for those timers,
650 // it also moves timers that have been modified to run later,
651 // and removes deleted timers. The caller must have locked the timers for pp.
652 func adjusttimers(pp *p, now int64) {
653 // If we haven't yet reached the time of the first timerModifiedEarlier
654 // timer, don't do anything. This speeds up programs that adjust
655 // a lot of timers back and forth if the timers rarely expire.
656 // We'll postpone looking through all the adjusted timers until
657 // one would actually expire.
658 first := atomic.Load64(&pp.timerModifiedEarliest)
659 if first == 0 || int64(first) > now {
660 if verifyTimers {
661 verifyTimerHeap(pp)
662 }
663 return
664 }
665
666 // We are going to clear all timerModifiedEarlier timers.
667 atomic.Store64(&pp.timerModifiedEarliest, 0)
668
669 var moved []*timer
670 for i := 0; i < len(pp.timers); i++ {
671 t := pp.timers[i]
672 if t.pp.ptr() != pp {
673 throw("adjusttimers: bad p")
674 }
675 switch s := atomic.Load(&t.status); s {
676 case timerDeleted:
677 if atomic.Cas(&t.status, s, timerRemoving) {
678 changed := dodeltimer(pp, i)
679 if !atomic.Cas(&t.status, timerRemoving, timerRemoved) {
680 badTimer()
681 }
682 atomic.Xadd(&pp.deletedTimers, -1)
683 // Go back to the earliest changed heap entry.
684 // "- 1" because the loop will add 1.
685 i = changed - 1
686 }
687 case timerModifiedEarlier, timerModifiedLater:
688 if atomic.Cas(&t.status, s, timerMoving) {
689 // Now we can change the when field.
690 t.when = t.nextwhen
691 // Take t off the heap, and hold onto it.
692 // We don't add it back yet because the
693 // heap manipulation could cause our
694 // loop to skip some other timer.
695 changed := dodeltimer(pp, i)
696 moved = append(moved, t)
697 // Go back to the earliest changed heap entry.
698 // "- 1" because the loop will add 1.
699 i = changed - 1
700 }
701 case timerNoStatus, timerRunning, timerRemoving, timerRemoved, timerMoving:
702 badTimer()
703 case timerWaiting:
704 // OK, nothing to do.
705 case timerModifying:
706 // Check again after modification is complete.
707 osyield()
708 i--
709 default:
710 badTimer()
711 }
712 }
713
714 if len(moved) > 0 {
715 addAdjustedTimers(pp, moved)
716 }
717
718 if verifyTimers {
719 verifyTimerHeap(pp)
720 }
721 }
722
723 // addAdjustedTimers adds any timers we adjusted in adjusttimers
724 // back to the timer heap.
725 func addAdjustedTimers(pp *p, moved []*timer) {
726 for _, t := range moved {
727 doaddtimer(pp, t)
728 if !atomic.Cas(&t.status, timerMoving, timerWaiting) {
729 badTimer()
730 }
731 }
732 }
733
734 // nobarrierWakeTime looks at P's timers and returns the time when we
735 // should wake up the netpoller. It returns 0 if there are no timers.
736 // This function is invoked when dropping a P, and must run without
737 // any write barriers.
738 //go:nowritebarrierrec
739 func nobarrierWakeTime(pp *p) int64 {
740 next := int64(atomic.Load64(&pp.timer0When))
741 nextAdj := int64(atomic.Load64(&pp.timerModifiedEarliest))
742 if next == 0 || (nextAdj != 0 && nextAdj < next) {
743 next = nextAdj
744 }
745 return next
746 }
747
748 // runtimer examines the first timer in timers. If it is ready based on now,
749 // it runs the timer and removes or updates it.
750 // Returns 0 if it ran a timer, -1 if there are no more timers, or the time
751 // when the first timer should run.
752 // The caller must have locked the timers for pp.
753 // If a timer is run, this will temporarily unlock the timers.
754 //go:systemstack
755 func runtimer(pp *p, now int64) int64 {
756 for {
757 t := pp.timers[0]
758 if t.pp.ptr() != pp {
759 throw("runtimer: bad p")
760 }
761 switch s := atomic.Load(&t.status); s {
762 case timerWaiting:
763 if t.when > now {
764 // Not ready to run.
765 return t.when
766 }
767
768 if !atomic.Cas(&t.status, s, timerRunning) {
769 continue
770 }
771 // Note that runOneTimer may temporarily unlock
772 // pp.timersLock.
773 runOneTimer(pp, t, now)
774 return 0
775
776 case timerDeleted:
777 if !atomic.Cas(&t.status, s, timerRemoving) {
778 continue
779 }
780 dodeltimer0(pp)
781 if !atomic.Cas(&t.status, timerRemoving, timerRemoved) {
782 badTimer()
783 }
784 atomic.Xadd(&pp.deletedTimers, -1)
785 if len(pp.timers) == 0 {
786 return -1
787 }
788
789 case timerModifiedEarlier, timerModifiedLater:
790 if !atomic.Cas(&t.status, s, timerMoving) {
791 continue
792 }
793 t.when = t.nextwhen
794 dodeltimer0(pp)
795 doaddtimer(pp, t)
796 if !atomic.Cas(&t.status, timerMoving, timerWaiting) {
797 badTimer()
798 }
799
800 case timerModifying:
801 // Wait for modification to complete.
802 osyield()
803
804 case timerNoStatus, timerRemoved:
805 // Should not see a new or inactive timer on the heap.
806 badTimer()
807 case timerRunning, timerRemoving, timerMoving:
808 // These should only be set when timers are locked,
809 // and we didn't do it.
810 badTimer()
811 default:
812 badTimer()
813 }
814 }
815 }
816
817 // runOneTimer runs a single timer.
818 // The caller must have locked the timers for pp.
819 // This will temporarily unlock the timers while running the timer function.
820 //go:systemstack
821 func runOneTimer(pp *p, t *timer, now int64) {
822 f := t.f
823 arg := t.arg
824 seq := t.seq
825
826 if t.period > 0 {
827 // Leave in heap but adjust next time to fire.
828 delta := t.when - now
829 t.when += t.period * (1 + -delta/t.period)
830 if t.when < 0 { // check for overflow.
831 t.when = maxWhen
832 }
833 siftdownTimer(pp.timers, 0)
834 if !atomic.Cas(&t.status, timerRunning, timerWaiting) {
835 badTimer()
836 }
837 updateTimer0When(pp)
838 } else {
839 // Remove from heap.
840 dodeltimer0(pp)
841 if !atomic.Cas(&t.status, timerRunning, timerNoStatus) {
842 badTimer()
843 }
844 }
845
846 unlock(&pp.timersLock)
847
848 f(arg, seq)
849
850 lock(&pp.timersLock)
851 }
852
853 // clearDeletedTimers removes all deleted timers from the P's timer heap.
854 // This is used to avoid clogging up the heap if the program
855 // starts a lot of long-running timers and then stops them.
856 // For example, this can happen via context.WithTimeout.
857 //
858 // This is the only function that walks through the entire timer heap,
859 // other than moveTimers which only runs when the world is stopped.
860 //
861 // The caller must have locked the timers for pp.
862 func clearDeletedTimers(pp *p) {
863 // We are going to clear all timerModifiedEarlier timers.
864 // Do this now in case new ones show up while we are looping.
865 atomic.Store64(&pp.timerModifiedEarliest, 0)
866
867 cdel := int32(0)
868 to := 0
869 changedHeap := false
870 timers := pp.timers
871 nextTimer:
872 for _, t := range timers {
873 for {
874 switch s := atomic.Load(&t.status); s {
875 case timerWaiting:
876 if changedHeap {
877 timers[to] = t
878 siftupTimer(timers, to)
879 }
880 to++
881 continue nextTimer
882 case timerModifiedEarlier, timerModifiedLater:
883 if atomic.Cas(&t.status, s, timerMoving) {
884 t.when = t.nextwhen
885 timers[to] = t
886 siftupTimer(timers, to)
887 to++
888 changedHeap = true
889 if !atomic.Cas(&t.status, timerMoving, timerWaiting) {
890 badTimer()
891 }
892 continue nextTimer
893 }
894 case timerDeleted:
895 if atomic.Cas(&t.status, s, timerRemoving) {
896 t.pp = 0
897 cdel++
898 if !atomic.Cas(&t.status, timerRemoving, timerRemoved) {
899 badTimer()
900 }
901 changedHeap = true
902 continue nextTimer
903 }
904 case timerModifying:
905 // Loop until modification complete.
906 osyield()
907 case timerNoStatus, timerRemoved:
908 // We should not see these status values in a timer heap.
909 badTimer()
910 case timerRunning, timerRemoving, timerMoving:
911 // Some other P thinks it owns this timer,
912 // which should not happen.
913 badTimer()
914 default:
915 badTimer()
916 }
917 }
918 }
919
920 // Set remaining slots in timers slice to nil,
921 // so that the timer values can be garbage collected.
922 for i := to; i < len(timers); i++ {
923 timers[i] = nil
924 }
925
926 atomic.Xadd(&pp.deletedTimers, -cdel)
927 atomic.Xadd(&pp.numTimers, -cdel)
928
929 timers = timers[:to]
930 pp.timers = timers
931 updateTimer0When(pp)
932
933 if verifyTimers {
934 verifyTimerHeap(pp)
935 }
936 }
937
938 // verifyTimerHeap verifies that the timer heap is in a valid state.
939 // This is only for debugging, and is only called if verifyTimers is true.
940 // The caller must have locked the timers.
941 func verifyTimerHeap(pp *p) {
942 for i, t := range pp.timers {
943 if i == 0 {
944 // First timer has no parent.
945 continue
946 }
947
948 // The heap is 4-ary. See siftupTimer and siftdownTimer.
949 p := (i - 1) / 4
950 if t.when < pp.timers[p].when {
951 print("bad timer heap at ", i, ": ", p, ": ", pp.timers[p].when, ", ", i, ": ", t.when, "\n")
952 throw("bad timer heap")
953 }
954 }
955 if numTimers := int(atomic.Load(&pp.numTimers)); len(pp.timers) != numTimers {
956 println("timer heap len", len(pp.timers), "!= numTimers", numTimers)
957 throw("bad timer heap len")
958 }
959 }
960
961 // updateTimer0When sets the P's timer0When field.
962 // The caller must have locked the timers for pp.
963 func updateTimer0When(pp *p) {
964 if len(pp.timers) == 0 {
965 atomic.Store64(&pp.timer0When, 0)
966 } else {
967 atomic.Store64(&pp.timer0When, uint64(pp.timers[0].when))
968 }
969 }
970
971 // updateTimerModifiedEarliest updates the recorded nextwhen field of the
972 // earlier timerModifiedEarier value.
973 // The timers for pp will not be locked.
974 func updateTimerModifiedEarliest(pp *p, nextwhen int64) {
975 for {
976 old := atomic.Load64(&pp.timerModifiedEarliest)
977 if old != 0 && int64(old) < nextwhen {
978 return
979 }
980 if atomic.Cas64(&pp.timerModifiedEarliest, old, uint64(nextwhen)) {
981 return
982 }
983 }
984 }
985
986 // timeSleepUntil returns the time when the next timer should fire,
987 // and the P that holds the timer heap that that timer is on.
988 // This is only called by sysmon and checkdead.
989 func timeSleepUntil() (int64, *p) {
990 next := int64(maxWhen)
991 var pret *p
992
993 // Prevent allp slice changes. This is like retake.
994 lock(&allpLock)
995 for _, pp := range allp {
996 if pp == nil {
997 // This can happen if procresize has grown
998 // allp but not yet created new Ps.
999 continue
1000 }
1001
1002 w := int64(atomic.Load64(&pp.timer0When))
1003 if w != 0 && w < next {
1004 next = w
1005 pret = pp
1006 }
1007
1008 w = int64(atomic.Load64(&pp.timerModifiedEarliest))
1009 if w != 0 && w < next {
1010 next = w
1011 pret = pp
1012 }
1013 }
1014 unlock(&allpLock)
1015
1016 return next, pret
1017 }
1018
1019 // Heap maintenance algorithms.
1020 // These algorithms check for slice index errors manually.
1021 // Slice index error can happen if the program is using racy
1022 // access to timers. We don't want to panic here, because
1023 // it will cause the program to crash with a mysterious
1024 // "panic holding locks" message. Instead, we panic while not
1025 // holding a lock.
1026
1027 // siftupTimer puts the timer at position i in the right place
1028 // in the heap by moving it up toward the top of the heap.
1029 // It returns the smallest changed index.
1030 func siftupTimer(t []*timer, i int) int {
1031 if i >= len(t) {
1032 badTimer()
1033 }
1034 when := t[i].when
1035 if when <= 0 {
1036 badTimer()
1037 }
1038 tmp := t[i]
1039 for i > 0 {
1040 p := (i - 1) / 4 // parent
1041 if when >= t[p].when {
1042 break
1043 }
1044 t[i] = t[p]
1045 i = p
1046 }
1047 if tmp != t[i] {
1048 t[i] = tmp
1049 }
1050 return i
1051 }
1052
1053 // siftdownTimer puts the timer at position i in the right place
1054 // in the heap by moving it down toward the bottom of the heap.
1055 func siftdownTimer(t []*timer, i int) {
1056 n := len(t)
1057 if i >= n {
1058 badTimer()
1059 }
1060 when := t[i].when
1061 if when <= 0 {
1062 badTimer()
1063 }
1064 tmp := t[i]
1065 for {
1066 c := i*4 + 1 // left child
1067 c3 := c + 2 // mid child
1068 if c >= n {
1069 break
1070 }
1071 w := t[c].when
1072 if c+1 < n && t[c+1].when < w {
1073 w = t[c+1].when
1074 c++
1075 }
1076 if c3 < n {
1077 w3 := t[c3].when
1078 if c3+1 < n && t[c3+1].when < w3 {
1079 w3 = t[c3+1].when
1080 c3++
1081 }
1082 if w3 < w {
1083 w = w3
1084 c = c3
1085 }
1086 }
1087 if w >= when {
1088 break
1089 }
1090 t[i] = t[c]
1091 i = c
1092 }
1093 if tmp != t[i] {
1094 t[i] = tmp
1095 }
1096 }
1097
1098 // badTimer is called if the timer data structures have been corrupted,
1099 // presumably due to racy use by the program. We panic here rather than
1100 // panicing due to invalid slice access while holding locks.
1101 // See issue #25686.
1102 func badTimer() {
1103 throw("timer data corruption")
1104 }