github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/vdso/cycle_clock.h (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  #ifndef VDSO_CYCLE_CLOCK_H_
    16  #define VDSO_CYCLE_CLOCK_H_
    17  
    18  #include <stdint.h>
    19  
    20  #include "vdso/barrier.h"
    21  
    22  namespace vdso {
    23  
    24  #if __x86_64__
    25  
    26  // TODO(b/74613497): The appropriate barrier instruction to use with rdtsc on
    27  // x86_64 depends on the vendor. Intel processors can use lfence but AMD may
    28  // need mfence, depending on MSR_F10H_DECFG_LFENCE_SERIALIZE_BIT.
    29  
    30  static inline uint64_t cycle_clock(void) {
    31    uint32_t lo, hi;
    32    asm volatile("lfence" : : : "memory");
    33    asm volatile("rdtsc" : "=a"(lo), "=d"(hi));
    34    return ((uint64_t)hi << 32) | lo;
    35  }
    36  
    37  #elif __aarch64__
    38  
    39  static inline uint64_t cycle_clock(void) {
    40    uint64_t val;
    41    asm volatile("mrs %0, CNTVCT_EL0" : "=r"(val)::"memory");
    42    return val;
    43  }
    44  
    45  #else
    46  #error "unsupported architecture"
    47  #endif
    48  
    49  }  // namespace vdso
    50  
    51  #endif  // VDSO_CYCLE_CLOCK_H_