Repository navigation
Expand file tree
/
Copy pathpthread.c
More file actions
2130 lines (1782 loc) · 57.1 KB
/
Copy pathpthread.c
File metadata and controls
2130 lines (1782 loc) · 57.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 2014,2026 The F9 Microkernel Project. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <l4/ipc.h>
#include <l4/pager.h>
#include <l4/schedule.h>
#include <l4/thread.h>
#include <l4/utcb.h>
#include <l4io.h>
#include <platform/link.h>
#include <posix/pthread.h>
#include <posix/sched.h>
#include __L4_INC_ARCH(syscalls.h)
/* Signal cleanup function - defined in signal.c */
extern void __signal_thread_cleanup(L4_ThreadId_t tid);
/* Cancel cleanup function - defined later in this file */
void __cancel_thread_cleanup(pthread_t *thread);
/* Thread lifecycle states */
#define PTHREAD_STATE_CREATED 0
#define PTHREAD_STATE_RUNNING 1
#define PTHREAD_STATE_EXITED 2
/*
* Shared spinlock helpers for waiter list serialization
*
* Uses Test-and-Test-and-Set (TTAS) pattern for reduced bus traffic:
* 1. Plain load to check if free (cache-friendly, no exclusive marking)
* 2. Only if free, attempt LDREX/STREX sequence
*
* On single-core Cortex-M this is a minor optimization, but cleaner
* and beneficial on multi-core platforms.
*/
/* Spinlock acquire using TTAS pattern with LDREX/STREX */
__USER_TEXT
static void spinlock_acquire(uint32_t *lock)
{
uint32_t status;
while (1) {
/* Test: Spin on plain load until lock appears free.
* Plain LDR is cache-friendly and doesn't mark exclusive. */
while (*(volatile uint32_t *) lock != 0)
; /* Spin - on single-core this yields naturally at tick */
/* Test-and-Set: Try to acquire with exclusive access */
__asm__ __volatile__(
"ldrex r0, [%[lock]]\n"
"cmp r0, #0\n"
"bne 2f\n" /* If locked (lost race), fail */
"mov r0, #1\n"
"strex %[status], r0, [%[lock]]\n"
"b 3f\n"
"2: mov %[status], #1\n" /* Mark as failed */
"3:\n"
: [status] "=&r"(status)
: [lock] "r"(lock)
: "r0", "cc", "memory");
if (status == 0) {
__asm__ __volatile__("dmb" ::: "memory"); /* Acquire */
return;
}
/* STREX failed or lock was taken between test and TAS - retry */
}
}
/* Spinlock release */
__USER_TEXT
static void spinlock_release(uint32_t *lock)
{
__asm__ __volatile__("dmb" ::: "memory"); /* Release barrier */
*lock = 0;
}
/* Thread attribute functions */
__USER_TEXT
int pthread_attr_init(pthread_attr_t *attr)
{
if (!attr)
return EINVAL;
attr->priority = 128; /* Default priority */
attr->stack_size = 512; /* Default stack (512 bytes) */
attr->detachstate = PTHREAD_CREATE_JOINABLE;
return 0;
}
__USER_TEXT
int pthread_attr_destroy(pthread_attr_t *attr)
{
if (!attr)
return EINVAL;
return 0;
}
__USER_TEXT
int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate)
{
if (!attr || (detachstate != PTHREAD_CREATE_DETACHED &&
detachstate != PTHREAD_CREATE_JOINABLE))
return EINVAL;
attr->detachstate = detachstate;
return 0;
}
__USER_TEXT
int pthread_attr_getdetachstate(const pthread_attr_t *attr, int *detachstate)
{
if (!attr || !detachstate)
return EINVAL;
*detachstate = attr->detachstate;
return 0;
}
__USER_TEXT
int pthread_attr_setstacksize(pthread_attr_t *attr, uint32_t stacksize)
{
if (!attr || stacksize < 256)
return EINVAL;
attr->stack_size = stacksize;
return 0;
}
__USER_TEXT
int pthread_attr_getstacksize(const pthread_attr_t *attr, uint32_t *stacksize)
{
if (!attr || !stacksize)
return EINVAL;
*stacksize = attr->stack_size;
return 0;
}
/* Forward declarations for thread_ptr table functions */
static int register_thread_ptr(pthread_t *thread);
static pthread_t *get_current_thread_ptr(void);
static void unregister_thread_ptr(void);
static void *get_utcb_for_thread(pthread_t *thread);
/* Pending early cancel table.
* Tracks pthread_t* that were cancelled before the child registered its TID.
* When the child registers, it checks this table and applies pending cancels.
*/
#define PENDING_CANCEL_SIZE 8
__USER_BSS static pthread_t *pending_cancel[PENDING_CANCEL_SIZE];
__USER_BSS static uint32_t pending_cancel_lock;
/* Global spinlock for mutex lazy initialization (PTHREAD_MUTEX_INITIALIZER).
* Protects check-then-initialize to prevent race between concurrent threads.
*/
__USER_BSS static uint32_t mutex_lazy_init_lock;
/* Add a pending early cancel for a pthread_t* (when child hasn't registered).
* Returns 0 on success, EAGAIN if table is full.
*/
__USER_TEXT
static int add_pending_cancel(pthread_t *thread)
{
int result = EAGAIN; /* Assume full until we find a slot */
spinlock_acquire(&pending_cancel_lock);
for (int i = 0; i < PENDING_CANCEL_SIZE; i++) {
if ((uintptr_t) pending_cancel[i] == 0) {
pending_cancel[i] = thread;
result = 0;
break;
}
}
spinlock_release(&pending_cancel_lock);
return result;
}
/* Check and consume pending early cancel for a pthread_t* */
__USER_TEXT
static int consume_pending_cancel(pthread_t *thread)
{
int found = 0;
spinlock_acquire(&pending_cancel_lock);
for (int i = 0; i < PENDING_CANCEL_SIZE; i++) {
if (pending_cancel[i] == thread) {
pending_cancel[i] = (pthread_t *) 0;
found = 1;
break;
}
}
spinlock_release(&pending_cancel_lock);
return found;
}
/* Forward declaration for set_cancel_pending (defined later) */
static int set_cancel_pending(pthread_t *thread);
/* Thread wrapper function.
* This wrapper receives pthread_t* as arg, registers the actual global ID
* in a translation table, then calls the user's entry function.
*/
__USER_TEXT
static void *pthread_entry_wrapper(void *wrapper_arg)
{
pthread_t *thread = (pthread_t *) wrapper_arg;
/* Register this thread's pthread_t* using UTCB address as key.
* This allows other code to find our pthread_t* without relying
* on the problematic t_globalid (which reads as 0 initially).
*/
register_thread_ptr(thread);
thread->state = PTHREAD_STATE_RUNNING;
/* Check for early cancel: if pthread_cancel was called before we
* registered, consume the pending cancel and apply it now.
*/
if (consume_pending_cancel(thread)) {
set_cancel_pending(thread);
}
/* Call the actual user function */
void *result = thread->entry(thread->arg);
/* Clean up cancel state before unregistering to prevent table leaks */
__cancel_thread_cleanup(thread);
/* Unregister on normal return */
unregister_thread_ptr();
return result;
}
/* Thread management functions */
__USER_TEXT
int pthread_create(pthread_t *thread,
const pthread_attr_t *attr,
void *(*start_routine)(void *),
void *arg)
{
if (!thread || !start_routine)
return EINVAL;
/* Create L4 thread via pager. */
L4_ThreadId_t tid = pager_create_thread();
if (tid.raw == 0)
return EAGAIN;
/* Initialize pthread structure.
* Store entry and arg for the wrapper to use.
* tid will be updated by the child to its actual global ID.
*/
thread->tid = tid; /* Placeholder, updated by child */
thread->entry = start_routine;
thread->arg = arg;
thread->retval = NULL;
thread->detached = attr ? attr->detachstate : PTHREAD_CREATE_JOINABLE;
thread->joined = 0;
thread->state = PTHREAD_STATE_CREATED;
thread->creator.raw = 0; /* Will be set by child */
/* Start thread execution via wrapper that updates tid.
* Pass pthread_t* as arg to the wrapper.
*/
pager_start_thread(tid, pthread_entry_wrapper, thread);
return 0;
}
__USER_TEXT
void pthread_exit(void *retval)
{
/* Get current thread's pthread_t* for cleanup */
pthread_t *self = get_current_thread_ptr();
if (self) {
self->state = PTHREAD_STATE_EXITED;
}
/* Clean up per-thread signal state to recycle slot.
* Note: signal cleanup still uses TID, but we try to get it safely.
*/
L4_ThreadId_t tid = L4_MyGlobalId();
__signal_thread_cleanup(tid);
/* Clean up per-thread cancellation state to recycle slot */
if (self) {
__cancel_thread_cleanup(self);
}
/* Unregister thread_ptr table entry */
unregister_thread_ptr();
/* Send exit notification to pager using same protocol as thread_container.
* This ensures joiners are woken and thread node is properly released.
*/
L4_Msg_t msg;
L4_MsgClear(&msg);
L4_Set_Label(&msg.tag, PAGER_REQUEST_LABEL);
L4_MsgAppendWord(&msg, THREAD_FREE);
L4_MsgAppendWord(&msg, (L4_Word_t) retval);
L4_MsgLoad(&msg);
L4_Send(L4_Pager());
/* Thread will be terminated by pager - halt forever */
while (1)
L4_Sleep(L4_Never);
}
__USER_TEXT
int pthread_join(pthread_t *thread, void **retval)
{
if (!thread)
return EINVAL;
if (thread->detached)
return EINVAL;
if (thread->joined)
return EINVAL;
/* Block until thread exits using IPC-based synchronization.
* This is RTOS-safe: no spinning, no arbitrary delays.
* The pager will wake us when the target thread calls THREAD_FREE.
*/
int ret = pager_thread_join(thread->tid, retval);
/* Only mark as joined on success, allowing retry on failure */
if (ret == 0)
thread->joined = 1;
return ret;
}
__USER_TEXT
int pthread_detach(pthread_t *thread)
{
if (!thread)
return EINVAL;
if (thread->detached)
return EINVAL;
thread->detached = 1;
/* Notify pager so it can release thread node on exit */
pager_thread_detach(thread->tid);
return 0;
}
__USER_TEXT
pthread_t pthread_self(void)
{
pthread_t self;
self.tid = L4_MyGlobalId();
self.creator = L4_nilthread;
self.entry = NULL;
self.arg = NULL;
self.retval = NULL;
self.detached = 0;
self.joined = 0;
self.state = PTHREAD_STATE_RUNNING;
return self;
}
__USER_TEXT
int pthread_equal(pthread_t t1, pthread_t t2)
{
return (t1.tid.raw == t2.tid.raw);
}
/* ============================================================
* Thread Cancellation (PSE51 POSIX_THREADS_BASE)
*
* Only deferred cancellation is supported. Asynchronous cancellation
* is hazardous in real-time systems (can leave locks held, data
* structures inconsistent) and is explicitly not implemented.
*
* Cancellation points: pthread_testcancel(), pthread_cond_wait(),
* pthread_cond_timedwait(), sem_wait(), nanosleep().
* ============================================================ */
/* Maximum threads for per-thread cancellation state */
#define CANCEL_MAX_THREADS 16
/* Per-thread cancellation state structure
* Uses UTCB address as key for lookup. This works for:
* - Child threads created via pthread_create (have UTCB registered)
* - Main/root thread (has valid current_utcb but no pthread_t*)
*/
struct thread_cancel_state {
void *utcb_addr; /* UTCB address for matching */
pthread_t *thread_ptr; /* Optional pthread_t* (for cleanup) */
uint8_t cancel_state; /* PTHREAD_CANCEL_ENABLE/DISABLE */
uint8_t cancel_type; /* PTHREAD_CANCEL_DEFERRED only */
uint8_t cancel_pending; /* Cancellation requested */
};
/* Per-thread cancellation state table */
__USER_BSS static struct thread_cancel_state cancel_table[CANCEL_MAX_THREADS];
/* Spinlock protecting cancel table */
__USER_BSS static uint32_t cancel_table_lock;
/* Per-thread pthread_t pointer table (indexed by UTCB address for uniqueness).
* This allows threads to find their pthread_t* without relying on t_globalid.
*/
#define THREAD_PTR_TABLE_SIZE 16
struct thread_ptr_entry {
void *utcb_addr; /* UTCB address as unique key */
pthread_t *thread_ptr; /* Associated pthread_t* */
};
__USER_BSS static struct thread_ptr_entry
thread_ptr_table[THREAD_PTR_TABLE_SIZE];
__USER_BSS static uint32_t thread_ptr_lock;
/* Register pthread_t* by UTCB address (called by pthread_entry_wrapper).
* Returns 0 on success, -1 if thread_ptr_table is full.
* When table is full, pthread_cancel and get_current_thread_ptr will fail.
*/
__USER_TEXT
static int register_thread_ptr(pthread_t *thread)
{
extern void *current_utcb;
int result = -1; /* Assume full until we find a slot */
spinlock_acquire(&thread_ptr_lock);
for (int i = 0; i < THREAD_PTR_TABLE_SIZE; i++) {
if (thread_ptr_table[i].utcb_addr == (void *) 0) {
thread_ptr_table[i].utcb_addr = current_utcb;
thread_ptr_table[i].thread_ptr = thread;
result = 0;
break;
}
}
spinlock_release(&thread_ptr_lock);
if (result < 0) {
/* Table full - log warning. Thread will still run but cancel won't
* work.
*/
printf(
"[POSIX] WARNING: thread_ptr_table full, pthread_cancel "
"disabled\n");
}
return result;
}
/* Get current thread's pthread_t* (uses UTCB address as key) */
__USER_TEXT
static pthread_t *get_current_thread_ptr(void)
{
extern void *current_utcb;
pthread_t *result = NULL;
spinlock_acquire(&thread_ptr_lock);
for (int i = 0; i < THREAD_PTR_TABLE_SIZE; i++) {
if (thread_ptr_table[i].utcb_addr == current_utcb) {
result = thread_ptr_table[i].thread_ptr;
break;
}
}
spinlock_release(&thread_ptr_lock);
return result;
}
/* Unregister pthread_t* (called on thread exit) */
__USER_TEXT
static void unregister_thread_ptr(void)
{
extern void *current_utcb;
spinlock_acquire(&thread_ptr_lock);
for (int i = 0; i < THREAD_PTR_TABLE_SIZE; i++) {
if (thread_ptr_table[i].utcb_addr == current_utcb) {
thread_ptr_table[i].utcb_addr = NULL;
thread_ptr_table[i].thread_ptr = NULL;
break;
}
}
spinlock_release(&thread_ptr_lock);
}
/* Get UTCB address for a pthread_t* (reverse lookup in thread_ptr_table) */
__USER_TEXT
static void *get_utcb_for_thread(pthread_t *thread)
{
void *utcb = NULL;
spinlock_acquire(&thread_ptr_lock);
for (int i = 0; i < THREAD_PTR_TABLE_SIZE; i++) {
if (thread_ptr_table[i].thread_ptr == thread) {
utcb = thread_ptr_table[i].utcb_addr;
break;
}
}
spinlock_release(&thread_ptr_lock);
return utcb;
}
/* Find or create cancellation state for current thread.
* Uses UTCB address as key, works for both child threads and main thread.
*/
__USER_TEXT
static struct thread_cancel_state *get_cancel_state(void)
{
extern void *current_utcb;
void *my_utcb = current_utcb;
if (!my_utcb)
return NULL;
int free_slot = -1;
spinlock_acquire(&cancel_table_lock);
for (int i = 0; i < CANCEL_MAX_THREADS; i++) {
if (cancel_table[i].utcb_addr == my_utcb) {
spinlock_release(&cancel_table_lock);
return &cancel_table[i];
}
if (free_slot < 0 && cancel_table[i].utcb_addr == (void *) 0)
free_slot = i;
}
/* Create new entry with defaults */
if (free_slot >= 0) {
cancel_table[free_slot].utcb_addr = my_utcb;
cancel_table[free_slot].thread_ptr = get_current_thread_ptr();
cancel_table[free_slot].cancel_state = PTHREAD_CANCEL_ENABLE;
cancel_table[free_slot].cancel_type = PTHREAD_CANCEL_DEFERRED;
cancel_table[free_slot].cancel_pending = 0;
spinlock_release(&cancel_table_lock);
return &cancel_table[free_slot];
}
spinlock_release(&cancel_table_lock);
return NULL; /* Table full */
}
/* Set pending cancellation for a thread (called by pthread_cancel).
* Uses UTCB address as key.
* Returns:
* 0 - Success
* ESRCH - Thread not registered yet (valid for early cancel)
* EAGAIN - Cancel table full (resource exhaustion)
*/
__USER_TEXT
static int set_cancel_pending(pthread_t *thread)
{
/* Look up target thread's UTCB address */
void *target_utcb = get_utcb_for_thread(thread);
if (!target_utcb)
return ESRCH; /* Thread not registered yet - early cancel case */
int free_slot = -1;
spinlock_acquire(&cancel_table_lock);
for (int i = 0; i < CANCEL_MAX_THREADS; i++) {
if (cancel_table[i].utcb_addr == target_utcb) {
/* Use atomic store for visibility to target thread */
__atomic_store_n(&cancel_table[i].cancel_pending, 1,
__ATOMIC_RELEASE);
spinlock_release(&cancel_table_lock);
return 0;
}
if (free_slot < 0 && cancel_table[i].utcb_addr == (void *) 0)
free_slot = i;
}
/* Create entry for thread that hasn't initialized cancel state */
if (free_slot >= 0) {
cancel_table[free_slot].utcb_addr = target_utcb;
cancel_table[free_slot].thread_ptr = thread;
cancel_table[free_slot].cancel_state = PTHREAD_CANCEL_ENABLE;
cancel_table[free_slot].cancel_type = PTHREAD_CANCEL_DEFERRED;
__atomic_store_n(&cancel_table[free_slot].cancel_pending, 1,
__ATOMIC_RELEASE);
spinlock_release(&cancel_table_lock);
return 0;
}
spinlock_release(&cancel_table_lock);
return EAGAIN; /* Table full */
}
/* Clean up cancellation state when thread exits.
* Uses UTCB address lookup from thread_ptr to find the entry.
*/
__USER_TEXT
void __cancel_thread_cleanup(pthread_t *thread)
{
void *target_utcb = get_utcb_for_thread(thread);
spinlock_acquire(&cancel_table_lock);
for (int i = 0; i < CANCEL_MAX_THREADS; i++) {
/* Match by UTCB if available, or by thread_ptr as fallback */
if ((target_utcb && cancel_table[i].utcb_addr == target_utcb) ||
(!target_utcb && cancel_table[i].thread_ptr == thread)) {
cancel_table[i].utcb_addr = NULL;
cancel_table[i].thread_ptr = NULL;
cancel_table[i].cancel_state = 0;
cancel_table[i].cancel_type = 0;
cancel_table[i].cancel_pending = 0;
break;
}
}
spinlock_release(&cancel_table_lock);
}
__USER_TEXT
int pthread_cancel(pthread_t *thread)
{
if (!thread)
return EINVAL;
/* Check if thread already exited */
if (thread->joined || thread->state == PTHREAD_STATE_EXITED) {
return ESRCH;
}
/* Try to set cancel pending directly using pthread_t*.
* If thread hasn't registered yet (ESRCH), queue for early cancel.
* If cancel table is full (EAGAIN), report the error.
*/
int result = set_cancel_pending(thread);
if (result == ESRCH) {
/* Thread not registered yet - queue for early cancel.
* The wrapper will apply it when the thread starts.
*/
if (thread->state == PTHREAD_STATE_CREATED) {
return add_pending_cancel(thread);
}
return ESRCH;
}
return result;
}
__USER_TEXT
int pthread_setcancelstate(int state, int *oldstate)
{
if (state != PTHREAD_CANCEL_ENABLE && state != PTHREAD_CANCEL_DISABLE)
return EINVAL;
struct thread_cancel_state *cs = get_cancel_state();
if (!cs)
return EAGAIN;
if (oldstate)
*oldstate = cs->cancel_state;
cs->cancel_state = state;
return 0;
}
__USER_TEXT
int pthread_setcanceltype(int type, int *oldtype)
{
/* Only deferred cancellation is supported.
* Asynchronous cancellation is hazardous in RT systems.
*/
if (type != PTHREAD_CANCEL_DEFERRED) {
if (type == PTHREAD_CANCEL_ASYNCHRONOUS)
return ENOTSUP; /* Explicitly not supported */
return EINVAL;
}
struct thread_cancel_state *cs = get_cancel_state();
if (!cs)
return EAGAIN;
if (oldtype)
*oldtype = cs->cancel_type;
cs->cancel_type = type;
return 0;
}
__USER_TEXT
void pthread_testcancel(void)
{
struct thread_cancel_state *cs = get_cancel_state();
if (!cs)
return;
/* Check if cancellation is pending and enabled.
* Use atomic load for visibility from pthread_cancel in other thread.
*/
if (__atomic_load_n(&cs->cancel_pending, __ATOMIC_ACQUIRE) &&
cs->cancel_state == PTHREAD_CANCEL_ENABLE) {
/* Clean up cancel state before exiting */
__cancel_thread_cleanup(cs->thread_ptr);
pthread_exit(PTHREAD_CANCELED);
}
}
/* Mutex attribute functions */
__USER_TEXT
int pthread_mutexattr_init(pthread_mutexattr_t *attr)
{
if (!attr)
return EINVAL;
attr->type = PTHREAD_MUTEX_NORMAL;
attr->initialized = 1;
return 0;
}
__USER_TEXT
int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
{
if (!attr || !attr->initialized)
return EINVAL;
attr->initialized = 0;
return 0;
}
__USER_TEXT
int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
{
if (!attr || !attr->initialized)
return EINVAL;
if (type != PTHREAD_MUTEX_NORMAL && type != PTHREAD_MUTEX_RECURSIVE)
return EINVAL;
attr->type = type;
return 0;
}
__USER_TEXT
int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type)
{
if (!attr || !type || !attr->initialized)
return EINVAL;
*type = attr->type;
return 0;
}
/* Mutex management functions */
/* Mutex waiter list helpers (spinlock-protected) */
/* Add current thread to mutex waiter list. Returns 0 on success, -1 if full. */
__USER_TEXT
static int mutex_waiter_add(pthread_mutex_t *m, L4_ThreadId_t tid)
{
spinlock_acquire(&m->waiters_lock);
if (m->num_waiters >= MUTEX_MAX_WAITERS) {
spinlock_release(&m->waiters_lock);
return -1; /* List full */
}
m->waiters[m->num_waiters] = tid;
m->num_waiters++;
spinlock_release(&m->waiters_lock);
return 0;
}
/* Remove a specific thread from mutex waiter list. */
__USER_TEXT
static void mutex_waiter_remove(pthread_mutex_t *m, L4_ThreadId_t tid)
{
spinlock_acquire(&m->waiters_lock);
for (uint32_t i = 0; i < m->num_waiters; i++) {
if (m->waiters[i].raw == tid.raw) {
/* Shift remaining entries down */
for (uint32_t j = i; j < m->num_waiters - 1; j++)
m->waiters[j] = m->waiters[j + 1];
m->num_waiters--;
break;
}
}
spinlock_release(&m->waiters_lock);
}
/* Pop first waiter from mutex list. Returns nilthread if list empty. */
__USER_TEXT
static L4_ThreadId_t mutex_waiter_pop(pthread_mutex_t *m)
{
L4_ThreadId_t tid = L4_nilthread;
spinlock_acquire(&m->waiters_lock);
if (m->num_waiters > 0) {
tid = m->waiters[0];
/* Shift remaining entries down */
for (uint32_t i = 0; i < m->num_waiters - 1; i++)
m->waiters[i] = m->waiters[i + 1];
m->num_waiters--;
}
spinlock_release(&m->waiters_lock);
return tid;
}
/* Internal: Initialize mutex if using static initializer.
* Uses global spinlock to prevent race between concurrent lazy inits.
*/
__USER_TEXT
static int pthread_mutex_lazy_init(pthread_mutex_t *mutex)
{
/* Fast path: already initialized */
if (mutex->initialized)
return 0;
/* Slow path: check sentinel and initialize under lock.
* Global spinlock prevents TOCTOU race between check and init.
*/
spinlock_acquire(&mutex_lazy_init_lock);
/* Double-check after acquiring lock (another thread may have initialized)
*/
if (mutex->count == PTHREAD_MUTEX_INITIALIZER_MAGIC &&
!mutex->initialized) {
mutex->lock = 0;
mutex->owner.raw = 0;
mutex->type = PTHREAD_MUTEX_NORMAL;
mutex->count = 0;
mutex->waiters_lock = 0;
mutex->num_waiters = 0;
for (int i = 0; i < MUTEX_MAX_WAITERS; i++)
mutex->waiters[i] = L4_nilthread;
/* Memory barrier before setting initialized flag */
__atomic_thread_fence(__ATOMIC_RELEASE);
mutex->initialized = 1;
}
spinlock_release(&mutex_lazy_init_lock);
return mutex->initialized ? 0 : EINVAL;
}
__USER_TEXT
int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr)
{
if (!mutex)
return EINVAL;
/* Validate attr if provided */
if (attr && !attr->initialized)
return EINVAL;
mutex->lock = 0;
mutex->owner.raw = 0;
mutex->type = attr ? attr->type : PTHREAD_MUTEX_NORMAL;
mutex->count = 0;
mutex->waiters_lock = 0;
mutex->num_waiters = 0;
for (int i = 0; i < MUTEX_MAX_WAITERS; i++)
mutex->waiters[i] = L4_nilthread;
mutex->initialized = 1;
return 0;
}
__USER_TEXT
int pthread_mutex_destroy(pthread_mutex_t *mutex)
{
if (!mutex)
return EINVAL;
/* Check if initialized (explicit or via lazy init) */
if (!mutex->initialized)
return EINVAL;
if (mutex->lock)
return EBUSY;
mutex->initialized = 0;
return 0;
}
__USER_TEXT
int pthread_mutex_lock(pthread_mutex_t *mutex)
{
if (!mutex)
return EINVAL;
/* Support PTHREAD_MUTEX_INITIALIZER lazy initialization */
if (!mutex->initialized) {
int ret = pthread_mutex_lazy_init(mutex);
if (ret != 0)
return ret;
}
L4_ThreadId_t self = L4_MyGlobalId();
/* Recursive mutex: allow re-locking by same thread */
if (mutex->type == PTHREAD_MUTEX_RECURSIVE) {
if (mutex->owner.raw == self.raw) {
mutex->count++;
return 0;
}
} else {
/* Deadlock detection for normal mutex */
if (mutex->owner.raw == self.raw)
return EDEADLK;
}
/* Blocking mutex acquisition using direct notifications.
*
* Fast path: Try atomic acquisition for uncontended case.
* Slow path: Register in waiter list and block via L4_NotifyWait.
*
* The retry loop handles:
* 1. Lost wakeups (mutex_unlock before we started waiting)
* 2. Spurious wakeups
* 3. Waiter list full (yield and retry)
*/
while (1) {
/* Fast path: try to acquire with atomic operation */
if (pthread_mutex_trylock(mutex) == 0)
return 0;
/* Slow path: register as waiter and block */
if (mutex_waiter_add(mutex, self) < 0) {
/* Waiter list full - yield and retry */
L4_Yield();
continue;
}
/* Double-check before blocking (unlock may have raced) */
if (pthread_mutex_trylock(mutex) == 0) {
/* Success! Remove ourselves from waiter list */
mutex_waiter_remove(mutex, self);
return 0;
}
/* Block waiting for notification */
L4_NotifyWait(POSIX_NOTIFY_MUTEX_BIT);
/* Woken up - remove self from list and retry */
mutex_waiter_remove(mutex, self);
/* Retry trylock to handle:
* 1. Normal wakeup from mutex_unlock
* 2. Spurious wakeup
* The loop continues until we successfully acquire
*/
}
}
__USER_TEXT
int pthread_mutex_trylock(pthread_mutex_t *mutex)
{
if (!mutex)
return EINVAL;
/* Support PTHREAD_MUTEX_INITIALIZER lazy initialization */
if (!mutex->initialized) {
int ret = pthread_mutex_lazy_init(mutex);
if (ret != 0)
return ret;
}
register int result = 1;
L4_ThreadId_t self = L4_MyGlobalId();
/* Recursive mutex: allow re-locking */
if (mutex->type == PTHREAD_MUTEX_RECURSIVE) {
if (mutex->owner.raw == self.raw) {
mutex->count++;
return 0;
}
}
/* ARM LDREX/STREX atomic operation with acquire barrier.
* Use ITE (If-Then-Else) to always write result:
* - If lock==0: STREX stores 1, r0 gets STREX result (0=success, 1=fail)
* - If lock!=0: r0 gets 1 (failure, mutex was locked)
*
* DMB ISH after successful lock provides acquire semantics:
* critical section memory accesses won't be reordered before lock.
*/
__asm__ __volatile__(
"mov r1, #1\n"
"mov r2, %[mutex]\n"
"ldrex r0, [r2]\n" /* Load exclusive: r0 = lock value */
"cmp r0, #0\n" /* Check if unlocked */
"ite eq\n" /* If-Then-Else block */
"strexeq r0, r1, [r2]\n" /* Then: store 1 if unlocked, r0=STREX result
*/
"movne r0, #1\n" /* Else: set r0=1 (already locked) */
"cmp r0, #0\n" /* Check if we acquired the lock */
"it eq\n"
"dmbeq\n" /* Acquire barrier on success */
"mov %[result], r0\n" /* Always store result */
: [result] "=r"(result)
: [mutex] "r"(&mutex->lock)
: "r0", "r1", "r2", "cc", "memory");
if (result == 0) {
mutex->owner = self;
mutex->count = 1;
}
return result ? EBUSY : 0;
}
__USER_TEXT
int pthread_mutex_unlock(pthread_mutex_t *mutex)
{
if (!mutex)