1 /*
2 * Copyright 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 */
17
18 #include <gtest/gtest.h>
19 #include <gmock/gmock.h>
20 #include <cpu-features.h>
21 #include <iostream>
22 #include <unistd.h>
23 #include <sched.h>
24 #include <errno.h>
25 #include <vector>
26 #include <cstdlib>
27 #include "testutils.h"
28
29 /**
30 * Call to sched_setaffinity must be repected.
31 */
TEST(cpu,sched_setaffinity)32 TEST(cpu, sched_setaffinity) {
33 ASSUME_GAMECORE_CERTIFIED();
34
35 int cpu_count = android_getCpuCount();
36 for (int cpu = 0; cpu < cpu_count; ++cpu) {
37 cpu_set_t set;
38 CPU_ZERO(&set);
39 CPU_SET(cpu, &set);
40 int rc = sched_setaffinity(0, sizeof(cpu_set_t), &set);
41 ASSERT_EQ(0, rc) << "sched_setaffinity failed. error = " << errno;
42 ASSERT_EQ(cpu, sched_getcpu()) << "sched_setaffinity was not respected.";
43 }
44 }
45
TEST(cpu,sched_setaffinity_multiple_cpu)46 TEST(cpu, sched_setaffinity_multiple_cpu) {
47 ASSUME_GAMECORE_CERTIFIED();
48
49 int cpu_count = android_getCpuCount();
50
51 std::vector<std::vector<int>> data {
52 {0, 1},
53 {2, 3, 4, 5},
54 {6, 7},
55 {0, 1, 2, 3},
56 {4, 5, 6, 7},
57 {0, cpu_count - 1}};
58
59 for (auto test_data : data) {
60 cpu_set_t set;
61 CPU_ZERO(&set);
62 for (int i = 0; i < test_data.size(); ++i) {
63 auto cpu = test_data[i];
64 if (cpu >= cpu_count) {
65 cpu = cpu_count - 1;
66 test_data[i] = cpu;
67 }
68 cpu_set_t other_set;
69 CPU_ZERO(&other_set);
70 CPU_SET(cpu, &other_set);
71 CPU_OR(&set, &set, &other_set);
72 }
73 int rc = sched_setaffinity(0, sizeof(cpu_set_t), &set);
74 ASSERT_EQ(0, rc) << "sched_setaffinity failed. error = " << errno;
75 ASSERT_THAT(test_data, ::testing::Contains(sched_getcpu()))
76 << "sched_setaffinity was not respected.";
77 }
78 }
79