netstack: remove mutex from standard clock

We can avoid locking altogether by saving the monotonic offset only during save
rather than every time we return a time.

PiperOrigin-RevId: 536471006
This commit is contained in:
Kevin Krakauer
2023-05-30 12:09:37 -07:00
committed by gVisor bot
parent 919cfd12bd
commit f4a4cde7dd
2 changed files with 9 additions and 25 deletions
+4 -21
View File
@@ -17,8 +17,6 @@ package tcpip
import (
"fmt"
"time"
"gvisor.dev/gvisor/pkg/sync"
)
// stdClock implements Clock with the time package.
@@ -57,14 +55,9 @@ type stdClock struct {
// monotonicOffset is the offset applied to the calculated monotonic time.
//
// monotonicOffset is assigned maxMonotonic after restore so that the
// monotonic time will continue from where it "left off" before saving as part
// of S/R.
monotonicOffset MonotonicTime `state:"nosave"`
// monotonicMU protects maxMonotonic.
monotonicMU sync.Mutex `state:"nosave"`
maxMonotonic MonotonicTime
// monotonicOffset is assigned after restore so that the monotonic time
// will continue from where it "left off" before saving as part of S/R.
monotonicOffset MonotonicTime
}
// NewStdClock returns an instance of a clock that uses the time package.
@@ -88,17 +81,7 @@ func (s *stdClock) NowMonotonic() MonotonicTime {
panic(fmt.Sprintf("got negative duration = %s since base time = %s", sinceBase, s.baseTime))
}
monotonicValue := s.monotonicOffset.Add(sinceBase)
s.monotonicMU.Lock()
defer s.monotonicMU.Unlock()
// Monotonic time values must never decrease.
if s.maxMonotonic.Before(monotonicValue) {
s.maxMonotonic = monotonicValue
}
return s.maxMonotonic
return s.monotonicOffset.Add(sinceBase)
}
// AfterFunc implements Clock.AfterFunc.
+5 -4
View File
@@ -16,11 +16,12 @@ package tcpip
import "time"
// beforeSave is invoked by stateify.
func (s *stdClock) beforeSave() {
s.monotonicOffset = s.NowMonotonic()
}
// afterLoad is invoked by stateify.
func (s *stdClock) afterLoad() {
s.baseTime = time.Now()
s.monotonicMU.Lock()
defer s.monotonicMU.Unlock()
s.monotonicOffset = s.maxMonotonic
}