okami.mom/strata

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

Niko1221Merge branch 'f-split-int' into f-split-vision7c5e84612

main
8.4 KiB173 linesraw
1#include "strata/kernels/cpu/pool.hpp"
2#include "pool_affinity_win.hpp"
3
4#include <algorithm>
5#include <cstdio>
6#include <thread>
7#include <vector>
8
9namespace cpu = strata::kernels::cpu;
10
11static bool check(bool ok, const char* message) {
12    if (!ok) std::fprintf(stderr, "Windows affinity test: %s (error %lu)\n", message, (unsigned long) GetLastError());
13    return ok;
14}
15
16static bool select(const std::vector<ULONG>& ids) {
17    return SetThreadSelectedCpuSets(GetCurrentThread(), ids.empty() ? nullptr : ids.data(), (ULONG) ids.size()) != 0;
18}
19
20static bool selected_is(std::vector<ULONG> expected) {
21    std::vector<ULONG> actual;
22    if (!cpu::detail::get_thread_cpu_sets(actual)) return false;
23    std::sort(actual.begin(), actual.end());
24    std::sort(expected.begin(), expected.end());
25    return actual == expected;
26}
27
28// Establish reachability before the round trip: CPU Sets are soft affinity and cannot override an
29// existing job/hard-affinity restriction. Afterwards, require the same observable reachability.
30static bool observe(int core) {
31    for (int i = 0; i < 200; ++i) {
32        Sleep(1);
33        PROCESSOR_NUMBER current{};
34        GetCurrentProcessorNumberEx(&current);
35        if ((int) current.Group * 64 + current.Number == core) return true;
36    }
37    return false;
38}
39
40static bool host_round_trips(const std::vector<int>& cores, const std::vector<ULONG>& ids) {
41    if (!check(select({}), "clear initial thread CPU Sets")) return false;
42    std::vector<bool> reachable;
43    for (size_t i = 0; i < cores.size(); ++i) {
44        if (!check(select({ids[i]}), "select baseline CPU Set")) return false;
45        reachable.push_back(observe(cores[i]));
46    }
47    if (!check(select({}), "clear baseline CPU Sets")) return false;
48
49    for (size_t i = 0; i < cores.size(); ++i) {
50        const auto previous = cpu::pin_current_thread(cores[i]);
51        const bool pinned = previous.valid && previous.cpu_sets.empty() && selected_is({ids[i]});
52        cpu::restore_thread_affinity(previous);
53        if (!check(pinned && selected_is({}), "restore empty thread assignment")) return false;
54    }
55
56    // GetThreadGroupAffinity alone misses a lost implicit all-group state. Selecting each CPU Set
57    // again must still permit execution there, without ever setting a hard group affinity.
58    for (size_t i = 0; i < cores.size(); ++i) {
59        if (!check(select({ids[i]}), "select CPU Set after restore")) return false;
60        if (reachable[i]) {
61            if (!check(observe(cores[i]), "lost CPU/group eligibility after host restore")) return false;
62            std::printf("Host restore: still executes on group %d processor %d\n", cores[i] / 64, cores[i] & 63);
63        } else {
64            std::printf("SKIP scheduling observation for group %d: not reachable before test\n", cores[i] / 64);
65        }
66    }
67
68    // A nonempty selection may span groups. Nested host selections must restore the entire set.
69    if (!check(select(ids), "set existing multi-CPU selection")) return false;
70    const auto outer = cpu::pin_current_thread(cores.front());
71    const auto inner = cpu::pin_current_thread(cores.back());
72    const bool inner_ok = inner.valid && selected_is({ids.back()});
73    cpu::restore_thread_affinity(inner);
74    const bool outer_ok = outer.valid && selected_is({ids.front()});
75    cpu::restore_thread_affinity(outer);
76    if (!check(inner_ok && outer_ok && selected_is(ids), "restore nested / existing CPU Set selections")) return false;
77    const auto invalid = cpu::pin_current_thread(-1);
78    cpu::restore_thread_affinity(invalid);
79    if (!check(!invalid.valid && selected_is(ids), "invalid target must not mutate selection")) return false;
80    return check(select({}), "clear final host selection");
81}
82
83static bool inherited_default(int core, ULONG id, int temporary_core, ULONG temporary_id) {
84    ULONG count = 0;
85    if (!GetProcessDefaultCpuSets(GetCurrentProcess(), nullptr, 0, &count) &&
86        GetLastError() != ERROR_INSUFFICIENT_BUFFER) return false;
87    std::vector<ULONG> saved(count);
88    if (count && !GetProcessDefaultCpuSets(GetCurrentProcess(), saved.data(), count, &count)) return false;
89    saved.resize(count);
90    if (!check(SetProcessDefaultCpuSets(GetCurrentProcess(), &id, 1) != 0, "set process default")) return false;
91    bool ok = false;
92    std::thread host([&] {
93        if (!select({})) return;
94        const bool reachable = observe(core);
95        const auto previous = cpu::pin_current_thread(temporary_core);
96        const bool overridden = previous.valid && selected_is({temporary_id});
97        cpu::restore_thread_affinity(previous);
98        ULONG inherited = 0, required = 0;
99        ok = overridden && previous.cpu_sets.empty() && selected_is({}) &&
100             GetProcessDefaultCpuSets(GetCurrentProcess(), &inherited, 1, &required) &&
101             required == 1 && inherited == id && (!reachable || observe(core));
102    });
103    host.join();
104    const bool restored = SetProcessDefaultCpuSets(GetCurrentProcess(), saved.empty() ? nullptr : saved.data(),
105                                                  (ULONG) saved.size()) != 0;
106    return check(ok && restored, "restore inherited process default");
107}
108
109// --host-core sibling: the host on the first layout's host core's SMT sibling, which no worker takes, and the first
110// logical processor left to nothing; `first` on a core without SMT.  Every affinity mode.
111static bool host_sibling_layout() {
112    bool ok = true;
113    for (const auto affinity : {cpu::PoolAffinity::All, cpu::PoolAffinity::Auto, cpu::PoolAffinity::PCores}) {
114        cpu::set_host_core(cpu::HostCore::First);
115        const cpu::CpuTopology first = cpu::detect_cpu_topology(true, affinity);
116        cpu::set_host_core(cpu::HostCore::Sibling);
117        const cpu::CpuTopology sib = cpu::detect_cpu_topology(true, affinity);
118        cpu::set_host_core(cpu::HostCore::First);
119        const auto has = [&](int core) {
120            return std::find(sib.worker_cores.begin(), sib.worker_cores.end(), core) != sib.worker_cores.end();
121        };
122        if (first.host_sibling < 0)
123            ok = check(sib.host_core == first.host_core && sib.worker_cores == first.worker_cores,
124                       "--host-core sibling without SMT must be first") && ok;
125        else
126            ok = check(sib.host_core == first.host_sibling && sib.host_core != first.host_core && !has(sib.host_core) &&
127                           !has(first.host_core),
128                       "--host-core sibling: the host on the sibling, no worker on its core") && ok;
129    }
130    return ok;
131}
132
133int main() {
134    if (!host_sibling_layout()) return 1;
135    const auto all = cpu::physical_cores(false);
136    std::vector<int> cores;
137    std::vector<ULONG> ids;
138    for (int core : all) {
139        if (std::any_of(cores.begin(), cores.end(), [core](int other) { return other / 64 == core / 64; })) continue;
140        ULONG id = 0;
141        if (!cpu::detail::cpu_set_for_core(core, id)) continue;
142        cores.push_back(core);
143        ids.push_back(id);
144    }
145    if (!check(!cores.empty(), "no usable CPU Sets")) return 1;
146    if (!check(cores.size() == GetActiveProcessorGroupCount(), "CPU Sets do not cover all active groups")) return 1;
147
148    // Hard pins belong on pool-owned threads; never contaminate the caller under test with one.
149    for (size_t i = 0; i < cores.size(); ++i) {
150        bool ok = false;
151        std::thread worker([&] {
152            if (!cpu::detail::set_thread_group_affinity(cores[i], (int) i)) return;
153            GROUP_AFFINITY pinned{};
154            if (!GetThreadGroupAffinity(GetCurrentThread(), &pinned)) return;
155            ok = pinned.Group == cores[i] / 64 && pinned.Mask == (KAFFINITY(1) << (cores[i] & 63));
156            // Host placement must also preserve an existing restrictive hard affinity.
157            const auto previous = cpu::pin_current_thread(cores.back());
158            cpu::restore_thread_affinity(previous);
159            GROUP_AFFINITY after{};
160            ok = ok && previous.valid && GetThreadGroupAffinity(GetCurrentThread(), &after) &&
161                 after.Group == pinned.Group && after.Mask == pinned.Mask;
162        });
163        worker.join();
164        if (!check(ok, "worker hard pin / caller hard-affinity preservation")) return 1;
165    }
166
167    bool host_ok = false;
168    std::thread host([&] { host_ok = host_round_trips(cores, ids); });
169    host.join();
170    if (!host_ok || !inherited_default(cores.back(), ids.back(), cores.front(), ids.front())) return 1;
171    std::printf("Windows affinity test: worker pins, host CPU Sets and process-default restoration passed (%zu groups)\n", cores.size());
172    return 0;
173}