github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/pkg/sentry/time/sampler_unsafe.go (about)

     1  // Copyright 2018 The gVisor Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package time
    16  
    17  import (
    18  	"unsafe"
    19  
    20  	"golang.org/x/sys/unix"
    21  )
    22  
    23  // syscallTSCReferenceClocks is the standard referenceClocks, collecting
    24  // samples using CLOCK_GETTIME and RDTSC.
    25  type syscallTSCReferenceClocks struct {
    26  	tscCycleClock
    27  }
    28  
    29  // Sample implements sampler.Sample.
    30  func (syscallTSCReferenceClocks) Sample(c ClockID) (sample, error) {
    31  	var s sample
    32  
    33  	s.before = Rdtsc()
    34  
    35  	// Don't call clockGettime to avoid a call which may call morestack.
    36  	var ts unix.Timespec
    37  	_, _, e := unix.RawSyscall(unix.SYS_CLOCK_GETTIME, uintptr(c), uintptr(unsafe.Pointer(&ts)), 0)
    38  	if e != 0 {
    39  		return sample{}, e
    40  	}
    41  
    42  	s.after = Rdtsc()
    43  	s.ref = ReferenceNS(ts.Nano())
    44  
    45  	return s, nil
    46  }
    47  
    48  // clockGettime calls SYS_CLOCK_GETTIME, returning time in nanoseconds.
    49  func clockGettime(c ClockID) (ReferenceNS, error) {
    50  	var ts unix.Timespec
    51  	_, _, e := unix.RawSyscall(unix.SYS_CLOCK_GETTIME, uintptr(c), uintptr(unsafe.Pointer(&ts)), 0)
    52  	if e != 0 {
    53  		return 0, e
    54  	}
    55  
    56  	return ReferenceNS(ts.Nano()), nil
    57  }