-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlgc.c
More file actions
2375 lines (2025 loc) · 63.5 KB
/
lgc.c
File metadata and controls
2375 lines (2025 loc) · 63.5 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
/*
** $Id: lgc.c,v 2.38.1.1 2007/12/27 13:02:25 roberto Exp $
** Garbage Collector
** See Copyright Notice in lua.h
*/
#define lgc_c
#define LUA_CORE
#include "thrlua.h"
#if USING_DRD
# define INLINE /* not inline */
#else
# define INLINE inline
#endif
/* Perform global traces in parallel, as opposed to having just one thread
* do it. Set to 0 to disable. */
static int USE_TRACE_THREADS = 1;
/* Number of trace threads to use. Start with 8, requires USE_TRACE_THREADS
* to be set to 1. */
static int NUM_TRACE_THREADS = 8;
/* Non-signal collector logic. Set to 0 to disable.*/
static int NON_SIGNAL_COLLECTOR = 1;
/* TR-1945: Maximum amount of time (in milliseconds) that global trace should
* should wait for the "all threads" lock before giving up.
* A value <= 0 means no wait -- just give up if the lock can't
* be acquired immediately.
*/
static int GLOBAL_TRACE_ALL_THREADS_WAIT_MS = 500; /* Default set, TR-1959 */
/* TR-1945: In order to trigger lock contention between global trace
* and thread inheritance, set this to e.g.: 1. Don't do this in production.
*/
static int TEST_INHERIT_THREAD_DELAY_MS = 0; /* off by default */
/* Maximum amount of time (in milliseconds) a global trace thread should
* wait for mutators to get out of a write barrier before assuming a deadlock
* has occurred. Settable only on restart via environment variable
* 'LUA_BLOCK_MUTATORS_MAX_WAIT_MS'.
* A value of -1 indicates that the global trace thread should wait indefinitely.
*/
static int BLOCK_MUTATORS_MAX_WAIT_MS = 10000;
/* Amount of time (in milliseconds) a global trace thread should
* wait between reattempts of try_block_mutators().
* Settable only on restart via environment variable
* 'LUA_BLOCK_MUTATORS_RETRY_WAIT_MS'.
*/
static int BLOCK_MUTATORS_RETRY_WAIT_MS = 100;
#ifdef LUA_OS_LINUX
# define DEF_LUA_SIG_SUSPEND SIGPWR
# define DEF_LUA_SIG_RESUME SIGXCPU
#elif defined(LUA_OS_DARWIN)
# define DEF_LUA_SIG_SUSPEND SIGINFO
# define DEF_LUA_SIG_RESUME SIGXCPU
#else
# define DEF_LUA_SIG_SUSPEND SIGUSR1
# define DEF_LUA_SIG_RESUME SIGUSR2
#endif
static int LUA_SIG_SUSPEND = DEF_LUA_SIG_SUSPEND;
static int LUA_SIG_RESUME = DEF_LUA_SIG_RESUME;
static pthread_once_t tls_init = PTHREAD_ONCE_INIT;
pthread_key_t lua_tls_key;
/* we use these to track the threads so that we can stop the world */
static pthread_mutex_t all_threads_lock; /* initialized via pthread_once */
static uint32_t num_threads = 0;
static uint32_t parked_threads = 0;
static TAILQ_HEAD(thr_StateList, thr_State)
all_threads = TAILQ_HEAD_INITIALIZER(all_threads);
static sigset_t suspend_handler_mask;
static struct ck_stack trace_stack;
static pthread_cond_t trace_cond;
static pthread_mutex_t trace_mtx;
/* This lock is used to synchronize threads trying to enter a barrier
* in the NON_SIGNAL_COLLECTOR case. This is only used to signal threads
* trying to block the collector while a global trace is going on. The reason
* we don't use this in the general case (and use the in_barrier/intend_to_stop
* logic) is because this codepath is very hot, and using the rwlock as the
* primary method of synchronization would be more expensive. So we will
* use the intend_to_stop/in_barrier method in normal circumstances, but to avoid
* busy waiting on the intend_to_stop test we will use sleep the threads on
* the rwlock. */
static pthread_rwlock_t trace_rwlock;
static void *trace_thread(void *);
static void trace_heap(GCheap *h);
static uint32_t trace_heaps = 0;
#define BLACKBIT (1<<0)
#define WEAKKEYBIT (1<<1)
#define WEAKVALBIT (1<<2)
#define GREYBIT (1<<3)
#define FINALBIT (1<<4)
#define FREEDBIT (1<<7)
static int local_collection(lua_State *L, int type);
static int global_trace(lua_State *L);
static void unblock_mutators(lua_State *L);
static INLINE int is_black(lua_State *L, GCheader *obj)
{
return ((obj->marked & BLACKBIT) == L->black);
}
static INLINE int is_grey(GCheader *obj)
{
return obj->marked & GREYBIT;
}
static INLINE int is_finalized(GCheader *obj)
{
return obj->marked & FINALBIT;
}
static INLINE int is_aggregate(GCheader *obj)
{
return obj->tt != LUA_TSTRING;
}
static INLINE int is_free(GCheader *obj)
{
return obj->marked & FREEDBIT;
}
/** defines GCheap_from_stack to convert a stack entry to a GCheap */
CK_STACK_CONTAINER(GCheap, instack, GCheap_from_stack);
/** defines GCheader_from_stack to convert a stack entry to a
* GCheader */
CK_STACK_CONTAINER(GCheader, instack, GCheader_from_stack);
/** defines GCheader_from_stack_finalize to convert a to finalize
* stack entry to a GCHeader */
CK_STACK_CONTAINER(GCheader, finalize_instack, GCheader_from_stack_finalize);
static GCheader *pop_obj(ck_stack_t *stack)
{
ck_stack_entry_t *ent = ck_stack_pop_npsc(stack);
GCheader *o;
if (!ent) return NULL;
o = GCheader_from_stack(ent);
lua_assert(&o->instack == ent);
ent->next = NULL;
return o;
}
static GCheader *pop_finalize(ck_stack_t *stack)
{
ck_stack_entry_t *ent = ck_stack_pop_npsc(stack);
GCheader *o;
if (!ent) return NULL;
o = GCheader_from_stack_finalize(ent);
lua_assert(&o->finalize_instack == ent);
ent->next = NULL;
return o;
}
static void push_obj(ck_stack_t *stack, GCheader *o)
{
#if DEBUG_ALLOC
if (o->instack.next) {
VALGRIND_PRINTF_BACKTRACE(
"push stack=%p obj=%p ALREADY IN A STACK!\n", stack, o);
}
#endif
lua_assert_obj(o->instack.next == NULL, o);
#if DEBUG_ALLOC
VALGRIND_PRINTF_BACKTRACE("push stack=%p obj=%p\n", stack, o);
#endif
ck_stack_push_spnc(stack, &o->instack);
}
static void push_finalize(ck_stack_t *stack, GCheader *o)
{
#if DEBUG_ALLOC
if (o->finalize_instack.next) {
VALGRIND_PRINTF_BACKTRACE(
"push stack=%p obj=%p ALREADY IN A STACK!\n", stack, o);
}
#endif
lua_assert_obj(o->finalize_instack.next == NULL, o);
#if DEBUG_ALLOC
VALGRIND_PRINTF_BACKTRACE("push stack=%p obj=%p\n", stack, o);
#endif
ck_stack_push_spnc(stack, &o->finalize_instack);
}
static void removeentry(Node *n)
{
lua_assert(ttisnil(gval(n)));
if (iscollectable(gkey(n)))
setttype(key2tval(n), LUA_TDEADKEY); /* dead key; remove it */
}
static INLINE int is_unknown_xref_val(lua_State *L, uint32_t val)
{
if ((ck_pr_load_32(&G(L)->isxref) & 3) == 1) {
return (val & 2) == 2;
}
return (val & 2) == 0;
}
static INLINE int is_unknown_xref(lua_State *L, GCheader *o) {
uint32_t val = ck_pr_load_32(&o->xref);
return is_unknown_xref_val(L, val);
}
static INLINE int is_not_xref(lua_State *L, GCheader *o)
{
return ck_pr_load_32(&o->xref) == ck_pr_load_32(&G(L)->notxref);
}
static INLINE void set_xref(lua_State *L, GCheader *lval, GCheader *rval,
int force)
{
if (lval->owner != rval->owner) {
ck_pr_store_32(&rval->xref, ck_pr_load_32(&G(L)->isxref));
} else if (force) {
uint32_t old_val = ck_pr_load_32(&rval->xref);
if (is_unknown_xref_val(L, old_val)) {
/* Here's the issue: There may be another thread marking this as an xref,
* and if we mark it as _not_ an xref at the same time, we're gonna have
* a bad time. So, we:
*
* 1. Load the value and save it locally.
* 2. Check if it's unknown.
* 3. If it's unknown, we run atomic CAS to compare it against the old
* value and make it 'not' xref. If somebody else changed it (either to
* not an xref, or an xref), that's cool.
*/
ck_pr_cas_32(&rval->xref, old_val, ck_pr_load_32(&G(L)->notxref));
}
}
}
static INLINE void make_grey(lua_State *L, GCheader *obj)
{
lua_assert_obj(obj->owner == L->heap, obj);
if ((obj->marked & GREYBIT) == GREYBIT) return;
obj->marked |= GREYBIT;
push_obj(&L->heap->grey, obj);
}
static INLINE void make_black(lua_State *L, GCheader *obj)
{
obj->marked = (obj->marked & ~(GREYBIT|BLACKBIT)) | L->black;
}
static INLINE void mark_object(lua_State *L, GCheader *obj)
{
register int m;
if (L->heap != obj->owner) {
/* external reference */
ck_pr_store_32(&obj->xref, ck_pr_load_32(&G(L)->isxref));
return;
}
lua_assert_obj(!is_free(obj), obj);
lua_assert_obj(obj->owner == L->heap, obj);
m = obj->marked;
if ((m & GREYBIT) || ((m & BLACKBIT) == L->black)) {
/** already marked */
return;
}
if (is_aggregate(obj)) {
make_grey(L, obj);
} else {
make_black(L, obj);
}
}
typedef void (*objfunc_t)(lua_State *, GCheader *, GCheader *);
static void traverse_object(lua_State *L, GCheader *o, objfunc_t objfunc);
static INLINE void traverse_obj(lua_State *L, GCheader *obj, GCheader *rval,
objfunc_t objfunc)
{
objfunc(L, obj, rval);
}
static INLINE void traverse_value(lua_State *L, GCheader *obj, TValue *val,
objfunc_t objfunc)
{
checkconsistency(val);
if (iscollectable(val)) {
traverse_obj(L, obj, gcvalue(val), objfunc);
}
}
static void sub_times(struct timeval a, struct timeval b,
struct timeval *result)
{
result->tv_usec = a.tv_usec - b.tv_usec;
if (result->tv_usec < 0L) {
a.tv_sec--;
result->tv_usec += 1000000L;
}
result->tv_sec = a.tv_sec - b.tv_sec;
if (result->tv_sec < 0L) {
result->tv_sec++;
result->tv_usec -= 1000000L;
}
}
static double interval_in_msecs(struct timeval start_time,
struct timeval end_time)
{
double time_ms = 0;
struct timeval diff;
sub_times(end_time, start_time, &diff);
time_ms = diff.tv_sec * 1000 + diff.tv_usec / 1000;
return time_ms;
}
/* Returns 1 on success.
Returns 0 if a potential deadlock is detected
*/
static INLINE int try_block_mutators(lua_State *L)
{
uint32_t pending;
thr_State *pt;
int *recursion = get_recursion();
/* For the non-signal thread stoppage, take a write lock. Important that
* we do this before setting intend to stop, as we acquire the write
* lock after the test for intend_to_stop. This doesn't actually mean
* we are yet safe to start the global trace, as when mutators are blocked
* the in_barrier test is the way we know somebody is writing. This is done
* to avoid extra system calls on this lock in the case when the global
* trace is not running. When we release the lock, that allows any threads
* blocking on the lock to acquire a read lock. They will immediately
* release the lock and ensure intend_to_stop is set to 0 _after_ they
* set their in_barirer flag to 1. */
if (NON_SIGNAL_COLLECTOR) {
pthread_rwlock_wrlock(&trace_rwlock);
}
(*recursion)++;
/* advertise our intent to stop everyone; this prevents any mutators
* from returning from their respective barriers */
ck_pr_store_32(&G(L)->intend_to_stop, 1);
ck_pr_fence_memory();
/* don't leave until we know that all threads are outside a barrier.
* No more threads will enter a barrier after this point because
* intend_to_stop is set to 1. */
gettimeofday(&G(L)->mutator_wait_start, NULL);
while (1) {
pending = 0;
TAILQ_FOREACH(pt, &all_threads, threads) {
if (pt->dead) {
continue;
}
if (ck_pr_load_32(&pt->in_barrier) == 1) {
pending++;
}
} /* end foreach thread */
if (!pending) {
gettimeofday(&G(L)->mutator_wait_end, NULL);
return 1;
}
if (BLOCK_MUTATORS_MAX_WAIT_MS > 0) {
gettimeofday(&G(L)->mutator_wait_end, NULL);
if (interval_in_msecs(G(L)->mutator_wait_start,
G(L)->mutator_wait_end) > BLOCK_MUTATORS_MAX_WAIT_MS) {
/* we might be in a deadlock (TR-273) */
unblock_mutators(L);
thrlua_log(L, DERROR, "thrlua: global trace waited for %d msecs but %lu "
"threads are still in a write barrier; restarting global trace in %d msecs\n",
BLOCK_MUTATORS_MAX_WAIT_MS, (unsigned long)pending, BLOCK_MUTATORS_RETRY_WAIT_MS);
return 0;
}
}
/* continue waiting */
ck_pr_stall();
} /* end while(1) */
}
static INLINE void unblock_mutators(lua_State *L)
{
int *recursion = get_recursion();
(*recursion)--;
ck_pr_store_32(&G(L)->intend_to_stop, 0);
ck_pr_fence_memory();
/* For the non-signal collector, release the write lock. This tells
* any threads trying to block the collector that they can now wake
* up and try to enter their write barrier. */
if (NON_SIGNAL_COLLECTOR) {
pthread_rwlock_unlock(&trace_rwlock);
}
}
/* NOTE: This is the alternate logic for stopping threads during a
* global trace. */
/* called during a global trace; when it returns, all mutators will be in
* a safe state that blocks them from mutating state */
static INLINE void block_mutators(lua_State *L)
{
int tries = 1;
while(!try_block_mutators(L)) {
/* try_block_mutators detected a potential deadlock.
* It has already given up trace_rwlock and set intend_to_stop = 0.
* wait and try again (TR-273). */
usleep(1000 * BLOCK_MUTATORS_RETRY_WAIT_MS);
tries++;
}
if (tries > 1) {
/* try_block_mutators had an issue blocking the mutators at least one time
* but now the mutators are blocked. Log an error for tracking purposes. */
thrlua_log(L, DERROR,
"thrlua: global trace successfully blocked mutators after %d tries\n", tries);
}
}
/* Per-thread collector block recursion counter. As it is per-thread we
* don't need to use any threadsafe operators to change or read it */
static pthread_key_t collector_block_recursion_key;
static void free_recursion(void *tofree) {
free(tofree);
}
static int *get_recursion(void) {
int *recursion;
if ((recursion = pthread_getspecific(collector_block_recursion_key)) == NULL) {
recursion = calloc(1, sizeof(*recursion));
pthread_setspecific(collector_block_recursion_key, recursion);
}
return recursion;
}
static INLINE void block_collector(lua_State *L, thr_State *pt)
{
int *recursion = get_recursion();
(*recursion)++;
if (*recursion > 1) {
/* Already blocked, do nothing */
return;
}
for (;;) {
while (ck_pr_load_32(&G(L)->intend_to_stop) == 1) {
if (!NON_SIGNAL_COLLECTOR) {
/* we will get suspended momentarily */
ck_pr_stall();
ck_pr_fence_memory();
} else {
/* We synchronize with the guy trying to trace using the rwlock.
* This replaces the 'stall' loop we were doing earlier which
* can cause a lot of context switching for systems with
* lots of threads. */
while (pthread_rwlock_rdlock(&trace_rwlock) == EAGAIN) ;
/* Now the global trace is done. We are good to unlock and
* proceed. We will double check that we are safely in our
* barrier below. */
pthread_rwlock_unlock(&trace_rwlock);
/* NOTE: This logic used to also act as a trace thread, but
* that's been removed because when there is no tracing to do
* it busy waits until the global trace is done. That extra
* context switching actually slows down the system more than
* necessary, which is why we are usign the rwlock strategy
* intead. */
}
}
/* tell a possible collector that we're in a write barrier */
ck_pr_store_32(&pt->in_barrier, 1);
ck_pr_fence_memory();
if (ck_pr_load_32(&G(L)->intend_to_stop) == 0) {
return;
}
/* Woops, a global trace started after we set the barrier flag,
* clear it out and loop again. */
ck_pr_store_32(&pt->in_barrier, 0);
ck_pr_fence_memory();
}
}
static INLINE void unblock_collector(lua_State *L, thr_State *pt)
{
int *recursion = get_recursion();
(*recursion)--;
if (*recursion != 0) {
/* Another block in play further up the stack, do nothing */
return;
}
ck_pr_store_32(&pt->in_barrier, 0);
ck_pr_fence_memory();
}
void luaC_blockcollector(lua_State *L) {
thr_State *pt = luaC_get_per_thread(L);
block_collector(L, pt);
}
void luaC_unblockcollector(lua_State *L) {
thr_State *pt = luaC_get_per_thread(L);
unblock_collector(L, pt);
}
# define GET_PT_FOR_NON_SIGNAL_COLLECTOR() \
thr_State *pt = luaC_get_per_thread(L)
# define BLOCK_COLLECTOR() do { \
if (NON_SIGNAL_COLLECTOR) { \
block_collector(L, pt); \
} \
} while(0)
# define UNBLOCK_COLLECTOR() do {\
if (NON_SIGNAL_COLLECTOR) { \
unblock_collector(L, pt); \
} \
} while (0)
void luaC_writebarrierxmove(lua_State *L, TValue **lhs,
const TValue *rhs, int num) {
int i;
thr_State *pt = luaC_get_per_thread(L);
// The write barrier will block again, but recursion on collector
// blocks is allowed
block_collector(L, pt);
for (i = 0; i < num; i++) {
setobj2s(L, (*lhs)++, rhs + i);
}
unblock_collector(L, pt);
}
void luaC_writebarrierov(lua_State *L, GCheader *object,
GCheader **lvalue, const TValue *rvalue)
{
GET_PT_FOR_NON_SIGNAL_COLLECTOR();
GCheader *ro = gcvalue(rvalue);
lua_assert(ro != NULL);
checkconsistency(rvalue);
BLOCK_COLLECTOR();
mark_object(L, ro);
set_xref(L, object, ro, 0);
ck_pr_store_ptr(lvalue, ro);
UNBLOCK_COLLECTOR();
}
void luaC_writebarriervo(lua_State *L, GCheader *object,
TValue *lvalue, GCheader *rvalue)
{
thr_State *pt = luaC_get_per_thread(L);
block_collector(L, pt);
set_xref(L, object, rvalue, 0);
mark_object(L, rvalue);
lvalue->value.gc = rvalue;
/* RACE: a global trace can trigger here and catch us pants-down
* wrt ->tt != value->tt; so this section must be protected by blocking
* the collector */
lvalue->tt = rvalue->tt;
unblock_collector(L, pt);
}
void luaC_writebarriervv(lua_State *L, GCheader *object,
TValue *lvalue, const TValue *rvalue)
{
thr_State *pt = luaC_get_per_thread(L);
block_collector(L, pt);
if (iscollectable(rvalue)) {
GCheader *ro = gcvalue(rvalue);
set_xref(L, object, ro, 0);
mark_object(L, ro);
}
lvalue->value = rvalue->value;
/* RACE: a global trace can trigger here and catch us pants-down
* wrt ->tt != value->tt; so this section must be protected by blocking
* the collector */
lvalue->tt = rvalue->tt;
unblock_collector(L, pt);
}
void luaC_writebarrier(lua_State *L, GCheader *object,
GCheader **lvalue, GCheader *rvalue)
{
GET_PT_FOR_NON_SIGNAL_COLLECTOR();
BLOCK_COLLECTOR();
if (rvalue) {
set_xref(L, object, rvalue, 0);
mark_object(L, rvalue);
}
ck_pr_store_ptr(lvalue, rvalue);
UNBLOCK_COLLECTOR();
}
void luaC_writebarrierstr(lua_State *L, unsigned int h,
struct stringtable_node *n) {
stringtable *tb = &L->strt;
thr_State *pt = luaC_get_per_thread(L);
struct stringtable_node **oldhash = NULL;
int oldsize = 0;
h = lmod(h, tb->size);
block_collector(L, pt);
n->next = tb->hash[h]; /* chain new entry */
tb->hash[h] = n;
tb->nuse++;
oldhash = tb->hash;
oldsize = tb->size;
unblock_collector(L, pt);
/* Can't do allocations or frees while blocking the collector */
if (tb->nuse > cast(uint32_t, tb->size) && tb->size <= MAX_INT/2) {
int newsize = tb->size * 2;
struct stringtable_node **newhash =
luaM_realloc(L, LUA_MEM_STRING_TABLE, NULL, 0,
newsize * sizeof(struct stringtable_node *));
/* luaS_resize does no allocations, but it needs the collector blocked */
block_collector(L, pt);
luaS_resize(L, tb, tb->size*2, newhash); /* too crowded */
unblock_collector(L, pt);
if (oldhash && oldsize) {
luaM_realloc(L, LUA_MEM_STRING_TABLE, oldhash,
oldsize * sizeof(struct stringtable_node *), 0);
}
}
}
/* broken out into a function to allow us to suppress it from drd.
* If the world is stopped, we don't need (and in fact, MUST NOT,
* due to risk of deadlock) take locks on items during collection cycles.
*/
static INLINE int is_world_stopped(lua_State *L)
{
return ck_pr_load_32(&G(L)->stopped);
}
/* traverse object must be async-signal safe when G(L)->stopped is true */
static void traverse_object(lua_State *L, GCheader *o, objfunc_t objfunc)
{
int i;
switch (o->tt) {
case LUA_TSTRING:
/* has no contents */
break;
case LUA_TUSERDATA:
{
Udata *ud = rawgco2u(o);
if (ud->uv.metatable) {
traverse_obj(L, o, ud->uv.metatable, objfunc);
}
if (ud->uv.env) {
traverse_obj(L, o, ud->uv.env, objfunc);
}
if (ud->uv.otherref) {
traverse_obj(L, o, ud->uv.otherref, objfunc);
}
break;
}
case LUA_TUPVAL:
{
UpVal *uv = gco2uv(o);
if (!uv->v) {
/* Not done being setup yet, skip */
return;
}
traverse_value(L, o, uv->v, objfunc);
break;
}
case LUA_TTABLE:
{
Table *h = gco2h(o);
int weakkey = 0, weakvalue = 0;
const TValue *mode;
int is_locked = 0;
if (!ck_pr_load_uint(&h->initialized)) {
/* Not done being setup yet, skip */
return;
}
/* Acquire fence: ensure we see all table data after initialized flag */
ck_pr_fence_load();
if (!is_world_stopped(L)) {
luaH_rdlock(L, h);
is_locked = 1;
}
if (h->metatable) {
traverse_obj(L, o, h->metatable, objfunc);
}
o->marked &= ~(WEAKKEYBIT|WEAKVALBIT);
mode = gfasttm(G(L), gch2h(h->metatable), TM_MODE);
if (mode && ttisstring(mode)) {
weakkey = (strchr(svalue(mode), 'k') != NULL);
weakvalue = (strchr(svalue(mode), 'v') != NULL);
if (weakkey) o->marked |= WEAKKEYBIT;
if (weakvalue) o->marked |= WEAKVALBIT;
}
if (!weakvalue) {
i = h->sizearray;
while (i--) {
traverse_value(L, o, &h->array[i], objfunc);
}
}
i = sizenode(h);
while (i--) {
Node *n = gnode(h, i);
lua_assert(ttype(gkey(n)) != LUA_TDEADKEY || ttisnil(gval(n)));
if (ttisnil(gval(n))) {
if (!is_world_stopped(L)) removeentry(n);
} else {
lua_assert(!ttisnil(gkey(n)));
/* These have been temporarily made volatile to prevent the
compiler from optimizing them out to gain more visibility
into the TR-298 crashes (TR-439) */
const char * volatile key_char_ptr = NULL;
TValue * volatile key_value = key2tval(n);
if (key_value->tt == LUA_TSTRING) {
TString *key_tstring = (TString*) (key_value->value.gc);
key_char_ptr = getstr(key_tstring);
}
if (!weakkey) {
traverse_value(L, o, key_value, objfunc);
}
if (!weakvalue) {
traverse_value(L, o, gval(n), objfunc);
}
}
}
if (is_locked) luaH_rdunlock(L, h);
break;
}
case LUA_TFUNCTION:
{
Closure *cl = gco2cl(o);
if (cl->c.isC) {
if (!cl->c.env) {
/* Not done setting up, return */
return;
}
traverse_obj(L, o, cl->c.env, objfunc);
for (i = 0; i < cl->c.nupvalues; i++) {
traverse_value(L, o, &cl->c.upvalue[i], objfunc);
}
} else {
if (!cl->l.env || !cl->l.p) {
/* Not done being setup yet, skip */
return;
}
lua_assert(cl->l.nupvalues == cl->l.p->nups);
traverse_obj(L, o, &cl->l.p->gch, objfunc);
traverse_obj(L, o, cl->l.env, objfunc);
for (i = 0; i < cl->l.nupvalues; i++) {
if (!cl->l.upvals[i]) {
/* Not done setting up, continue */
continue;
}
traverse_obj(L, o, &cl->l.upvals[i]->gch, objfunc);
}
}
break;
}
case LUA_TTHREAD:
{
lua_State *th = gco2th(o);
StkId sk, lim;
UpVal *uv;
CallInfo *ci;
int i;
struct stringtable_node *n;
int is_locked = 0;
if (!th->stack || !th->base_ci) {
/* Not setup yet, skip for now */
return;
}
if (!is_world_stopped(L)) {
lua_lock(th);
is_locked = 1;
}
traverse_value(L, o, &th->l_gt, objfunc);
traverse_value(L, o, &th->env, objfunc);
traverse_value(L, o, &th->tls, objfunc);
/* the corresponding global state */
lua_assert(G(L) == th->l_G);
traverse_obj(L, o, &th->l_G->gch, objfunc);
lim = th->top;
for (ci = th->base_ci; ci <= th->ci; ci++) {
lua_assert(ci->top <= th->stack_last);
if (lim < ci->top) {
lim = ci->top;
}
}
for (sk = th->stack; sk < th->top; sk++) {
traverse_value(L, o, sk, objfunc);
}
if (th == L && !is_world_stopped(L)) {
for (; sk <= lim; sk++) {
setnilvalue(sk);
}
}
/* open upvalues also */
for (uv = th->openupval.u.l.next;
uv != &th->openupval; uv = uv->u.l.next) {
traverse_obj(L, o, (GCheader*)uv, objfunc);
}
/* stringtable */
for (i = 0; i < th->strt.size; i++) {
for (n = th->strt.hash[i]; n; n = n->next) {
traverse_obj(L, o, &n->str->tsv.gch, objfunc);
}
}
if (is_locked) lua_unlock(th);
break;
}
case LUA_TPROTO:
{
Proto *f = gco2p(o);
if (f->source) {
traverse_obj(L, o, &f->source->tsv.gch, objfunc);
}
for (i = 0; i < f->sizek; i++) {
traverse_value(L, o, &f->k[i], objfunc);
}
for (i = 0; i < f->sizeupvalues; i++) {
if (f->upvalues[i]) {
traverse_obj(L, o, f->upvalues[i], objfunc);
}
}
for (i = 0; i < f->sizep; i++) {
if (f->p[i]) {
traverse_obj(L, o, &f->p[i]->gch, objfunc);
}
}
for (i = 0; i < f->sizelocvars; i++) {
if (f->locvars[i].varname) {
traverse_obj(L, o, f->locvars[i].varname, objfunc);
}
}
break;
}
case LUA_TGLOBAL:
traverse_obj(L, o, &G(L)->memerr->tsv.gch, objfunc);
for (i = 0; i < NUM_TAGS; i++) {
if (G(L)->mt[i]) {
traverse_obj(L, o, &G(L)->mt[i]->gch, objfunc);
}
}
for (i = 0; i < TM_N; i++) {
if (G(L)->tmname[i]) {
traverse_obj(L, o, &G(L)->tmname[i]->tsv.gch, objfunc);
}
}
traverse_value(L, o, &G(L)->l_registry, objfunc);
traverse_value(L, o, &G(L)->ostls, objfunc);
traverse_value(L, o, &G(L)->l_globals, objfunc);
traverse_obj(L, o, &G(L)->mainthread->gch, objfunc);
break;
default:
#if HAVE_VALGRIND
VALGRIND_PRINTF_BACKTRACE("marking %s not implemented o=%p\n",
lua_typename(L, o->tt), o);
#endif
fprintf(stderr, "marking for tt=%d is not implemented\n", o->tt);
abort();
}
}
static void grey_object(lua_State *L, GCheader *lval, GCheader *rval)
{
mark_object(L, rval);
}
static void blacken_object(lua_State *L, GCheader *o)
{
lua_assert_obj(!is_free(o), o);
lua_assert_obj(o->owner == L->heap, o);
lua_assert_obj(is_grey(o) || is_black(L, o), o);
make_black(L, o);
traverse_object(L, o, grey_object);
if (o->tt == LUA_TTABLE) {
Table *h = gco2h(o);
if (o->marked & (WEAKVALBIT|WEAKKEYBIT)) {
/* remember that it had weak bits, as we will need to fixup the table
* contents if we collect them */
push_obj(&L->heap->weak, o);
}
}
}
static void propagate(lua_State *L)
{
GCheader *o;
while ((o = pop_obj(&L->heap->grey)) != NULL) {
blacken_object(L, o);
}
}
static INLINE void lock_all_threads(void)
{
int r = pthread_mutex_lock(&all_threads_lock);
if (r) {
fprintf(stderr, "LOCK(all_threads): %d %s\n", r, strerror(r));
abort();
}
}
/* Try to grab the "all threads" lock.
*
* When wait_in_ms > 0, this will wait that many milliseconds,
* in order to acquire the lock. If it's <= 0,
* then it will try once and then fail if the mutex could not be acquired.
*
* The Lua state L can be NULL.
*/
static INLINE int try_lock_all_threads (lua_State *L, int wait_in_ms)
{
int r = EBUSY;
if (wait_in_ms > 0) {
struct timespec timeout;
clock_gettime(CLOCK_REALTIME, &timeout);
timeout.tv_nsec += wait_in_ms * 1000000L; /* ms -> ns */
while (timeout.tv_nsec >= 1000000000L) {
timeout.tv_sec += 1L;
timeout.tv_nsec -= 1000000000L;
}
r = pthread_mutex_timedlock(&all_threads_lock, &timeout);
} else {
r = pthread_mutex_trylock(&all_threads_lock);
}
switch (r) {
case 0:
return 1;
case ETIMEDOUT: /* pthread_mutex_timedlock timed out */
case EBUSY: /* pthread_mutex_trylock failed to grab it */
return 0;
default:
if (L) {
thrlua_log(L, DCRITICAL, "thrlua: LOCK(all_threads): %d %s\n", r, strerror(r));
}
fprintf(stderr, "LOCK(all_threads): %d %s\n", r, strerror(r));
abort();
}