-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy patherl_nif.c
6839 lines (6008 loc) · 192 KB
/
erl_nif.c
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
/*
* %CopyrightBegin%
*
* Copyright Ericsson AB 2009-2024. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* %CopyrightEnd%
*/
/* Erlang Native InterFace
*/
/*
* Environment contains a pointer to currently executing process.
* In the dirty case this pointer do however not point to the
* actual process structure of the executing process, but instead
* a "shadow process structure". This in order to be able to handle
* heap allocation without the need to acquire the main lock on
* the process.
*
* The dirty process is allowed to allocate on the heap without
* the main lock, i.e., incrementing htop, but is not allowed to
* modify mbuf, offheap, etc without the main lock. The dirty
* process moves mbuf list and offheap list of the shadow process
* structure into the real structure when the dirty nif call
* completes.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "erl_nif.h"
#include "sys.h"
#include "global.h"
#include "erl_binary.h"
#include "bif.h"
#include "error.h"
#include "big.h"
#include "erl_map.h"
#include "beam_bp.h"
#include "erl_thr_progress.h"
#include "dtrace-wrapper.h"
#include "erl_process.h"
#include "erl_bif_unique.h"
#include "erl_utils.h"
#include "erl_io_queue.h"
#include "erl_proc_sig_queue.h"
#include "beam_common.h"
#undef ERTS_WANT_NFUNC_SCHED_INTERNALS__
#define ERTS_WANT_NFUNC_SCHED_INTERNALS__
#include "erl_nfunc_sched.h"
#if defined(USE_DYNAMIC_TRACE) && (defined(USE_DTRACE) || defined(USE_SYSTEMTAP))
#define HAVE_USE_DTRACE 1
#endif
#include "jit/beam_asm.h"
#include "erl_global_literals.h"
#include "erl_iolist.h"
#include <limits.h>
#include <stddef.h> /* offsetof */
#define ERTS_NIF_HALT_INFO_FLAG_BLOCK (1 << 0)
#define ERTS_NIF_HALT_INFO_FLAG_HALTING (1 << 1)
#define ERTS_NIF_HALT_INFO_FLAG_WAITING (1 << 2)
typedef struct ErtsNifOnHaltData_ ErtsNifOnHaltData;
struct ErtsNifOnHaltData_ {
ErtsNifOnHaltData *next;
ErtsNifOnHaltData *prev;
ErlNifOnHaltCallback *callback;
};
/* Information about a loaded nif library.
* Each successful call to erlang:load_nif will allocate an instance of
* erl_module_nif. Two calls opening the same library will thus have the same
* 'handle'.
*/
struct erl_module_nif {
erts_refc_t refc; /* References to this struct
* +1 erl_module_instance (loaded Erlang code)
* +1 "dlopen" (loaded native code)
* +1 scheduled load finisher
* +1 for each owned resource type
*/
erts_mtx_t load_mtx; /* protects load finish from unload */
struct ErtsNifFinish_* finish;
ErtsCodeBarrier barrier;
void* priv_data;
void* handle; /* "dlopen", NULL for static linked */
struct enif_entry_t entry;
erts_refc_t dynlib_refc; /* References to loaded native code
+1 erl_module_instance
+1 for each owned resource type with callbacks
+1 for each ongoing dirty NIF call
*/
int flags;
ErtsNifOnHaltData on_halt;
ErlNifOnUnloadThreadCallback* unload_thr_callback;
erts_atomic_t unload_thr_counter;
Module* mod; /* Can be NULL if purged and dynlib_refc > 0 */
/* Holds a copy of the `erl_module_instance` we're loading the module into,
* which may be freed (and moved into the staging table) if there's an
* on_load function that finishes before we're done loading the NIF. */
struct erl_module_instance mi_copy;
ErlNifFunc _funcs_copy_[1]; /* only used for old libs */
};
#define ERTS_MOD_NIF_FLG_LOADING (1 << 0)
#define ERTS_MOD_NIF_FLG_DELAY_HALT (1 << 1)
#define ERTS_MOD_NIF_FLG_ON_HALT (1 << 2)
static erts_atomic_t halt_tse;
static erts_mtx_t on_halt_mtx;
static ErtsNifOnHaltData *on_halt_requests;
typedef ERL_NIF_TERM (*NativeFunPtr)(ErlNifEnv*, int, const ERL_NIF_TERM[]);
#ifdef DEBUG
# define READONLY_CHECK
# define ERTS_DBG_NIF_NOT_SCHED_MARKER ((void *) (UWord) 1)
#endif
#ifdef READONLY_CHECK
# define ADD_READONLY_CHECK(ENV,PTR,SIZE) add_readonly_check(ENV,PTR,SIZE)
static void add_readonly_check(ErlNifEnv*, unsigned char* ptr, unsigned sz);
#else
# define ADD_READONLY_CHECK(ENV,PTR,SIZE) ((void)0)
#endif
#ifdef ERTS_NIF_ASSERT_IN_ENV
# define ASSERT_IN_ENV(ENV, TERM, NR, TYPE) dbg_assert_in_env(ENV, TERM, NR, TYPE, __func__)
static void dbg_assert_in_env(ErlNifEnv*, Eterm term, int nr, const char* type, const char* func);
# include "erl_gc.h"
#else
# define ASSERT_IN_ENV(ENV, TERM, NR, TYPE)
#endif
#ifdef DEBUG
static int is_offheap(const ErlOffHeap* off_heap);
#endif
#ifdef USE_VM_PROBES
void dtrace_nifenv_str(ErlNifEnv *, char *);
#endif
#define MIN_HEAP_FRAG_SZ 200
static Eterm* alloc_heap_heavy(ErlNifEnv* env, size_t need, Eterm* hp);
static void install_on_halt_callback(ErtsNifOnHaltData *ohdp);
static void uninstall_on_halt_callback(ErtsNifOnHaltData *ohdp);
static ERTS_INLINE int
is_scheduler(void)
{
ErtsSchedulerData *esdp = erts_get_scheduler_data();
if (!esdp)
return 0;
if (ERTS_SCHEDULER_IS_DIRTY(esdp))
return -1;
return 1;
}
static ERTS_INLINE void
execution_state(ErlNifEnv *env, Process **c_pp, int *schedp)
{
if (schedp)
*schedp = is_scheduler();
if (c_pp) {
if (!env || env->proc->common.id == ERTS_INVALID_PID)
*c_pp = NULL;
else {
Process *c_p = env->proc;
if (!(c_p->static_flags & ERTS_STC_FLG_SHADOW_PROC)) {
ERTS_LC_ASSERT(erts_proc_lc_my_proc_locks(c_p)
& ERTS_PROC_LOCK_MAIN);
}
else {
c_p = env->proc->next;
ASSERT(is_scheduler() < 0);
ASSERT(c_p && env->proc->common.id == c_p->common.id);
}
*c_pp = c_p;
ASSERT(!(c_p->static_flags & ERTS_STC_FLG_SHADOW_PROC));
}
}
}
static ERTS_INLINE Eterm* alloc_heap(ErlNifEnv* env, size_t need)
{
Eterm* hp = env->hp;
env->hp += need;
if (env->hp <= env->hp_end) {
return hp;
}
return alloc_heap_heavy(env, need, hp);
}
static Eterm* alloc_heap_heavy(ErlNifEnv* env, size_t need, Eterm* hp)
{
env->hp = hp;
if (env->heap_frag == NULL) {
ASSERT(HEAP_LIMIT(env->proc) == env->hp_end);
ASSERT(env->hp + need > env->hp_end);
HEAP_TOP(env->proc) = env->hp;
}
else {
Uint usz = env->hp - env->heap_frag->mem;
env->proc->mbuf_sz += usz - env->heap_frag->used_size;
env->heap_frag->used_size = usz;
ASSERT(env->heap_frag->used_size <= env->heap_frag->alloc_size);
}
hp = erts_heap_alloc(env->proc, need, MIN_HEAP_FRAG_SZ);
env->heap_frag = MBUF(env->proc);
env->hp = hp + need;
env->hp_end = env->heap_frag->mem + env->heap_frag->alloc_size;
return hp;
}
#if SIZEOF_LONG != ERTS_SIZEOF_ETERM
static ERTS_INLINE void ensure_heap(ErlNifEnv* env, size_t may_need)
{
if (env->hp + may_need > env->hp_end) {
alloc_heap_heavy(env, may_need, env->hp);
env->hp -= may_need;
}
}
#endif
void erts_pre_nif(ErlNifEnv* env, Process* p, struct erl_module_nif* mod_nif,
Process* tracee)
{
env->mod_nif = mod_nif;
env->proc = p;
env->hp = HEAP_TOP(p);
env->hp_end = HEAP_LIMIT(p);
env->heap_frag = NULL;
env->tmp_obj_list = NULL;
env->exception_thrown = 0;
env->tracee = tracee;
ASSERT(p->common.id != ERTS_INVALID_PID);
#ifdef ERTS_NIF_ASSERT_IN_ENV
env->dbg_disable_assert_in_env = 0;
#endif
#if defined(DEBUG) && defined(ERTS_DIRTY_SCHEDULERS)
{
ErtsSchedulerData *esdp = erts_get_scheduler_data();
ASSERT(esdp);
if (!ERTS_SCHEDULER_IS_DIRTY(esdp)) {
erts_aint32_t state = erts_atomic32_read_nob(&p->state);
ASSERT(p->scheduler_data == esdp);
ASSERT((state & (ERTS_PSFLG_RUNNING
| ERTS_PSFLG_RUNNING_SYS))
&& !(state & (ERTS_PSFLG_DIRTY_RUNNING
| ERTS_PSFLG_DIRTY_RUNNING_SYS)));
}
}
#endif
}
static void full_cache_env(ErlNifEnv *env);
static void cache_env(ErlNifEnv* env);
static void full_flush_env(ErlNifEnv *env);
static void flush_env(ErlNifEnv* env);
/* Temporary object header, auto-deallocated when NIF returns or when
* independent environment is cleared.
*
* The payload can be accessed with &tmp_obj_ptr[1] but keep in mind that its
* first element must not require greater alignment than `next`. */
struct enif_tmp_obj_t {
struct enif_tmp_obj_t* next;
void (*dtor)(struct enif_tmp_obj_t*);
ErtsAlcType_t allocator;
/*char data[];*/
};
static ERTS_INLINE void free_tmp_objs(ErlNifEnv* env)
{
while (env->tmp_obj_list != NULL) {
struct enif_tmp_obj_t* free_me = env->tmp_obj_list;
env->tmp_obj_list = free_me->next;
free_me->dtor(free_me);
}
}
/* Whether the given environment is bound to a process and will be cleaned up
* when the NIF returns. It's safe to use temp_alloc for objects in
* env->tmp_obj_list when this is true. */
static ERTS_INLINE int is_proc_bound(ErlNifEnv *env)
{
return env->mod_nif != NULL;
}
/* Allocates and attaches an object to the given environment, running its
* destructor when the environment is cleared. To avoid temporary variables the
* address of the allocated object is returned instead of the enif_tmp_obj_t.
*
* The destructor *must* call `erts_free(tmp_obj->allocator, tmp_obj)` to free
* the object. If the destructor needs to refer to the allocated object its
* address will be &tmp_obj[1]. */
static ERTS_INLINE void *alloc_tmp_obj(ErlNifEnv *env, size_t size,
void (*dtor)(struct enif_tmp_obj_t*)) {
struct enif_tmp_obj_t *tmp_obj;
ErtsAlcType_t allocator;
allocator = is_proc_bound(env) ? ERTS_ALC_T_TMP : ERTS_ALC_T_NIF;
tmp_obj = erts_alloc(allocator, sizeof(struct enif_tmp_obj_t) + MAX(1, size));
tmp_obj->next = env->tmp_obj_list;
tmp_obj->allocator = allocator;
tmp_obj->dtor = dtor;
env->tmp_obj_list = tmp_obj;
return (void*)&tmp_obj[1];
}
/* Generic destructor for objects allocated through alloc_tmp_obj that don't
* care about their payload. */
static void tmp_alloc_dtor(struct enif_tmp_obj_t *tmp_obj)
{
erts_free(tmp_obj->allocator, tmp_obj);
}
void erts_post_nif(ErlNifEnv* env)
{
full_flush_env(env);
free_tmp_objs(env);
env->exiting = ERTS_PROC_IS_EXITING(env->proc);
}
/*
* Initialize a ErtsNativeFunc struct. Create it if needed and store it in the
* proc. The direct_fp function is what will be invoked by op_call_nif, and
* the indirect_fp function, if not NULL, is what the direct_fp function
* will call. If the allocated ErtsNativeFunc isn't enough to hold all of argv,
* allocate a larger one. Save 'current' and registers if first time this
* call is scheduled.
*/
static ERTS_INLINE ERL_NIF_TERM
schedule(ErlNifEnv* env, NativeFunPtr direct_fp, NativeFunPtr indirect_fp,
Eterm mod, Eterm func_name, int argc, const ERL_NIF_TERM argv[])
{
ErtsNativeFunc *ep;
Process *c_p, *dirty_shadow_proc;
ErtsCodePtr caller;
execution_state(env, &c_p, NULL);
ASSERT(c_p);
if (c_p == env->proc)
dirty_shadow_proc = NULL;
else
dirty_shadow_proc = env->proc;
ERTS_LC_ASSERT(ERTS_PROC_LOCK_MAIN & erts_proc_lc_my_proc_locks(c_p));
erts_inspect_frame(c_p->stop, &caller);
ep = erts_nfunc_schedule(c_p, dirty_shadow_proc,
c_p->current,
caller,
BeamOpCodeAddr(op_call_nif_WWW),
direct_fp, indirect_fp,
mod, func_name,
argc, (const Eterm *) argv);
if (!ep->m) {
/* First time this call is scheduled... */
erts_refc_inc(&env->mod_nif->dynlib_refc, 2);
ep->m = env->mod_nif;
}
return (ERL_NIF_TERM) THE_NON_VALUE;
}
static ERTS_NOINLINE void
eternal_sleep(void)
{
while (!0)
erts_milli_sleep(1000*1000);
}
static ERTS_NOINLINE void
handle_halting_unblocked_halt(erts_aint32_t info)
{
if (info & ERTS_NIF_HALT_INFO_FLAG_WAITING) {
erts_tse_t *tse;
ERTS_THR_MEMORY_BARRIER;
tse = (erts_tse_t *) erts_atomic_read_nob(&halt_tse);
ASSERT(tse);
erts_tse_set(tse);
}
eternal_sleep();
}
static ERL_NIF_TERM dirty_nif_finalizer(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM dirty_nif_exception(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
int
erts_call_dirty_nif(ErtsSchedulerData *esdp,
Process *c_p,
ErtsCodePtr I,
Eterm *reg)
{
int exiting;
ERL_NIF_TERM *argv = (ERL_NIF_TERM *) reg;
ErtsNativeFunc *nep = ERTS_I_BEAM_OP_TO_NFUNC(I);
const ErtsCodeMFA *codemfa = erts_code_to_codemfa(I);
NativeFunPtr dirty_nif = (NativeFunPtr) nep->trampoline.dfunc;
ErlNifEnv env;
ERL_NIF_TERM result;
#ifdef DEBUG
erts_aint32_t state = erts_atomic32_read_nob(&c_p->state);
ASSERT(nep == ERTS_PROC_GET_NFUNC_TRAP_WRAPPER(c_p));
ASSERT(!c_p->scheduler_data);
ASSERT((state & ERTS_PSFLG_DIRTY_RUNNING)
&& !(state & (ERTS_PSFLG_RUNNING|ERTS_PSFLG_RUNNING_SYS)));
ASSERT(esdp);
nep->func = ERTS_DBG_NIF_NOT_SCHED_MARKER;
#endif
erts_pre_nif(&env, c_p, nep->m, NULL);
env.proc = erts_make_dirty_shadow_proc(esdp, c_p);
env.proc->freason = EXC_NULL;
env.proc->fvalue = NIL;
env.proc->ftrace = NIL;
env.proc->i = c_p->i;
ASSERT(ERTS_SCHEDULER_IS_DIRTY(erts_get_scheduler_data()));
erts_atomic32_read_band_mb(&c_p->state, ~(ERTS_PSFLG_DIRTY_CPU_PROC
| ERTS_PSFLG_DIRTY_IO_PROC));
ASSERT(esdp->current_nif == NULL);
esdp->current_nif = &env;
erts_proc_unlock(c_p, ERTS_PROC_LOCK_MAIN);
if (!(env.mod_nif->flags & ERTS_MOD_NIF_FLG_DELAY_HALT)) {
result = (*dirty_nif)(&env, codemfa->arity, argv); /* Call dirty NIF */
}
else {
erts_atomic32_t *dirty_nif_halt_info = &esdp->u.dirty_nif_halt_info;
erts_aint32_t info;
info = erts_atomic32_cmpxchg_nob(dirty_nif_halt_info,
ERTS_NIF_HALT_INFO_FLAG_BLOCK,
0);
if (info != 0) {
ASSERT(info == ERTS_NIF_HALT_INFO_FLAG_HALTING
|| info == (ERTS_NIF_HALT_INFO_FLAG_HALTING
| ERTS_NIF_HALT_INFO_FLAG_WAITING));
eternal_sleep();
}
result = (*dirty_nif)(&env, codemfa->arity, argv); /* Call dirty NIF */
info = erts_atomic32_read_band_relb(dirty_nif_halt_info,
~ERTS_NIF_HALT_INFO_FLAG_BLOCK);
if (info & ERTS_NIF_HALT_INFO_FLAG_HALTING) {
ASSERT(info == (ERTS_NIF_HALT_INFO_FLAG_BLOCK
| ERTS_NIF_HALT_INFO_FLAG_HALTING)
|| info == (ERTS_NIF_HALT_INFO_FLAG_BLOCK
| ERTS_NIF_HALT_INFO_FLAG_HALTING
| ERTS_NIF_HALT_INFO_FLAG_WAITING));
handle_halting_unblocked_halt(info);
}
ASSERT(info == ERTS_NIF_HALT_INFO_FLAG_BLOCK);
}
erts_proc_lock(c_p, ERTS_PROC_LOCK_MAIN);
ASSERT(esdp->current_nif == &env);
esdp->current_nif = NULL;
ASSERT(env.proc->static_flags & ERTS_STC_FLG_SHADOW_PROC);
ASSERT(env.proc->next == c_p);
exiting = ERTS_PROC_IS_EXITING(c_p);
if (!exiting) {
if (env.exception_thrown) {
schedule_exception:
schedule(&env, dirty_nif_exception, NULL,
am_erts_internal, am_dirty_nif_exception,
1, &env.proc->fvalue);
}
else if (is_value(result)) {
schedule(&env, dirty_nif_finalizer, NULL,
am_erts_internal, am_dirty_nif_finalizer,
1, &result);
}
else if (env.proc->freason != TRAP) { /* user returned garbage... */
ERTS_DECL_AM(badreturn);
(void) enif_raise_exception(&env, AM_badreturn);
goto schedule_exception;
}
else {
/* Rescheduled by dirty NIF call... */
ASSERT(nep->func != ERTS_DBG_NIF_NOT_SCHED_MARKER);
}
c_p->i = env.proc->i;
c_p->arity = env.proc->arity;
}
#ifdef DEBUG
if (nep->func == ERTS_DBG_NIF_NOT_SCHED_MARKER)
nep->func = NULL;
#endif
full_flush_env(&env);
free_tmp_objs(&env);
return exiting;
}
static void full_flush_env(ErlNifEnv* env)
{
flush_env(env);
if (env->proc->static_flags & ERTS_STC_FLG_SHADOW_PROC)
/* Dirty nif call using shadow process struct */
erts_flush_dirty_shadow_proc(env->proc);
}
static void full_cache_env(ErlNifEnv* env)
{
if (env->proc->static_flags & ERTS_STC_FLG_SHADOW_PROC) {
erts_cache_dirty_shadow_proc(env->proc);
/*
* If shadow proc had heap fragments when flushed
* those have now been moved to the real proc.
* Ensure heap pointers do not point into a heap
* fragment on real proc...
*/
ASSERT(!env->proc->mbuf);
env->hp_end = HEAP_LIMIT(env->proc);
env->hp = HEAP_TOP(env->proc);
}
cache_env(env);
}
/* Flush out our cached heap pointers to allow an ordinary HAlloc
*/
static void flush_env(ErlNifEnv* env)
{
if (env->heap_frag == NULL) {
ASSERT(env->hp_end == HEAP_LIMIT(env->proc));
ASSERT(env->hp >= HEAP_TOP(env->proc));
ASSERT(env->hp <= HEAP_LIMIT(env->proc));
HEAP_TOP(env->proc) = env->hp;
}
else {
Uint usz;
ASSERT(env->hp_end != HEAP_LIMIT(env->proc));
ASSERT(env->hp_end - env->hp <= env->heap_frag->alloc_size);
usz = env->hp - env->heap_frag->mem;
env->proc->mbuf_sz += usz - env->heap_frag->used_size;
env->heap_frag->used_size = usz;
ASSERT(env->heap_frag->used_size <= env->heap_frag->alloc_size);
}
}
/* Restore cached heap pointers to allow alloc_heap again.
*/
static void cache_env(ErlNifEnv* env)
{
env->heap_frag = MBUF(env->proc);
if (env->heap_frag == NULL) {
ASSERT(env->hp_end == HEAP_LIMIT(env->proc));
ASSERT(env->hp <= HEAP_TOP(env->proc));
ASSERT(env->hp <= HEAP_LIMIT(env->proc));
env->hp = HEAP_TOP(env->proc);
}
else {
env->hp = env->heap_frag->mem + env->heap_frag->used_size;
env->hp_end = env->heap_frag->mem + env->heap_frag->alloc_size;
}
}
void* enif_priv_data(ErlNifEnv* env)
{
return env->mod_nif->priv_data;
}
void* enif_alloc(size_t size)
{
return erts_alloc_fnf(ERTS_ALC_T_NIF, (Uint) size);
}
void* enif_realloc(void* ptr, size_t size)
{
return erts_realloc_fnf(ERTS_ALC_T_NIF, ptr, size);
}
void enif_free(void* ptr)
{
erts_free(ERTS_ALC_T_NIF, ptr);
}
struct enif_msg_environment_t
{
ErlNifEnv env;
Process phony_proc;
};
static Eterm phony_heap[32];
static ERTS_INLINE void
setup_nif_env(struct enif_msg_environment_t* msg_env,
struct erl_module_nif* mod,
Process* tracee)
{
ASSERT(sizeof(phony_heap) > (S_REDZONE * sizeof(Eterm)));
msg_env->env.hp = &phony_heap[0];
msg_env->env.hp_end = &phony_heap[0];
msg_env->env.heap_frag = NULL;
msg_env->env.mod_nif = mod;
msg_env->env.tmp_obj_list = NULL;
msg_env->env.proc = &msg_env->phony_proc;
msg_env->env.exception_thrown = 0;
sys_memset(&msg_env->phony_proc, 0, sizeof(Process));
HEAP_START(&msg_env->phony_proc) = &phony_heap[0];
HEAP_TOP(&msg_env->phony_proc) = &phony_heap[0];
STACK_TOP(&msg_env->phony_proc) = &phony_heap[S_REDZONE];
STACK_START(&msg_env->phony_proc) = &phony_heap[S_REDZONE];
MBUF(&msg_env->phony_proc) = NULL;
msg_env->phony_proc.common.id = ERTS_INVALID_PID;
msg_env->env.tracee = tracee;
#ifdef FORCE_HEAP_FRAGS
msg_env->phony_proc.space_verified = 0;
msg_env->phony_proc.space_verified_from = NULL;
#endif
#ifdef ERTS_NIF_ASSERT_IN_ENV
msg_env->env.dbg_disable_assert_in_env = 0;
#endif
}
ErlNifEnv* enif_alloc_env(void)
{
struct enif_msg_environment_t* msg_env =
erts_alloc_fnf(ERTS_ALC_T_NIF, sizeof(struct enif_msg_environment_t));
setup_nif_env(msg_env, NULL, NULL);
return &msg_env->env;
}
void enif_free_env(ErlNifEnv* env)
{
enif_clear_env(env);
erts_free(ERTS_ALC_T_NIF, env);
}
static ERTS_INLINE void pre_nif_noproc(struct enif_msg_environment_t* msg_env,
struct erl_module_nif* mod,
Process* tracee)
{
setup_nif_env(msg_env, mod, tracee);
}
static ERTS_INLINE void post_nif_noproc(struct enif_msg_environment_t* msg_env)
{
enif_clear_env(&msg_env->env);
}
static ERTS_INLINE void clear_offheap(ErlOffHeap* oh)
{
oh->first = NULL;
oh->overhead = 0;
}
void enif_clear_env(ErlNifEnv* env)
{
struct enif_msg_environment_t* menv = (struct enif_msg_environment_t*)env;
Process* p = &menv->phony_proc;
ASSERT(p == menv->env.proc);
ASSERT(p->common.id == ERTS_INVALID_PID);
ASSERT(MBUF(p) == menv->env.heap_frag);
free_tmp_objs(env);
if (MBUF(p) != NULL) {
erts_cleanup_offheap(&MSO(p));
clear_offheap(&MSO(p));
free_message_buffer(MBUF(p));
MBUF(p) = NULL;
menv->env.heap_frag = NULL;
}
ASSERT(HEAP_TOP(p) == HEAP_END(p) - S_REDZONE);
menv->env.hp = menv->env.hp_end = HEAP_TOP(p);
ASSERT(!is_offheap(&MSO(p)));
ASSERT(!p->wrt_bins);
}
#ifdef DEBUG
static int enif_send_delay = 0;
#define ERTS_FORCE_ENIF_SEND_DELAY() (enif_send_delay++ % 32 == 0)
#else
#ifdef ERTS_PROC_LOCK_OWN_IMPL
#define ERTS_FORCE_ENIF_SEND_DELAY() 0
#else
/*
* We always schedule messages if we do not use our own
* process lock implementation, as if we try to do a trylock on
* a lock that might already be locked by the same thread.
* And what happens then with different mutex implementations
* is not always guaranteed.
*/
#define ERTS_FORCE_ENIF_SEND_DELAY() 1
#endif
#endif
int erts_flush_trace_messages(Process *c_p, ErtsProcLocks c_p_locks)
{
ErlTraceMessageQueue *msgq, **last_msgq;
int reds = 0;
/* Only one thread at a time is allowed to flush trace messages,
so we require the main lock to be held when doing the flush */
ERTS_CHK_HAVE_ONLY_MAIN_PROC_LOCK(c_p);
erts_proc_lock(c_p, ERTS_PROC_LOCK_TRACE);
msgq = c_p->trace_msg_q;
if (!msgq)
goto error;
do {
Process* rp;
ErtsProcLocks rp_locks;
ErtsMessage *first, **last;
Uint len;
first = msgq->first;
last = msgq->last;
len = msgq->len;
msgq->first = NULL;
msgq->last = &msgq->first;
msgq->len = 0;
erts_proc_unlock(c_p, ERTS_PROC_LOCK_TRACE);
ASSERT(len != 0);
rp = erts_proc_lookup(msgq->receiver);
if (rp) {
rp_locks = 0;
if (rp->common.id == c_p->common.id)
rp_locks = c_p_locks;
erts_queue_proc_messages(c_p, rp, rp_locks, first, last, len);
if (rp->common.id == c_p->common.id)
rp_locks &= ~c_p_locks;
if (rp_locks)
erts_proc_unlock(rp, rp_locks);
reds += len;
} else {
erts_cleanup_messages(first);
}
reds += 1;
erts_proc_lock(c_p, ERTS_PROC_LOCK_TRACE);
msgq = msgq->next;
} while (msgq);
last_msgq = &c_p->trace_msg_q;
while (*last_msgq) {
msgq = *last_msgq;
if (msgq->len == 0) {
*last_msgq = msgq->next;
erts_free(ERTS_ALC_T_TRACE_MSG_QUEUE, msgq);
} else {
last_msgq = &msgq->next;
}
}
error:
erts_proc_unlock(c_p, ERTS_PROC_LOCK_TRACE);
return reds;
}
/** @brief Create a message with the content of process independent \c msg_env.
* Invalidates \c msg_env.
*/
ErtsMessage* erts_create_message_from_nif_env(ErlNifEnv* msg_env)
{
struct enif_msg_environment_t* menv = (struct enif_msg_environment_t*)msg_env;
ErtsMessage* mp;
flush_env(msg_env);
mp = erts_alloc_message(0, NULL);
mp->data.heap_frag = menv->env.heap_frag;
ASSERT(mp->data.heap_frag == MBUF(&menv->phony_proc));
if (mp->data.heap_frag != NULL) {
/* Move all offheap's from phony proc to the first fragment.
Quick and dirty... */
ASSERT(!is_offheap(&mp->data.heap_frag->off_heap));
mp->data.heap_frag->off_heap = MSO(&menv->phony_proc);
clear_offheap(&MSO(&menv->phony_proc));
menv->env.heap_frag = NULL;
MBUF(&menv->phony_proc) = NULL;
}
return mp;
}
static ERTS_INLINE ERL_NIF_TERM make_copy(ErlNifEnv* dst_env,
ERL_NIF_TERM src_term,
Uint *cpy_szp)
{
Uint sz;
Eterm* hp;
/*
* No preserved sharing allowed as long as literals are also preserved.
* Process independent environment can not be reached by purge.
*/
sz = size_object(src_term);
if (cpy_szp)
*cpy_szp += sz;
hp = alloc_heap(dst_env, sz);
return copy_struct(src_term, sz, &hp, &MSO(dst_env->proc));
}
int enif_send(ErlNifEnv* env, const ErlNifPid* to_pid,
ErlNifEnv* msg_env, ERL_NIF_TERM msg)
{
struct enif_msg_environment_t* menv = (struct enif_msg_environment_t*)msg_env;
ErtsProcLocks rp_locks = 0;
ErtsProcLocks lc_locks = 0;
Process* rp;
Process* c_p;
ErtsMessage *mp;
Eterm from;
Eterm receiver = to_pid->pid;
int scheduler;
Uint copy_sz = 0;
execution_state(env, &c_p, &scheduler);
if (scheduler > 0) { /* Normal scheduler */
rp = erts_proc_lookup(receiver);
if (!rp)
return 0;
}
else {
if (c_p) {
ASSERT(scheduler < 0); /* Dirty scheduler */
if (ERTS_PROC_IS_EXITING(c_p))
return 0;
if (env->proc->static_flags & ERTS_STC_FLG_SHADOW_PROC) {
erts_proc_lock(c_p, ERTS_PROC_LOCK_MAIN);
}
}
rp = erts_pid2proc_opt(c_p, ERTS_PROC_LOCK_MAIN,
receiver, rp_locks,
ERTS_P2P_FLG_INC_REFC);
if (!rp) {
if (c_p && (env->proc->static_flags & ERTS_STC_FLG_SHADOW_PROC))
erts_proc_unlock(c_p, ERTS_PROC_LOCK_MAIN);
return 0;
}
}
if (c_p == rp)
rp_locks = ERTS_PROC_LOCK_MAIN;
if (menv) {
Eterm token = c_p ? SEQ_TRACE_TOKEN(c_p) : am_undefined;
if (token != NIL && token != am_undefined) {
/* This code is copied from erts_send_message */
Eterm stoken = SEQ_TRACE_TOKEN(c_p);
#ifdef USE_VM_PROBES
DTRACE_CHARBUF(sender_name, 64);
DTRACE_CHARBUF(receiver_name, 64);
Sint tok_label = 0;
Sint tok_lastcnt = 0;
Sint tok_serial = 0;
Eterm utag = NIL;
*sender_name = *receiver_name = '\0';
if (DTRACE_ENABLED(message_send)) {
erts_snprintf(sender_name, sizeof(DTRACE_CHARBUF_NAME(sender_name)),
"%T", c_p->common.id);
erts_snprintf(receiver_name, sizeof(DTRACE_CHARBUF_NAME(receiver_name)),
"%T", rp->common.id);
}
#endif
if (have_seqtrace(stoken)) {
seq_trace_update_serial(c_p);
seq_trace_output(stoken, msg, SEQ_TRACE_SEND,
rp->common.id, c_p);
}
#ifdef USE_VM_PROBES
if (!(DT_UTAG_FLAGS(c_p) & DT_UTAG_SPREADING)) {
stoken = NIL;
}
#endif
token = make_copy(msg_env, stoken, ©_sz);
#ifdef USE_VM_PROBES
if (DT_UTAG_FLAGS(c_p) & DT_UTAG_SPREADING) {
if (is_immed(DT_UTAG(c_p)))
utag = DT_UTAG(c_p);
else
utag = make_copy(msg_env, DT_UTAG(c_p), ©_sz);
}
if (DTRACE_ENABLED(message_send)) {
if (have_seqtrace(stoken)) {
tok_label = SEQ_TRACE_T_DTRACE_LABEL(stoken);
tok_lastcnt = signed_val(SEQ_TRACE_T_LASTCNT(stoken));
tok_serial = signed_val(SEQ_TRACE_T_SERIAL(stoken));
}
DTRACE6(message_send, sender_name, receiver_name,
size_object(msg), tok_label, tok_lastcnt, tok_serial);
}
#endif
}
mp = erts_create_message_from_nif_env(msg_env);
ERL_MESSAGE_TOKEN(mp) = token;
} else {
erts_literal_area_t litarea;
ErlOffHeap *ohp;
Eterm *hp;
Uint sz;
INITIALIZE_LITERAL_PURGE_AREA(litarea);
sz = size_object_litopt(msg, &litarea);
copy_sz += sz;
if (c_p && !env->tracee) {
full_flush_env(env);
mp = erts_alloc_message_heap(rp, &rp_locks, sz, &hp, &ohp);
full_cache_env(env);
}
else {
erts_aint_t state = erts_atomic32_read_nob(&rp->state);
if (state & ERTS_PSFLG_OFF_HEAP_MSGQ) {
mp = erts_alloc_message(sz, &hp);
ohp = sz == 0 ? NULL : &mp->hfrag.off_heap;
}
else {
ErlHeapFragment *bp = new_message_buffer(sz);
mp = erts_alloc_message(0, NULL);
mp->data.heap_frag = bp;
hp = bp->mem;
ohp = &bp->off_heap;
}
}
ERL_MESSAGE_TOKEN(mp) = am_undefined;
msg = copy_struct_litopt(msg, sz, &hp, ohp, &litarea);
}
from = c_p ? c_p->common.id : am_undefined;
if (!env || !env->tracee) {
/* This clause is taken when enif_send is called in a nif
that is not a erl_tracer nif. */
if (c_p) {
ASSERT(env);
if (ERTS_IS_P_TRACED_FL(c_p, F_TRACE_SEND)) {
full_flush_env(env);
trace_send(c_p, receiver, msg);
full_cache_env(env);
}
if (scheduler > 0 && copy_sz > ERTS_MSG_COPY_WORDS_PER_REDUCTION) {
Uint reds = copy_sz / ERTS_MSG_COPY_WORDS_PER_REDUCTION;
if (reds > CONTEXT_REDS)
reds = CONTEXT_REDS;
BUMP_REDS(c_p, (int) reds);
}
}
}
else {