From f4a4cde7ddc19b1e5f434d5e15f089af4f6f0f15 Mon Sep 17 00:00:00 2001 From: Kevin Krakauer Date: Tue, 30 May 2023 12:05:24 -0700 Subject: [PATCH] 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 --- pkg/tcpip/stdclock.go | 25 ++++--------------------- pkg/tcpip/stdclock_state.go | 9 +++++---- 2 files changed, 9 insertions(+), 25 deletions(-) diff --git a/pkg/tcpip/stdclock.go b/pkg/tcpip/stdclock.go index 371da2f40..cc3397ca9 100644 --- a/pkg/tcpip/stdclock.go +++ b/pkg/tcpip/stdclock.go @@ -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. diff --git a/pkg/tcpip/stdclock_state.go b/pkg/tcpip/stdclock_state.go index 795db9181..25be1755f 100644 --- a/pkg/tcpip/stdclock_state.go +++ b/pkg/tcpip/stdclock_state.go @@ -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 }