Black Lives Matter. Support the Equal Justice Initiative.

Source file src/runtime/time.go

Documentation: runtime

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

View as plain text