Source file src/runtime/time.go

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

View as plain text