okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge branch 'f-139b-spd' into f-139-rel4f5e6c841

main
11.1 KiB290 linesraw
1#ifndef _GNU_SOURCE
2#define _GNU_SOURCE
3#endif
4
5#include "strata/kernels/cpu/pool.hpp"
6
7#include <algorithm>
8#include <cerrno>
9#include <climits>
10#include <cstdio>
11#include <cstdlib>
12#include <cstring>
13#include <string>
14#include <thread>
15#include <vector>
16
17#if defined(__linux__)
18#include "pool_affinity_linux.hpp"
19
20#include <pthread.h>
21#include <sched.h>
22#include <unistd.h>
23
24namespace cpu = strata::kernels::cpu;
25
26class DynamicCpuSet {
27public:
28    explicit DynamicCpuSet(size_t count)
29        : count_(count), bytes_(CPU_ALLOC_SIZE(count)), set_(CPU_ALLOC(count)) {
30        if (set_) CPU_ZERO_S(bytes_, set_);
31    }
32
33    ~DynamicCpuSet() {
34        if (set_) CPU_FREE(set_);
35    }
36
37    DynamicCpuSet(const DynamicCpuSet&) = delete;
38    DynamicCpuSet& operator=(const DynamicCpuSet&) = delete;
39
40    cpu_set_t* get() { return set_; }
41    const cpu_set_t* get() const { return set_; }
42    size_t bytes() const { return bytes_; }
43    size_t count() const { return count_; }
44    explicit operator bool() const { return set_ != nullptr; }
45
46private:
47    size_t count_;
48    size_t bytes_;
49    cpu_set_t* set_;
50};
51
52static size_t initial_cpu_count() {
53    const long configured = sysconf(_SC_NPROCESSORS_CONF);
54    return (std::max)(size_t(128), configured > 0 ? (size_t) configured : size_t(0));
55}
56
57// Query with CPU_ALLOC rather than cpu_set_t: this must observe CPUs beyond CPU_SETSIZE too.
58static bool get_affinity(std::vector<int>& ids) {
59    size_t count = initial_cpu_count();
60    for (int attempt = 0; attempt < 8; ++attempt) {
61        DynamicCpuSet set(count);
62        if (!set) return false;
63        const int error = pthread_getaffinity_np(pthread_self(), set.bytes(), set.get());
64        if (error == 0) {
65            ids.clear();
66            for (size_t i = 0; i < set.count(); ++i)
67                if (CPU_ISSET_S(i, set.bytes(), set.get())) ids.push_back((int) i);
68            return !ids.empty();
69        }
70        if (error != EINVAL || count > (size_t(1) << 20)) {
71            std::fprintf(stderr, "pthread_getaffinity_np failed: %s\n", std::strerror(error));
72            return false;
73        }
74        count *= 2;
75    }
76    std::fprintf(stderr, "pthread_getaffinity_np still needs a larger CPU set\n");
77    return false;
78}
79
80static bool set_affinity(const std::vector<int>& ids) {
81    if (ids.empty()) return false;
82    const int highest = *std::max_element(ids.begin(), ids.end());
83    if (highest < 0) return false;
84    const size_t count = (std::max)(initial_cpu_count(), (size_t) highest + 1);
85    DynamicCpuSet set(count);
86    if (!set) return false;
87    for (int id : ids) {
88        if (id < 0 || (size_t) id >= count) return false;
89        CPU_SET_S((size_t) id, set.bytes(), set.get());
90    }
91    const int error = pthread_setaffinity_np(pthread_self(), set.bytes(), set.get());
92    if (error != 0) {
93        std::fprintf(stderr, "pthread_setaffinity_np failed: %s\n", std::strerror(error));
94        return false;
95    }
96    return true;
97}
98
99class OriginalAffinity {
100public:
101    bool capture() { return get_affinity(ids_); }
102    const std::vector<int>& ids() const { return ids_; }
103    bool restore() { return ids_.empty() || set_affinity(ids_); }
104    ~OriginalAffinity() { if (!ids_.empty()) set_affinity(ids_); }
105
106private:
107    std::vector<int> ids_;
108};
109
110static bool expect_affinity(const std::vector<int>& expected, const char* label) {
111    std::vector<int> actual;
112    if (!get_affinity(actual)) {
113        std::fprintf(stderr, "Linux affinity test: %s: cannot query current affinity\n", label);
114        return false;
115    }
116    if (actual != expected) {
117        std::fprintf(stderr, "Linux affinity test: %s: expected %zu CPUs, observed %zu\n",
118                     label, expected.size(), actual.size());
119        return false;
120    }
121    return true;
122}
123
124static bool round_trip_full_mask(const std::vector<int>& allowed) {
125    const int target = allowed.front();
126    const auto previous = cpu::pin_current_thread(target);
127    const bool pinned = previous.valid && expect_affinity({target}, "pin from full allowed mask");
128    cpu::restore_thread_affinity(previous);
129    return pinned && expect_affinity(allowed, "restore full allowed mask");
130}
131
132static bool topology_respects_current_mask() {
133    std::vector<int> allowed;
134    if (!get_affinity(allowed)) return false;
135    const auto topology = cpu::detect_cpu_topology(false);
136    if (topology.worker_cores.empty()) return false;
137    for (int core : topology.worker_cores) {
138        if (!std::binary_search(allowed.begin(), allowed.end(), core)) {
139            std::fprintf(stderr, "Linux affinity test: topology selected disallowed CPU %d\n", core);
140            return false;
141        }
142    }
143    return true;
144}
145
146static bool round_trip_sparse_nested(const std::vector<int>& allowed) {
147    if (allowed.size() < 2) {
148        std::puts("SKIP sparse/nested affinity: fewer than two allowed CPUs");
149        return true;
150    }
151    const std::vector<int> sparse{allowed.front(), allowed.back()};
152    if (!set_affinity(sparse) || !expect_affinity(sparse, "establish sparse mask") ||
153        !topology_respects_current_mask()) return false;
154
155    const auto outer = cpu::pin_current_thread(sparse.front());
156    const bool outer_pinned = outer.valid && expect_affinity({sparse.front()}, "outer pin");
157    if (!outer_pinned) {
158        cpu::restore_thread_affinity(outer);
159        return false;
160    }
161
162    const auto inner = cpu::pin_current_thread(sparse.back());
163    const bool inner_pinned = inner.valid && expect_affinity({sparse.back()}, "inner pin");
164    cpu::restore_thread_affinity(inner);
165    const bool outer_restored = expect_affinity({sparse.front()}, "restore inner pin to outer pin");
166    cpu::restore_thread_affinity(outer);
167    const bool sparse_restored = expect_affinity(sparse, "restore outer pin to sparse mask");
168    const bool full_restored = set_affinity(allowed) && expect_affinity(allowed, "restore full mask after sparse test");
169    return inner_pinned && outer_restored && sparse_restored && full_restored;
170}
171
172static bool round_trip_high_cpu(const std::vector<int>& allowed, bool require_high) {
173    const auto it = std::find_if(allowed.begin(), allowed.end(), [](int id) { return id >= 64; });
174    if (it == allowed.end()) {
175        if (require_high) {
176            std::fprintf(stderr, "Linux affinity test: --require-high-cpu requested, but no allowed CPU ID is >= 64\n");
177            return false;
178        }
179        std::puts("SKIP high-CPU affinity path: no allowed CPU ID is >= 64 (use --require-high-cpu to require it)");
180        return true;
181    }
182    const int target = allowed.front() == *it ? (allowed.size() > 1 ? allowed.back() : *it) : allowed.front();
183    if (target == *it) {
184        if (require_high) {
185            std::fprintf(stderr, "Linux affinity test: --require-high-cpu needs at least two allowed CPUs to test restoration\n");
186            return false;
187        }
188        std::puts("SKIP high-CPU affinity round trip: only one CPU is allowed, so no meaningful pin transition is possible");
189        return true;
190    }
191
192    // Restrict the caller to one high-numbered CPU, then pin to a different originally allowed CPU.
193    // Restoring the high-only mask catches truncation even when the original process mask is sparse.
194    const std::vector<int> high_only{*it};
195    if (!set_affinity(high_only) || !expect_affinity(high_only, "establish high-only mask") ||
196        !topology_respects_current_mask()) return false;
197    const auto previous = cpu::pin_current_thread(target);
198    const bool pinned = previous.valid && expect_affinity({target}, "pin away from high-only mask");
199    cpu::restore_thread_affinity(previous);
200    const bool restored = pinned && expect_affinity(high_only, "restore high-only mask");
201    if (restored) std::printf("High-CPU affinity round trip: saved CPU %d, pin target %d\n", *it, target);
202    return restored;
203}
204
205static bool negative_cpu_is_noop() {
206    std::vector<int> before;
207    if (!get_affinity(before)) return false;
208    const auto invalid = cpu::pin_current_thread(-1);
209    std::vector<int> after;
210    const bool unchanged = get_affinity(after) && before == after;
211    cpu::restore_thread_affinity(invalid);
212    return !invalid.valid && unchanged && expect_affinity(before, "negative CPU no-op");
213}
214
215static bool worker_thread_can_pin(int target) {
216    bool ok = false;
217    std::thread worker([&] {
218        std::vector<int> before;
219        if (!get_affinity(before)) return;
220        std::vector<unsigned long> saved;
221        if (cpu::detail::get_thread_affinity(saved) != 0) return;
222        const int pin_error = cpu::detail::pin_thread_to_cpu(target);
223        const bool pinned = pin_error == 0 && expect_affinity({target}, "worker thread helper pin") &&
224                            sched_getcpu() == target;
225        const int restore_error = cpu::detail::set_thread_affinity(saved);
226        ok = pinned && restore_error == 0 && expect_affinity(before, "worker thread helper restore");
227    });
228    worker.join();
229    return ok;
230}
231
232static bool failed_pin_preserves_affinity() {
233    std::vector<int> before;
234    if (!get_affinity(before)) return false;
235    // An ID outside the caller's current mask may still be online and legal, so it is not a
236    // reliable failure case. INT_MAX is rejected before allocating or changing any CPU set.
237    const int error = cpu::detail::pin_thread_to_cpu(INT_MAX);
238    std::vector<int> after;
239    const bool helper_unchanged = get_affinity(after) && before == after;
240    if (error == 0) {
241        std::fprintf(stderr, "Linux affinity test: pin_thread_to_cpu(INT_MAX) unexpectedly succeeded\n");
242        return false;
243    }
244    const auto invalid = cpu::pin_current_thread(INT_MAX);
245    cpu::restore_thread_affinity(invalid);
246    std::vector<int> after_public;
247    const bool public_unchanged = get_affinity(after_public) && before == after_public;
248    if (!helper_unchanged || invalid.valid || !public_unchanged)
249        std::fprintf(stderr, "Linux affinity test: failed pin changed the observed affinity or returned a valid snapshot\n");
250    return helper_unchanged && !invalid.valid && public_unchanged;
251}
252
253int main(int argc, char** argv) {
254    bool require_high = false;
255    for (int i = 1; i < argc; ++i) {
256        if (std::strcmp(argv[i], "--require-high-cpu") == 0) require_high = true;
257        else {
258            std::fprintf(stderr, "Unknown argument: %s\n", argv[i]);
259            return 2;
260        }
261    }
262
263    OriginalAffinity original;
264    if (!original.capture()) {
265        std::fprintf(stderr, "Linux affinity test: cannot capture original thread affinity\n");
266        return 1;
267    }
268    const auto allowed = original.ids();
269
270    bool ok = round_trip_full_mask(allowed) && worker_thread_can_pin(allowed.back());
271    if (ok) ok = round_trip_sparse_nested(allowed);
272    if (ok) ok = round_trip_high_cpu(allowed, require_high);
273    if (ok) ok = negative_cpu_is_noop();
274    if (ok) ok = failed_pin_preserves_affinity();
275    const bool restored = original.restore() && expect_affinity(allowed, "final original affinity cleanup");
276    if (!ok || !restored) return 1;
277
278    std::printf("Linux affinity test: full, sparse/nested, worker helper, invalid-target, failed-pin, and cleanup checks passed (%zu allowed CPUs)\n",
279                allowed.size());
280    return 0;
281}
282
283#else
284
285int main() {
286    std::puts("SKIP Linux affinity test: Linux is required");
287    return 0;
288}
289
290#endif