okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
4f5e6c841
main
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 : 28explicit DynamicCpuSet (size_t count ) 29 :count_ (count ),bytes_ (CPU_ALLOC_SIZE (count )),set_ (CPU_ALLOC (count )) { 30if (set_ )CPU_ZERO_S (bytes_ ,set_ ); 31 } 32 33 ~DynamicCpuSet () { 34if (set_ )CPU_FREE (set_ ); 35 } 36 37DynamicCpuSet (const DynamicCpuSet & )= delete ; 38DynamicCpuSet & operator= (const DynamicCpuSet & )= delete ; 39 40cpu_set_t * get () {return set_ ; } 41const cpu_set_t * get ()const {return set_ ; } 42size_t bytes ()const {return bytes_ ; } 43size_t count ()const {return count_ ; } 44explicit operatorbool ()const {return set_ != nullptr ; } 45 46private : 47size_t count_ ; 48size_t bytes_ ; 49cpu_set_t * set_ ; 50}; 51 52static size_t initial_cpu_count () { 53const long configured = sysconf (_SC_NPROCESSORS_CONF ); 54return (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 ) { 59size_t count = initial_cpu_count (); 60for (int attempt = 0 ;attempt < 8 ;++ attempt ) { 61DynamicCpuSet set (count ); 62if (!set )return false; 63const int error = pthread_getaffinity_np (pthread_self (),set .bytes (),set .get ()); 64if (error == 0 ) { 65ids .clear (); 66for (size_t i = 0 ;i < set .count ();++ i ) 67if (CPU_ISSET_S (i ,set .bytes (),set .get ()))ids .push_back ((int )i ); 68return !ids .empty (); 69 } 70if (error != EINVAL || count > (size_t (1 ) <<20 )) { 71 std::fprintf (stderr ,"pthread_getaffinity_np failed: %s\n" , std::strerror (error )); 72return false; 73 } 74count *=2 ; 75 } 76 std::fprintf (stderr ,"pthread_getaffinity_np still needs a larger CPU set\n" ); 77return false; 78} 79 80static bool set_affinity (const std::vector < int >& ids ) { 81if (ids .empty ())return false; 82const int highest = * std::max_element (ids .begin (),ids .end ()); 83if (highest < 0 )return false; 84const size_t count = (std::max )(initial_cpu_count (), (size_t )highest + 1 ); 85DynamicCpuSet set (count ); 86if (!set )return false; 87for (int id :ids ) { 88if (id < 0 || (size_t )id >=count )return false; 89CPU_SET_S ((size_t )id ,set .bytes (),set .get ()); 90 } 91const int error = pthread_setaffinity_np (pthread_self (),set .bytes (),set .get ()); 92if (error != 0 ) { 93 std::fprintf (stderr ,"pthread_setaffinity_np failed: %s\n" , std::strerror (error )); 94return false; 95 } 96return true; 97} 98 99class OriginalAffinity { 100public : 101bool capture () {return get_affinity (ids_ ); } 102const std::vector < int >& ids ()const {return ids_ ; } 103bool 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 ; 112if (!get_affinity (actual )) { 113 std::fprintf (stderr ,"Linux affinity test: %s: cannot query current affinity\n" ,label ); 114return false; 115 } 116if (actual != expected ) { 117 std::fprintf (stderr ,"Linux affinity test: %s: expected %zu CPUs, observed %zu\n" , 118label ,expected .size (),actual .size ()); 119return false; 120 } 121return true; 122} 123 124static bool round_trip_full_mask (const std::vector < int >& allowed ) { 125const int target = allowed .front (); 126const auto previous = cpu::pin_current_thread (target ); 127const bool pinned = previous .valid && expect_affinity ({target },"pin from full allowed mask" ); 128 cpu::restore_thread_affinity (previous ); 129return pinned && expect_affinity (allowed ,"restore full allowed mask" ); 130} 131 132static bool topology_respects_current_mask () { 133 std::vector < int > allowed ; 134if (!get_affinity (allowed ))return false; 135const auto topology = cpu::detect_cpu_topology (false); 136if (topology .worker_cores .empty ())return false; 137for (int core :topology .worker_cores ) { 138if (!std::binary_search (allowed .begin (),allowed .end (),core )) { 139 std::fprintf (stderr ,"Linux affinity test: topology selected disallowed CPU %d\n" ,core ); 140return false; 141 } 142 } 143return true; 144} 145 146static bool round_trip_sparse_nested (const std::vector < int >& allowed ) { 147if (allowed .size ()< 2 ) { 148 std::puts ("SKIP sparse/nested affinity: fewer than two allowed CPUs" ); 149return true; 150 } 151const std::vector < int > sparse {allowed .front (),allowed .back ()}; 152if (!set_affinity (sparse )|| !expect_affinity (sparse ,"establish sparse mask" )|| 153 !topology_respects_current_mask ())return false; 154 155const auto outer = cpu::pin_current_thread (sparse .front ()); 156const bool outer_pinned = outer .valid && expect_affinity ({sparse .front ()},"outer pin" ); 157if (!outer_pinned ) { 158 cpu::restore_thread_affinity (outer ); 159return false; 160 } 161 162const auto inner = cpu::pin_current_thread (sparse .back ()); 163const bool inner_pinned = inner .valid && expect_affinity ({sparse .back ()},"inner pin" ); 164 cpu::restore_thread_affinity (inner ); 165const bool outer_restored = expect_affinity ({sparse .front ()},"restore inner pin to outer pin" ); 166 cpu::restore_thread_affinity (outer ); 167const bool sparse_restored = expect_affinity (sparse ,"restore outer pin to sparse mask" ); 168const bool full_restored = set_affinity (allowed )&& expect_affinity (allowed ,"restore full mask after sparse test" ); 169return inner_pinned && outer_restored && sparse_restored && full_restored ; 170} 171 172static bool round_trip_high_cpu (const std::vector < int >& allowed ,bool require_high ) { 173const auto it = std::find_if (allowed .begin (),allowed .end (), [](int id ) {return id >=64 ; }); 174if (it == allowed .end ()) { 175if (require_high ) { 176 std::fprintf (stderr ,"Linux affinity test: --require-high-cpu requested, but no allowed CPU ID is >= 64\n" ); 177return false; 178 } 179 std::puts ("SKIP high-CPU affinity path: no allowed CPU ID is >= 64 (use --require-high-cpu to require it)" ); 180return true; 181 } 182const int target = allowed .front ()== * it ? (allowed .size ()> 1 ?allowed .back () :* it ) :allowed .front (); 183if (target == * it ) { 184if (require_high ) { 185 std::fprintf (stderr ,"Linux affinity test: --require-high-cpu needs at least two allowed CPUs to test restoration\n" ); 186return false; 187 } 188 std::puts ("SKIP high-CPU affinity round trip: only one CPU is allowed, so no meaningful pin transition is possible" ); 189return 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. 194const std::vector < int > high_only {* it }; 195if (!set_affinity (high_only )|| !expect_affinity (high_only ,"establish high-only mask" )|| 196 !topology_respects_current_mask ())return false; 197const auto previous = cpu::pin_current_thread (target ); 198const bool pinned = previous .valid && expect_affinity ({target },"pin away from high-only mask" ); 199 cpu::restore_thread_affinity (previous ); 200const bool restored = pinned && expect_affinity (high_only ,"restore high-only mask" ); 201if (restored ) std::printf ("High-CPU affinity round trip: saved CPU %d, pin target %d\n" ,* it ,target ); 202return restored ; 203} 204 205static bool negative_cpu_is_noop () { 206 std::vector < int > before ; 207if (!get_affinity (before ))return false; 208const auto invalid = cpu::pin_current_thread (-1 ); 209 std::vector < int > after ; 210const bool unchanged = get_affinity (after )&& before == after ; 211 cpu::restore_thread_affinity (invalid ); 212return !invalid .valid && unchanged && expect_affinity (before ,"negative CPU no-op" ); 213} 214 215static bool worker_thread_can_pin (int target ) { 216bool ok = false; 217 std::thread worker ([& ] { 218 std::vector < int > before ; 219if (!get_affinity (before ))return ; 220 std::vector < unsigned long > saved ; 221if (cpu::detail::get_thread_affinity (saved )!= 0 )return ; 222const int pin_error = cpu::detail::pin_thread_to_cpu (target ); 223const bool pinned = pin_error == 0 && expect_affinity ({target },"worker thread helper pin" )&& 224sched_getcpu ()== target ; 225const int restore_error = cpu::detail::set_thread_affinity (saved ); 226ok = pinned && restore_error == 0 && expect_affinity (before ,"worker thread helper restore" ); 227 }); 228worker .join (); 229return ok ; 230} 231 232static bool failed_pin_preserves_affinity () { 233 std::vector < int > before ; 234if (!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. 237const int error = cpu::detail::pin_thread_to_cpu (INT_MAX ); 238 std::vector < int > after ; 239const bool helper_unchanged = get_affinity (after )&& before == after ; 240if (error == 0 ) { 241 std::fprintf (stderr ,"Linux affinity test: pin_thread_to_cpu(INT_MAX) unexpectedly succeeded\n" ); 242return false; 243 } 244const auto invalid = cpu::pin_current_thread (INT_MAX ); 245 cpu::restore_thread_affinity (invalid ); 246 std::vector < int > after_public ; 247const bool public_unchanged = get_affinity (after_public )&& before == after_public ; 248if (!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" ); 250return helper_unchanged && !invalid .valid && public_unchanged ; 251} 252 253int main (int argc ,char ** argv ) { 254bool require_high = false; 255for (int i = 1 ;i < argc ;++ i ) { 256if (std::strcmp (argv [i ],"--require-high-cpu" )== 0 )require_high = true; 257else { 258 std::fprintf (stderr ,"Unknown argument: %s\n" ,argv [i ]); 259return 2 ; 260 } 261 } 262 263OriginalAffinity original ; 264if (!original .capture ()) { 265 std::fprintf (stderr ,"Linux affinity test: cannot capture original thread affinity\n" ); 266return 1 ; 267 } 268const auto allowed = original .ids (); 269 270bool ok = round_trip_full_mask (allowed )&& worker_thread_can_pin (allowed .back ()); 271if (ok )ok = round_trip_sparse_nested (allowed ); 272if (ok )ok = round_trip_high_cpu (allowed ,require_high ); 273if (ok )ok = negative_cpu_is_noop (); 274if (ok )ok = failed_pin_preserves_affinity (); 275const bool restored = original .restore ()&& expect_affinity (allowed ,"final original affinity cleanup" ); 276if (!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" , 279allowed .size ()); 280return 0 ; 281} 282 283#else 284 285int main () { 286 std::puts ("SKIP Linux affinity test: Linux is required" ); 287return 0 ; 288} 289 290#endif