Debian Codegraph @

rpython/translator/c/src/thread_win7.c

raw symbols SCIP
1 /* Copy-and-pasted from CPython at 3.10.14
2 * by following code paths with !_PY_EMULATED_WIN_CV
3 */
4
5 #define WIN32_LEAN_AND_MEAN
6 #include <stdint.h>
7 #include <stdio.h>
8 #include <limits.h>
9 #include <process.h>
10 #include <windows.h>
11
12
13 /*
14 * Thread support.
15 */
16 /* In rpython, this file is pulled in by thread.c */
17
18 /* see thread_win7.h */
19 typedef struct RPyOpaque_ThreadLock NRMUTEX, *PNRMUTEX;
20
21 /* -------------------------
22 * From Include/pyport.h
23 */
24
25 /* enable more aggressive optimization for MSVC */
26 /* active in both release and debug builds - see bpo-43271 */
27 # pragma optimize("gt", on)
28 /* ignore warnings if the compiler decides not to inline a function */
29 # pragma warning(disable: 4710)
30 # define Py_LOCAL_INLINE(type) static __inline type __fastcall
31
32 /* -------------------------
33 * From Include/internal/pycore_condvar.h
34 */
35
36 /* Use native Win7 primitives if build target is Win7 or higher */
37
38 /* SRWLOCK is faster and better than CriticalSection */
39 typedef SRWLOCK PyMUTEX_T;
40
41 typedef CONDITION_VARIABLE PyCOND_T;
42
43 /* -------------------------
44 * Taken from Python/pytime.c
45 */
46
47 typedef long long _RPyTime_t;
48 #define _RPyTime_MAX INT64_MAX
49 typedef enum {
50 _RPyTime_ROUND_FLOOR=0,
51 _RPyTime_ROUND_CEILING=1,
52 _RPyTime_ROUND_HALF_EVEN=2,
53 _RPyTime_ROUND_UP=3,
54 _RPyTime_ROUND_TIMEOUT = _RPyTime_ROUND_UP
55 } _RPyTime_round_t;
56
57
58 static _RPyTime_t
59 _PyTime_Divide(const _RPyTime_t t, const _RPyTime_t k,
60 const _RPyTime_round_t round)
61 {
62 assert(k > 1);
63 if (round == _RPyTime_ROUND_HALF_EVEN) {
64 _RPyTime_t x, r, abs_r;
65 x = t / k;
66 r = t % k;
67 abs_r = abs(r);
68 if (abs_r > k / 2 || (abs_r == k / 2 && (abs(x) & 1))) {
69 if (t >= 0) {
70 x++;
71 }
72 else {
73 x--;
74 }
75 }
76 return x;
77 }
78 else if (round == _RPyTime_ROUND_CEILING) {
79 if (t >= 0) {
80 return (t + k - 1) / k;
81 }
82 else {
83 return t / k;
84 }
85 }
86 else if (round == _RPyTime_ROUND_FLOOR){
87 if (t >= 0) {
88 return t / k;
89 }
90 else {
91 return (t - (k - 1)) / k;
92 }
93 }
94 else {
95 assert(round == _RPyTime_ROUND_UP);
96 if (t >= 0) {
97 return (t + k - 1) / k;
98 }
99 else {
100 return (t - (k - 1)) / k;
101 }
102 }
103 }
104
105
106 static _RPyTime_t
107 _RPyTime_AsMicroseconds(_RPyTime_t t, _RPyTime_round_t round)
108 {
109 return _PyTime_Divide(t, 1000, round);
110 }
111
112 #define SEC_TO_NS (1000 * 1000 * 1000)
113
114 static int
115 win_perf_counter_frequency(LONGLONG *pfrequency)
116 {
117 LONGLONG frequency;
118
119 LARGE_INTEGER freq;
120 if (!QueryPerformanceFrequency(&freq)) {
121 return -1;
122 }
123 frequency = freq.QuadPart;
124
125 /* Sanity check: should never occur in practice */
126 if (frequency < 1) {
127 return -1;
128 }
129
130 if (frequency > _RPyTime_MAX
131 || frequency > (LONGLONG)_RPyTime_MAX / (LONGLONG)SEC_TO_NS)
132 {
133 return -1;
134 }
135
136 *pfrequency = frequency;
137 return 0;
138 }
139
140 static _RPyTime_t
141 RPyTime_MulDiv(_RPyTime_t ticks, _RPyTime_t mul, _RPyTime_t div)
142 {
143 _RPyTime_t intpart, remaining;
144 /* Compute (ticks * mul / div) in two parts to prevent integer overflow:
145 compute integer part, and then the remaining part.
146
147 (ticks * mul) / div == (ticks / div) * mul + (ticks % div) * mul / div
148
149 The caller must ensure that "(div - 1) * mul" cannot overflow. */
150 intpart = ticks / div;
151 ticks %= div;
152 remaining = ticks * mul;
153 remaining /= div;
154 return intpart * mul + remaining;
155 }
156
157 static int
158 py_get_win_perf_counter(_RPyTime_t *tp)
159 {
160 static LONGLONG frequency = 0;
161 if (frequency == 0) {
162 if (win_perf_counter_frequency(&frequency) < 0) {
163 return -1;
164 }
165 }
166
167 LARGE_INTEGER now;
168 QueryPerformanceCounter(&now);
169 LONGLONG ticksll = now.QuadPart;
170
171 /* Make sure that casting LONGLONG to _RPyTime_t cannot overflow,
172 * both types are signed */
173 _RPyTime_t ticks;
174 assert(sizeof(ticksll) <= sizeof(ticks));
175 ticks = (_RPyTime_t)ticksll;
176
177 *tp = RPyTime_MulDiv(ticks, SEC_TO_NS, (_RPyTime_t)frequency);
178 return 0;
179 }
180
181
182 static _RPyTime_t
183 RPyTime_GetPerfCounter(void)
184 {
185 _RPyTime_t t;
186 int res;
187 res = py_get_win_perf_counter(&t);
188 if (res < 0) {
189 // If win_perf_counter_frequency() or py_get_monotonic_clock() fails:
190 // silently ignore the failure and return 0.
191 t = 0;
192 }
193 return t;
194 }
195
196
197
198 /* -------------------------
199 * From Python/condvar.h
200 */
201
202
203 Py_LOCAL_INLINE(int)
204 PyMUTEX_INIT(PyMUTEX_T *cs)
205 {
206 InitializeSRWLock(cs);
207 return 0;
208 }
209
210 Py_LOCAL_INLINE(int)
211 PyMUTEX_FINI(PyMUTEX_T *cs)
212 {
213 return 0;
214 }
215
216 Py_LOCAL_INLINE(int)
217 PyMUTEX_LOCK(PyMUTEX_T *cs)
218 {
219 AcquireSRWLockExclusive(cs);
220 return 0;
221 }
222
223 Py_LOCAL_INLINE(int)
224 PyMUTEX_UNLOCK(PyMUTEX_T *cs)
225 {
226 ReleaseSRWLockExclusive(cs);
227 return 0;
228 }
229
230
231 Py_LOCAL_INLINE(int)
232 PyCOND_INIT(PyCOND_T *cv)
233 {
234 InitializeConditionVariable(cv);
235 return 0;
236 }
237 Py_LOCAL_INLINE(int)
238 PyCOND_FINI(PyCOND_T *cv)
239 {
240 return 0;
241 }
242
243 Py_LOCAL_INLINE(int)
244 PyCOND_WAIT(PyCOND_T *cv, PyMUTEX_T *cs)
245 {
246 return SleepConditionVariableSRW(cv, cs, INFINITE, 0) ? 0 : -1;
247 }
248
249 /* This implementation makes no distinction about timeouts. Signal
250 * 2 to indicate that we don't know.
251 */
252 Py_LOCAL_INLINE(int)
253 PyCOND_TIMEDWAIT(PyCOND_T *cv, PyMUTEX_T *cs, long long us)
254 {
255 /* timeout in milliseconds */
256 DWORD ms = (DWORD)_PyTime_Divide(us, 1000, _RPyTime_ROUND_TIMEOUT);
257 return SleepConditionVariableSRW(cv, cs, ms, 0) != 0 ? 2 : -1;
258 }
259
260 Py_LOCAL_INLINE(int)
261 PyCOND_SIGNAL(PyCOND_T *cv)
262 {
263 WakeConditionVariable(cv);
264 return 0;
265 }
266
267 Py_LOCAL_INLINE(int)
268 PyCOND_BROADCAST(PyCOND_T *cv)
269 {
270 WakeAllConditionVariable(cv);
271 return 0;
272 }
273 /* -------------------------
274 * Taken from Python/thread_nt.h
275 */
276
277 #if 0
278 #define PyMem_RawMalloc malloc
279 #define PyMem_RawFree free
280
281 PNRMUTEX
282 AllocNonRecursiveMutex()
283 {
284 PNRMUTEX m = (PNRMUTEX)PyMem_RawMalloc(sizeof(NRMUTEX));
285 if (!m)
286 return NULL;
287 if (PyCOND_INIT(&m->cv))
288 goto fail;
289 if (PyMUTEX_INIT(&m->cs)) {
290 PyCOND_FINI(&m->cv);
291 goto fail;
292 }
293 m->locked = 0;
294 return m;
295 fail:
296 PyMem_RawFree(m);
297 return NULL;
298 }
299 VOID
300 FreeNonRecursiveMutex(PNRMUTEX mutex)
301 {
302 if (mutex) {
303 PyCOND_FINI(&mutex->cv);
304 PyMUTEX_FINI(&mutex->cs);
305 PyMem_RawFree(mutex);
306 }
307 }
308 #endif
309
310 static void gil_fatal(const char *msg, int64_t dw) {
311 fprintf(stderr, "Fatal error in the GIL or with locks: %s [%llx,%x]\n",
312 msg, dw, (int)GetLastError());
313 abort();
314 }
315
316 DWORD
317 EnterNonRecursiveMutex(PNRMUTEX mutex, RPY_TIMEOUT_T microseconds)
318 {
319 DWORD result = WAIT_OBJECT_0;
320 if (PyMUTEX_LOCK(&mutex->cs))
321 return WAIT_FAILED;
322 if (microseconds == INFINITE) {
323 while (mutex->locked) {
324 if (PyCOND_WAIT(&mutex->cv, &mutex->cs)) {
325 result = WAIT_FAILED;
326 break;
327 }
328 }
329 } else if (microseconds != 0) {
330 /* wait at least until the target */
331 _RPyTime_t now_ns = RPyTime_GetPerfCounter();
332 if (now_ns <= 0) {
333 gil_fatal("RPyTime_GetPerfCounter() <= 0", (int)now_ns);
334 }
335 /* This can fail to timeout if microseconds is too big */
336 _RPyTime_t target_ns = now_ns + (microseconds * 1000);
337 while (mutex->locked) {
338 if (PyCOND_TIMEDWAIT(&mutex->cv, &mutex->cs, microseconds) < 0) {
339 DWORD err = GetLastError();
340 if (err != ERROR_TIMEOUT) {
341 fprintf(stderr, "EnterNonRecursiveMutex failed %d\n", GetLastError());
342 result = WAIT_FAILED;
343 break;
344 }
345 }
346 now_ns = RPyTime_GetPerfCounter();
347 if (target_ns <= now_ns)
348 break;
349 microseconds = _RPyTime_AsMicroseconds(target_ns - now_ns, _RPyTime_ROUND_TIMEOUT);
350 }
351 }
352 if (!mutex->locked) {
353 mutex->locked = 1;
354 result = WAIT_OBJECT_0;
355 } else if (result == WAIT_OBJECT_0)
356 result = WAIT_TIMEOUT;
357 /* else, it is WAIT_FAILED */
358 PyMUTEX_UNLOCK(&mutex->cs); /* must ignore result here */
359 return result;
360 }
361
362 BOOL
363 LeaveNonRecursiveMutex(PNRMUTEX mutex)
364 {
365 BOOL result;
366 if (!mutex->locked) {
367 return FALSE;
368 }
369 PyMUTEX_LOCK(&mutex->cs);
370 mutex->locked = 0;
371 /* condvar APIs return 0 on success. We need to return TRUE on success. */
372 PyCOND_SIGNAL(&mutex->cv);
373 PyMUTEX_UNLOCK(&mutex->cs);
374 return TRUE;
375 }
376
377 typedef struct {
378 void (*func)(void *);
379 void *arg;
380 Signed id;
381 HANDLE done;
382 } callobj;
383
384 /* win64: _beginthread takes a UINT so we can store this in a long */
385 static long _pypythread_stacksize = 0;
386
387 static void
388 bootstrap(void *call)
389 {
390 callobj *obj = (callobj*)call;
391 /* copy callobj since other thread might free it before we're done */
392 void (*func)(void *) = obj->func;
393 void *arg = obj->arg;
394
395 obj->id = (Signed)GetCurrentThreadId();
396 if (!ReleaseSemaphore(obj->done, 1, NULL))
397 gil_fatal("bootstrap ReleaseSemaphore", 0);
398 func(arg);
399 }
400
401 Signed RPyThreadStart(void (*func)(void))
402 {
403 /* a kind-of-invalid cast, but the 'func' passed here doesn't expect
404 any argument, so it's unlikely to cause problems */
405 return RPyThreadStartEx((void(*)(void *))func, NULL);
406 }
407
408 Signed RPyThreadStartEx(void (*func)(void *), void *arg)
409 {
410 Unsigned rv;
411 callobj obj;
412
413 obj.id = -1; /* guilty until proved innocent */
414 obj.func = func;
415 obj.arg = arg;
416 obj.done = CreateSemaphore(NULL, 0, 1, NULL);
417 if (obj.done == NULL)
418 return -1;
419
420 rv = _beginthread(bootstrap, _pypythread_stacksize, &obj);
421 if (rv == (Unsigned)-1) {
422 /* I've seen errno == EAGAIN here, which means "there are
423 * too many threads".
424 */
425 obj.id = -1;
426 }
427 else {
428 /* wait for thread to initialize, so we can get its id */
429 DWORD res = WaitForSingleObject(obj.done, INFINITE);
430 if (res != WAIT_OBJECT_0)
431 gil_fatal("WaitForSingleObject(obj.done) failed", res);
432 if (obj.id == -1)
433 gil_fatal("obj.id == -1", 0);
434 }
435 CloseHandle((HANDLE)obj.done);
436 return obj.id;
437 }
438
439 /************************************************************/
440 /* PyPy RPython from here
441 * but RPyThread* calls are strongly adapted on the thread_nt.h code
442 */
443
444
445
446 /* minimum/maximum thread stack sizes supported */
447 /* win64: _beginthread takes a UINT, so max must be <4GB.
448 It is also stored in a LONG (see above), it must be <2GB.
449 The functions below take Signed to simplify Python code. */
450 #define THREAD_MIN_STACKSIZE 0x8000 /* 32kB */
451 #define THREAD_MAX_STACKSIZE 0x10000000 /* 256MB */
452
453 Signed RPyThreadGetStackSize(void)
454 {
455 return _pypythread_stacksize;
456 }
457
458 Signed RPyThreadSetStackSize(Signed newsize)
459 {
460 if (newsize == 0) { /* set to default */
461 _pypythread_stacksize = 0;
462 return 0;
463 }
464
465 /* check the range */
466 if (newsize >= THREAD_MIN_STACKSIZE && newsize < THREAD_MAX_STACKSIZE) {
467 /* win64: this cast is safe, see THREAD_MAX_STACKSIZE comment */
468 _pypythread_stacksize = (long) newsize;
469 return 0;
470 }
471 return -1;
472 }
473
474 unsigned long
475 RPyThread_get_thread_native_id(void)
476 {
477 DWORD native_id;
478 native_id = GetCurrentThreadId();
479 return (unsigned long) native_id;
480 }
481
482 /************************************************************/
483
484
485
486 void RPyThreadAfterFork(void)
487 {
488 }
489
490 int RPyThreadLockInit(struct RPyOpaque_ThreadLock *lock)
491 {
492 /* In upstream this is AllocNonRecursiveMutex */
493 if (!lock)
494 return -1;
495 if (PyCOND_INIT(&lock->cv))
496 return -2;
497 if (PyMUTEX_INIT(&lock->cs)) {
498 PyCOND_FINI(&lock->cv);
499 return -3;
500 }
501 lock->locked = 0;
502 return 1;
503 }
504
505 void RPyOpaqueDealloc_ThreadLock(struct RPyOpaque_ThreadLock *mutex)
506 {
507 /* FreeNonRecursiveMutex(lock) without the "free" */
508 if (mutex) {
509 PyCOND_FINI(&mutex->cv);
510 PyMUTEX_FINI(&mutex->cs);
511 }
512 }
513
514 /*
515 * Return 1 on success if the lock was acquired
516 *
517 * and 0 if the lock was not acquired. This means a 0 is returned
518 * if the lock has already been acquired by this thread!
519 */
520 RPyLockStatus
521 RPyThreadAcquireLockTimed(struct RPyOpaque_ThreadLock *aLock,
522 RPY_TIMEOUT_T microseconds, int intr_flag)
523 {
524 /* Fow now, intr_flag does nothing on Windows, and lock acquires are
525 * uninterruptible. */
526 RPyLockStatus success;
527
528 if (microseconds < 0) {
529 microseconds = INFINITE;
530 }
531 if (aLock && EnterNonRecursiveMutex((PNRMUTEX)aLock,
532 microseconds) == WAIT_OBJECT_0) {
533 success = RPY_LOCK_ACQUIRED;
534 }
535 else {
536 success = RPY_LOCK_FAILURE;
537 }
538
539 return success;
540 }
541
542 int RPyThreadAcquireLock(struct RPyOpaque_ThreadLock *lock, int waitflag)
543 {
544 return RPyThreadAcquireLockTimed(lock, waitflag ? -1 : 0, /*intr_flag=*/0);
545 }
546
547 Signed RPyThreadReleaseLock(struct RPyOpaque_ThreadLock *lock)
548 {
549 if (LeaveNonRecursiveMutex(lock))
550 return 0; /* success */
551 else
552 return -1; /* failure: the lock was not previously acquired */
553 }
554
555 /************************************************************/
556 /* GIL code */
557 /************************************************************/
558
559 #define ASSERT_STATUS(call) \
560 if (call != 0) { \
561 fprintf(stderr, "Fatal error: " #call); \
562 abort(); \
563 }
564
565
566 typedef PyMUTEX_T mutex1_t;
567
568 static INLINE void mutex1_init(mutex1_t *mutex) {
569 ASSERT_STATUS(PyMUTEX_INIT(mutex));
570 }
571
572 static INLINE void mutex1_lock(mutex1_t *mutex) {
573 ASSERT_STATUS(PyMUTEX_LOCK(mutex));
574 }
575
576 static INLINE void mutex1_unlock(mutex1_t *mutex) {
577 ASSERT_STATUS(PyMUTEX_UNLOCK(mutex));
578 }
579
580 typedef NRMUTEX mutex2_t;
581
582 static INLINE void mutex2_init_locked(mutex2_t *mutex) {
583 mutex->locked = 1;
584 ASSERT_STATUS(PyCOND_INIT(&mutex->cv));
585 ASSERT_STATUS(PyMUTEX_INIT(&mutex->cs));
586 }
587
588 static INLINE void mutex2_unlock(mutex2_t *mutex) {
589 ASSERT_STATUS(PyMUTEX_LOCK(&mutex->cs));
590 mutex->locked = 0;
591 ASSERT_STATUS(PyMUTEX_UNLOCK(&mutex->cs));
592 PyCOND_SIGNAL(&mutex->cv);
593 }
594 static INLINE void mutex2_signal(mutex2_t *mutex) {
595 /* Signal without changing locked state. Used to wake a stealer that
596 is sleeping in SleepConditionVariableSRW so it can re-check rpy_fastgil.
597 Safe to call without holding mutex->cs; a missed wakeup is benign
598 because the stealer's SleepConditionVariableSRW has a fallback timeout. */
599 PyCOND_SIGNAL(&mutex->cv);
600 }
601
602 static INLINE void mutex2_loop_start(mutex2_t *mutex) {
603 ASSERT_STATUS(PyMUTEX_LOCK(&mutex->cs));
604 }
605 static INLINE void mutex2_loop_stop(mutex2_t *mutex) {
606 ASSERT_STATUS(PyMUTEX_UNLOCK(&mutex->cs));
607 }
608
609 static INLINE int mutex2_lock_timeout(mutex2_t *mutex, double delay)
610 {
611 if (mutex->locked) {
612 /* delay in seconds */
613 DWORD ms = (DWORD)(delay * 1000.0 + 0.999);
614 int error_from_timedwait = SleepConditionVariableSRW(&mutex->cv, &mutex->cs, ms, 0);
615 if (error_from_timedwait == 0) {
616 DWORD err = GetLastError();
617 if (err != ERROR_TIMEOUT) {
618 ASSERT_STATUS(error_from_timedwait);
619 }
620 }
621 }
622 int result = !mutex->locked;
623 mutex->locked = 1;
624 return result;
625 }
626
627 //#define pypy_lock_test_and_set(ptr, value) see thread_nt.h
628 #ifdef _WIN64
629 #define atomic_increment(ptr) InterlockedIncrement64(ptr)
630 #define atomic_decrement(ptr) InterlockedDecrement64(ptr)
631 #else
632 #define atomic_increment(ptr) InterlockedIncrement(ptr)
633 #define atomic_decrement(ptr) InterlockedDecrement(ptr)
634 #endif
635 #ifdef YieldProcessor
636 # define RPy_YieldProcessor() YieldProcessor()
637 #else
638 # define RPy_YieldProcessor() __asm { rep nop }
639 #endif
640 #define RPy_CompilerMemoryBarrier() _ReadWriteBarrier()
641
642 #include "src/thread_gil.c"