gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/test/syscalls/linux/getcpu.cc (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  #include <sched.h>
    16  
    17  #include "gtest/gtest.h"
    18  #include "absl/time/clock.h"
    19  #include "absl/time/time.h"
    20  #include "test/util/test_util.h"
    21  
    22  namespace gvisor {
    23  namespace testing {
    24  
    25  namespace {
    26  
    27  TEST(GetcpuTest, IsValidCpuStress) {
    28    const int num_cpus = NumCPUs();
    29    absl::Time deadline = absl::Now() + absl::Seconds(10);
    30    while (absl::Now() < deadline) {
    31      int cpu;
    32      ASSERT_THAT(cpu = sched_getcpu(), SyscallSucceeds());
    33      ASSERT_LT(cpu, num_cpus);
    34    }
    35  }
    36  
    37  TEST(GetcpuTest, IsValidCpu) {
    38    const int num_cpus = NumCPUs();
    39    cpu_set_t orig_set;
    40    ASSERT_THAT(sched_getaffinity(getpid(), sizeof(orig_set), &orig_set),
    41                SyscallSucceeds());
    42    for (int i = 0; i < num_cpus; i++) {
    43      if (CPU_ISSET(i, &orig_set) == 0) continue;
    44      cpu_set_t set = {};
    45      int cpu;
    46      CPU_SET(i, &set);
    47      ASSERT_THAT(sched_setaffinity(getpid(), sizeof(set), &set),
    48                  SyscallSucceeds());
    49      ASSERT_THAT(cpu = sched_getcpu(), SyscallSucceeds());
    50      // sched_setaffinity doesn't work if Kernel.useHostCores is true.
    51      ASSERT_THAT(sched_getaffinity(getpid(), sizeof(set), &set),
    52                  SyscallSucceeds());
    53      ASSERT_NE(CPU_ISSET(cpu, &set), 0);
    54    }
    55  }
    56  
    57  }  // namespace
    58  
    59  }  // namespace testing
    60  }  // namespace gvisor