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
27 /**
28 * Call to sched_setaffinity must be repected.
29 */
TEST(cpu,sched_setaffinity)30 TEST(cpu, sched_setaffinity) {
31 int cpu_count = android_getCpuCount();
32 for (int cpu = 0; cpu < cpu_count; ++cpu) {
33 cpu_set_t set;
34 CPU_ZERO(&set);
35 CPU_SET(cpu, &set);
36 int rc = sched_setaffinity(0, sizeof(cpu_set_t), &set);
37 ASSERT_EQ(0, rc) << "sched_setaffinity failed. error = " << errno;
38 ASSERT_EQ(cpu, sched_getcpu()) << "sched_setaffinity was not respected.";
39 }
40 }
41
TEST(cpu,sched_setaffinity_multiple_cpu)42 TEST(cpu, sched_setaffinity_multiple_cpu) {
43 int cpu_count = android_getCpuCount();
44
45 std::vector<std::vector<int>> data {
46 {0, 1},
47 {2, 3, 4, 5},
48 {6, 7},
49 {0, 1, 2, 3},
50 {4, 5, 6, 7},
51 {0, cpu_count - 1}};
52
53 for (auto test_data : data) {
54 cpu_set_t set;
55 CPU_ZERO(&set);
56 for (int i = 0; i < test_data.size(); ++i) {
57 auto cpu = test_data[i];
58 if (cpu >= cpu_count) {
59 cpu = cpu_count - 1;
60 test_data[i] = cpu;
61 }
62 cpu_set_t other_set;
63 CPU_ZERO(&other_set);
64 CPU_SET(cpu, &other_set);
65 CPU_OR(&set, &set, &other_set);
66 }
67 int rc = sched_setaffinity(0, sizeof(cpu_set_t), &set);
68 ASSERT_EQ(0, rc) << "sched_setaffinity failed. error = " << errno;
69 ASSERT_THAT(test_data, ::testing::Contains(sched_getcpu()))
70 << "sched_setaffinity was not respected.";
71 }
72 }
73