diff --git a/.github/labeler.yml b/.github/labeler.yml new file mode 100644 index 0000000000000..9359bd0ca70a6 --- /dev/null +++ b/.github/labeler.yml @@ -0,0 +1,3 @@ +# See https://github.com/actions/labeler +port-to-master: '**' +port-to-v1.10: '**' diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000000000..7ed825781c53b --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,14 @@ + +## PR Description + +_What does this PR do?_ + +## Checklist + +Requirements for merging: +- [ ] I have opened an issue or PR upstream on JuliaLang/julia: +- [ ] I have removed the `port-to-*` labels that don't apply. +- [ ] I have opened a PR on raicode to test these changes: diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml new file mode 100644 index 0000000000000..2141a906e96cd --- /dev/null +++ b/.github/workflows/labeler.yml @@ -0,0 +1,17 @@ +# See https://github.com/actions/labeler +name: "Pull Request Labeler" +on: + pull_request_target: + types: + - opened + +jobs: + triage: + permissions: + contents: read + pull-requests: write + runs-on: ubuntu-latest + steps: + - uses: actions/labeler@v4 + with: + dot: true diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml new file mode 100644 index 0000000000000..3df2093491753 --- /dev/null +++ b/.github/workflows/stale.yml @@ -0,0 +1,16 @@ +name: "Close stale PRs" +on: + schedule: + - cron: "0 0 * * *" # every night at midnight + +jobs: + stale: + runs-on: ubuntu-latest + steps: + - uses: actions/stale@v8 + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + stale-pr-message: 'This PR is stale because it has been open 30 days with no activity. Comment or remove stale label, or this PR will be closed in 5 days.' + days-before-stale: 30 + days-before-close: 5 + stale-pr-label: 'stale' diff --git a/.github/workflows/update-upstream-branches.yml b/.github/workflows/update-upstream-branches.yml new file mode 100644 index 0000000000000..247000bbd42cd --- /dev/null +++ b/.github/workflows/update-upstream-branches.yml @@ -0,0 +1,28 @@ +name: "Update upstream branches" +on: + schedule: + - cron: "0 0 * * *" # every night at midnight + workflow_dispatch: + +jobs: + PullUpstream: + runs-on: ubuntu-latest + strategy: + fail-fast: false # run all jobs in the matrix even if one fails + matrix: + branch: + - "master" + - "backports-release-1.10" + steps: + - name: Checkout RAI/julia + uses: actions/checkout@v3 + with: + ref: ${{ matrix.branch }} + - name: Update ${{ matrix.branch }} + run: | + git config --global user.email "julia-engineering@relational.ai" + git config --global user.name "RAI CI (GitHub Action Automation)" + + git remote add upstream https://github.com/JuliaLang/julia + git pull upstream ${{ matrix.branch }} + git push origin ${{ matrix.branch }} diff --git a/Compiler/src/reinfer.jl b/Compiler/src/reinfer.jl index 9da34afde6431..1f6b768f6ba53 100644 --- a/Compiler/src/reinfer.jl +++ b/Compiler/src/reinfer.jl @@ -33,6 +33,15 @@ struct VerifyMethodResultState result_maxworld::UInt end +# The result of `_methods_by_ftype(sig, nothing, lim, world, ...)` for one signature +struct VerifyCallLookup + lim::Int + world::UInt + result::Union{Nothing,Vector{Any}} + minworld::UInt + maxworld::UInt +end + # Container for all the work arrays struct VerifyMethodWorkspace # Arrays of different state categories @@ -50,6 +59,28 @@ struct VerifyMethodWorkspace end end +# The lookups stay valid for as long as no method is added or deleted, that is, while the world +# counter does not change. Then they can be shared between the images loaded in that time. +# Checked on every use. A cache that was saved into a system image is dropped on its first use +# in a process. Image loading is serialized (the require lock), which this relies on. +const VERIFY_CALL_CACHE = IdDict{Any,VerifyCallLookup}() +const VERIFY_CALL_CACHE_WORLD = RefValue{UInt}(0) +function verify_call_cache() + world = get_world_counter() + first_use = ccall(:jl_reinfer_cache_first_use, Cint, ()) != 0 + if first_use || VERIFY_CALL_CACHE_WORLD[] != world + empty!(VERIFY_CALL_CACHE) + VERIFY_CALL_CACHE_WORLD[] = world + end + return VERIFY_CALL_CACHE +end + +# Frees the cache, for callers that know they are done loading images for now. +function empty_verify_call_cache!() + empty!(VERIFY_CALL_CACHE) + return nothing +end + # Helper functions to create default states function VerifyMethodInitialState(codeinst::CodeInstance) mi = get_ci_mi(codeinst) @@ -573,7 +604,21 @@ function verify_call(@nospecialize(sig), expecteds::Core.SimpleVector, i::Int, n minworld = RefValue{UInt}(1) maxworld = RefValue{UInt}(typemax(UInt)) has_ambig = RefValue{Int32}(0) - result = _methods_by_ftype(sig, nothing, lim, world, #=ambig=#false, minworld, maxworld, has_ambig) + # Without invalidation logging the lookup result is only read below, so it can be shared + # between the edges with this signature. + use_cache = _jl_debug_method_invalidation[] === nothing + call_cache = verify_call_cache() + cached = use_cache ? get(call_cache, sig, nothing) : nothing + if cached !== nothing && cached.lim == lim && cached.world == world + result = cached.result + minworld[] = cached.minworld + maxworld[] = cached.maxworld + else + result = _methods_by_ftype(sig, nothing, lim, world, #=ambig=#false, minworld, maxworld, has_ambig) + if use_cache + call_cache[sig] = VerifyCallLookup(lim, world, result, minworld[], maxworld[]) + end + end if result === nothing empty!(matches) maxworld[] = 0 diff --git a/Compiler/src/ssair/passes.jl b/Compiler/src/ssair/passes.jl index f38068c181eec..848353aa1d1d7 100644 --- a/Compiler/src/ssair/passes.jl +++ b/Compiler/src/ssair/passes.jl @@ -880,6 +880,8 @@ function perform_lifting!(compact::IncrementalCompact, return Pair{Any, PhiNest}(stmt_val, PhiNest(visited_philikes, lifted_philikes, lifted_leaves, reverse_mapping, walker_callback)) end +const MAX_LIFTED_APPLY_TUPLE_LENGTH = 32 # same as the default `max_tuple_splat` + # Handle _apply_iterate calls: convert arguments to use `Core.svec`. # The behavior of `Core.svec` (with boxing) better matches the ABI of codegen. function lift_apply_args!(compact::IncrementalCompact, idx::Int, stmt::Expr) @@ -898,7 +900,10 @@ function lift_apply_args!(compact::IncrementalCompact, idx::Int, stmt::Expr) if svec_args === nothing # Fallback path: generate getfield calls for tuple elements tuple_length = length(arg_type.parameters) - if tuple_length > 0 && !isvarargtype(arg_type.parameters[tuple_length]) + # Longer tuples were deliberately not unrolled by the inliner (`max_tuple_splat`). + # Expanding them here costs one statement per element and call. + if 0 < tuple_length <= MAX_LIFTED_APPLY_TUPLE_LENGTH && + !isvarargtype(arg_type.parameters[tuple_length]) svec_args = Vector{Any}(undef, tuple_length + 1) for j in 1:tuple_length getfield_call = Expr(:call, GlobalRef(Core, :getfield), arg, j) @@ -1788,10 +1793,15 @@ function sroa_mutables!(ir::IRCode, defuses::IdDict{Int,Tuple{SPCSet,SSADefUse}} # show up in the nuses_total count. nleaves = length(defuse.uses) + length(defuse.defs) nuses = 0 + nintermediaries = 0 for iidx in intermediaries + # An intermediary that DCE already deleted no longer contributes its own use + # to `used_ssas[defidx]`, so it must not be subtracted again below. + ir[SSAValue(iidx)][:stmt] === nothing && continue nuses += used_ssas[iidx] + nintermediaries += 1 end - nuses_total = used_ssas[defidx] + nuses - length(intermediaries) + nuses_total = used_ssas[defidx] + nuses - nintermediaries all_eliminated = all_forwarded = true if nleaves ≠ nuses_total finalizer_useidx = find_finalizer_useidx(defuse) diff --git a/Compiler/src/typeinfer.jl b/Compiler/src/typeinfer.jl index 066a21a031ee8..05cac56aa578e 100644 --- a/Compiler/src/typeinfer.jl +++ b/Compiler/src/typeinfer.jl @@ -112,10 +112,8 @@ function finish!(interp::AbstractInterpreter, caller::InferenceState, validation ci = result.ci mi = result.linfo # if we aren't cached, we don't need this edge - # but our caller might, so let's just make it anyways. - # A tombstoned result is the exception: each new caller infers it again, so its - # backedges would pile up. Its callers depend on its edges directly instead. - if last(result.valid_worlds) >= validation_world && !result.tombstone + # but our caller might, so let's just make it anyways + if last(result.valid_worlds) >= validation_world # if we can record all of the backedges in the global reverse-cache, # we can now widen our applicability in the global cache too store_backedges(ci, edges) @@ -288,7 +286,6 @@ function finish_cycle(::AbstractInterpreter, frames::Vector{AbsIntState}, cyclei caller.time_caches = 0.0 end empty!(opt_cache) - share_tombstoned_cycle_edges!(frames, cycleid) cycletop = frames[cycleid]::InferenceState time_start = cycletop.time_start validation_world = get_world_counter() @@ -316,32 +313,6 @@ function finish_cycle(::AbstractInterpreter, frames::Vector{AbsIntState}, cyclei return nothing end -# Members of a cycle consume each other's results through `MethodInstance` edges. A -# tombstoned member has no backedges (see `finish!`), so it and every member that consumed -# it depend on the edges of the whole cycle directly. Other members reach those through -# the backedges of the members they consumed. -function share_tombstoned_cycle_edges!(frames::Vector{AbsIntState}, cycleid::Int) - sharers = IdSet{InferenceState}() - for frameid = cycleid:length(frames) - member = frames[frameid]::InferenceState - member.result.tombstone || continue - push!(sharers, member) - for (consumer, _) in member.cycle_backedges - push!(sharers, consumer) - end - end - isempty(sharers) && return nothing - cycle_edges = Any[] - for frameid = cycleid:length(frames) - append_edges!(cycle_edges, (frames[frameid]::InferenceState).edges) - end - for sharer in sharers - # `opt.inlining.edges` is this same vector, so this also reaches optimized members - append_edges!(sharer.edges, cycle_edges) - end - return nothing -end - function adjust_cycle_frame!(sv::InferenceState, cycle_valid_worlds::WorldRange, cycle_valid_effects::Effects) update_valid_age!(sv, cycle_valid_worlds) sv.ipo_effects = cycle_valid_effects @@ -834,45 +805,6 @@ function compute_edges!(sv::InferenceState) nothing end -# Number of entries of the edge record starting at `edges[i]`, see `ForwardToBackedgeIterator` -function edge_record_length(edges, i::Int) - item = edges[i] - item isa Int && return 2 + abs(item) # nmatches, atype, matches... - item isa Union{MethodInstance,CodeInstance,Core.Binding,Method} && return 1 - return 2 # invokesig or atype, followed by its target or `Core.methodtable` -end - -# Append the edge records of `from` that `edges` does not have yet. -function append_edges!(edges::Vector{Any}, from) - singles = IdSet{Any}() - multis = Int[] - i = 1 - while i <= length(edges) - n = edge_record_length(edges, i) - n == 1 ? push!(singles, edges[i]) : push!(multis, i) - i += n - end - i = 1 - while i <= length(from) - n = edge_record_length(from, i) - if n == 1 - if !(from[i] in singles) - push!(singles, from[i]) - push!(edges, from[i]) - end - elseif !any(multis) do j - edge_record_length(edges, j) == n && all(k -> edges[j+k] === from[i+k], 0:n-1) - end - push!(multis, length(edges) + 1) - for k = 0:n-1 - push!(edges, from[i+k]) - end - end - i += n - end - return edges -end - function record_slot_assign!(sv::InferenceState) # look at all assignments to slots # and union the set of types stored there @@ -1182,8 +1114,6 @@ function typeinf_edge(interp::AbstractInterpreter, method::Method, @nospecialize push!(caller.tasks, function get_infer_result(interp, caller) update_valid_age!(caller, frame.world.valid_worlds) local isinferred = is_inferred(frame) - # a tombstoned callee has no backedges, see `finish!` - isinferred && result.tombstone && append_edges!(caller.edges, frame.edges) local edge = isinferred ? edge_ci : nothing local effects = isinferred ? frame.result.ipo_effects : # effects are adjusted already within `finish` for ipo_effects adjust_effects(effects_for_cycle(frame.ipo_effects), method) @@ -1653,6 +1583,11 @@ function add_codeinsts_to_jit!(interp::AbstractInterpreter, ci, source_mode::UIn codegen === nothing && return ci workqueue = CompilationQueue(; interp) push!(workqueue, ci) + # Resolve every source first (this may run inference) and only then hand the code to the + # JIT, callees before callers. Once a caller is in the JIT, another thread that needs it + # completes it at once, and every callee that is not in the JIT yet is then called + # through a stub that boxes its arguments, for good. + toadd = Any[] while !isempty(workqueue) # ci_has_real_invoke(ci) && return ci # optimization: cease looping if ci happens to get compiled (not just jl_fptr_wait_for_compiled, but fully jl_is_compiled_codeinst) callee = pop!(workqueue) @@ -1691,7 +1626,11 @@ function add_codeinsts_to_jit!(interp::AbstractInterpreter, ci, source_mode::UIn callee = cached end end - ccall(:jl_add_codeinst_to_jit, Cvoid, (Any, Any), callee, src) + push!(toadd, callee) + push!(toadd, src) + end + for i in length(toadd):-2:2 + ccall(:jl_add_codeinst_to_jit, Cvoid, (Any, Any), toadd[i-1], toadd[i]) end return ci end diff --git a/Compiler/test/invalidation.jl b/Compiler/test/invalidation.jl index dbf01783d02db..3af37961de890 100644 --- a/Compiler/test/invalidation.jl +++ b/Compiler/test/invalidation.jl @@ -395,61 +395,3 @@ let mi = Base.method_instance(co_caller, (COBox,)) @test ci.owner === InvalidationTesterToken() @test ci.max_world == typemax(UInt) end - -# A result with limited accuracy is never cached, and every new caller infers it again. -# Its CodeInstance must not be registered as a backedge, or each caller adds another one, -# and invalidating `inner` walks all of them recursively (issue #63933). Here the inner -# `memo` call is widened against the outer one, which limits the cycle `p` <-> `q` and the -# self-recursive `r` in between. -module LimitedResultBackedges - struct Box{T} - x::T - end - struct Holder - b::Box - end - @noinline call(f) = f() - @noinline memo(f) = call(f) - inner(b::Box) = memo(() -> b.x) - p(x::Int, h::Holder) = x < 0 ? q(x, h) : 0 - q(x::Int, h::Holder) = x < -1 ? p(x, h) : inner(h.b) - r(x::Int, h::Holder) = x < -1 ? r(x + 1, h) : x < 0 ? inner(h.b) : 0 - const ncallers = 20 - for k in 1:ncallers - @eval $(Symbol(:pcaller, k))(h::Holder) = memo(() -> p($k, h)) - @eval $(Symbol(:rcaller, k))(h::Holder) = memo(() -> r($k, h)) - end -end -let M = LimitedResultBackedges - for k in 1:M.ncallers, caller in (:pcaller, :rcaller) - Base.return_types(getglobal(M, Symbol(caller, k)), (M.Holder,); interp=InvalidationTester()) - end - for callee in (M.p, M.q, M.r) - mi = Base.method_instance(callee, (Int, M.Holder)) - @test !isdefined(mi, :cache) - cis = filter(isdefined(mi, :backedges) ? mi.backedges : Any[]) do edge - edge isa Core.CodeInstance && edge.owner === InvalidationTesterToken() - end - @test !isempty(cis) - # only cached callers may be registered - @test all(cis) do ci - mi = Base.get_ci_mi(ci) - isdefined(mi, :cache) || return false - cached = mi.cache - while cached !== ci - isdefined(cached, :next) || return false - cached = cached.next - end - return true - end - end - callers = [Base.method_instance(getglobal(M, Symbol(caller, k)), (M.Holder,)).cache - for k in 1:M.ncallers for caller in (:pcaller, :rcaller)] - @test all(ci -> ci.owner === InvalidationTesterToken() && ci.max_world == typemax(UInt), callers) - invlog = ccall(:jl_debug_method_invalidation, Any, (Cint,), 1) - @eval M inner(b::Box) = memo(() -> b.x + 1) - ccall(:jl_debug_method_invalidation, Any, (Cint,), 0) - @test all(ci -> ci.max_world < typemax(UInt), callers) - depths = Int[x for x in invlog if x isa Int32] - @test maximum(depths) < M.ncallers -end diff --git a/Compiler/test/irpasses.jl b/Compiler/test/irpasses.jl index 513f0a69ea5f2..5177fea907e2d 100644 --- a/Compiler/test/irpasses.jl +++ b/Compiler/test/irpasses.jl @@ -2159,6 +2159,17 @@ let src = code_typed1((Vector{Any},)) do xs @test count(iscall((src, Core.svec)), src.code) == 1 end +# A tuple that is too long for the inliner to unroll (`max_tuple_splat`) must not be expanded +# into one `getfield` per element either: recursion over `Base.tail` is quadratic otherwise. +let src = code_typed1(Base.tail, (NTuple{40,Vector{Int}},)) + @test count(iscall((src, Core._apply_iterate)), src.code) == 1 + @test count(iscall((src, Core.svec)), src.code) == 0 + @test count(iscall((src, getfield)), src.code) == 0 +end +let src = code_typed1(Base.tail, (NTuple{32,Vector{Int}},)) + @test count(iscall((src, Core._apply_iterate)), src.code) == 0 +end + # Negative NewSSAValue ids must be preserved during compaction function f_57827(op, init, x) v = op(init, x) @@ -2174,3 +2185,21 @@ let rf = (acc, x) -> ifelse(x > acc[1], (x,), (acc[1],)) ir = first(only(Base.code_ircode(f_57827, (typeof(rf), Tuple{Float64}, Int64); optimize_until="CC: SROA"))) @test ir isa Compiler.IRCode end + +# SROA must not treat a `Core.Box` as non-escaping when the `π` node it reaches its +# only `getfield` through was already deleted by DCE: the box still escapes via the +# closure that captures it. +@noinline sroa_box_apply(f, xs) = map(f, xs) +function sroa_box_count_from(xs, start::Int) + ii = start + function bump(x::Int) + y = x + ii + ii += 1 + return y + end + bump(x) = x + return (sroa_box_apply(bump, xs), ii) +end +sroa_box_first_only(xs) = sroa_box_count_from(xs, 10)[1] +@test sroa_box_first_only(Any[1, 2]) == [11, 13] +@test sroa_box_count_from(Any[1, 2], 10) == ([11, 13], 12) diff --git a/VERSION b/VERSION index 80138e7146693..c7eda9365d8f0 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.13.4 +1.13.4+RAI diff --git a/base/options.jl b/base/options.jl index 4c1909c6f098e..41f09e57a5c8a 100644 --- a/base/options.jl +++ b/base/options.jl @@ -62,6 +62,7 @@ struct JLOptions heap_size_hint::UInt64 hard_heap_limit::UInt64 heap_target_increment::UInt64 + heap_target_increment_per_thread::UInt64 trace_compile_timing::Int8 trim::Int8 trace_eval::Int8 @@ -70,6 +71,7 @@ struct JLOptions gc_sweep_always_full::Int8 compress_sysimage::Int8 alert_on_critical_error::Int8 + safe_crash_log_file::Ptr{UInt8} end # This runs early in the sysimage != is not defined yet diff --git a/base/partr.jl b/base/partr.jl index 67287f8a0642d..9fae016c742ba 100644 --- a/base/partr.jl +++ b/base/partr.jl @@ -97,7 +97,7 @@ function multiq_sift_down(heap::taskheap, idx::Int32) child = Int(child) child > length(heap.tasks) && break if isassigned(heap.tasks, child) && - heap.tasks[child].priority < heap.tasks[idx].priority + heap.tasks[child].priority <= heap.tasks[idx].priority t = heap.tasks[idx] heap.tasks[idx] = heap.tasks[child] heap.tasks[child] = t diff --git a/deps/openblas.mk b/deps/openblas.mk index ac5f5145c84eb..0e9b28700889c 100644 --- a/deps/openblas.mk +++ b/deps/openblas.mk @@ -44,7 +44,7 @@ OPENBLAS_CFLAGS := -O2 # Decide whether to build for 32-bit or 64-bit arch ifneq ($(XC_HOST),) -OPENBLAS_BUILD_OPTS += OSNAME=$(OS) CROSS=1 HOSTCC=$(HOSTCC) CROSS_SUFFIX=$(CROSS_COMPILE) +OPENBLAS_BUILD_OPTS += OSNAME=$(OS) CROSS=1 HOSTCC="$(HOSTCC)" CROSS_SUFFIX=$(CROSS_COMPILE) endif ifeq ($(OS),WINNT) ifneq ($(ARCH),x86_64) diff --git a/src/aotcompile.cpp b/src/aotcompile.cpp index 0fd3724e93bc1..6d80bfa643575 100644 --- a/src/aotcompile.cpp +++ b/src/aotcompile.cpp @@ -1144,7 +1144,7 @@ static GlobalVariable *emit_ptls_table(Module &M, Type *T_size, Type *T_ptr) { // See src/processor.h for documentation about this table. Corresponds to jl_image_header_t. static GlobalVariable *emit_image_header(Module &M, unsigned threads, unsigned nfvars, unsigned ngvars) { - constexpr uint32_t version = 1; + constexpr uint32_t version = JL_IMAGE_FORMAT_VERSION; std::array header{ version, threads, diff --git a/src/gc-pages.c b/src/gc-pages.c index 04625d82e9b47..8d483df0d82a9 100644 --- a/src/gc-pages.c +++ b/src/gc-pages.c @@ -28,6 +28,28 @@ JL_DLLEXPORT uint64_t jl_get_pg_size(void) static int block_pg_cnt = DEFAULT_BLOCK_PG_ALLOC; +// Julia allocates large blocks (64M) with mmap. These are never +// unmapped but the underlying physical memory may be released +// with calls to madvise(MADV_DONTNEED). +static uint64_t poolmem_blocks_allocated_total = 0; + +JL_DLLEXPORT uint64_t jl_poolmem_blocks_allocated_total(void) +{ + return poolmem_blocks_allocated_total; +} + +JL_DLLEXPORT uint64_t jl_poolmem_bytes_allocated(void) +{ + return jl_atomic_load_relaxed(&gc_heap_stats.bytes_resident); +} + +JL_DLLEXPORT uint64_t jl_current_pg_count(void) +{ + assert(jl_page_size == GC_PAGE_SZ && "RAI fork of Julia should be running on platforms for which jl_page_size == GC_PAGE_SZ"); + size_t nb = jl_atomic_load_relaxed(&gc_heap_stats.bytes_resident); + return nb / GC_PAGE_SZ; // exact division +} + void jl_gc_init_page(void) { if (GC_PAGE_SZ * block_pg_cnt < jl_page_size) @@ -55,6 +77,11 @@ char *jl_gc_try_alloc_pages_(int pg_cnt) JL_NOTSAFEPOINT MAP_NORESERVE | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (mem == MAP_FAILED) return NULL; + +#ifdef MADV_NOHUGEPAGE + madvise(mem, pages_sz, MADV_NOHUGEPAGE); +#endif + #endif if (GC_PAGE_SZ > jl_page_size) // round data pointer up to the nearest gc_page_data-aligned @@ -62,6 +89,7 @@ char *jl_gc_try_alloc_pages_(int pg_cnt) JL_NOTSAFEPOINT mem = (char*)gc_page_data(mem + GC_PAGE_SZ - 1); jl_atomic_fetch_add_relaxed(&gc_heap_stats.bytes_mapped, pages_sz); jl_atomic_fetch_add_relaxed(&gc_heap_stats.bytes_resident, pages_sz); + poolmem_blocks_allocated_total++; // RAI-specific return mem; } @@ -187,7 +215,7 @@ void jl_gc_free_page(jl_gc_pagemeta_t *pg) JL_NOTSAFEPOINT } #ifdef _OS_WINDOWS_ VirtualFree(p, decommit_size, MEM_DECOMMIT); -#elif defined(MADV_FREE) +#elif 0 static int supports_madv_free = 1; if (supports_madv_free) { if (madvise(p, decommit_size, MADV_FREE) == -1) { diff --git a/src/gc-stacks.c b/src/gc-stacks.c index 9387c7fb065ec..55c4a470dd33e 100644 --- a/src/gc-stacks.c +++ b/src/gc-stacks.c @@ -72,8 +72,10 @@ static void *malloc_stack(size_t bufsz) JL_NOTSAFEPOINT munmap(stk, bufsz); return MAP_FAILED; } -# endif - +#ifdef MADV_NOHUGEPAGE + madvise(stk, bufsz, MADV_NOHUGEPAGE); +#endif +#endif jl_atomic_fetch_add_relaxed(&num_stack_mappings, 1); return stk; } diff --git a/src/gc-stock.c b/src/gc-stock.c index f85fb51489d17..064eafd2b54cb 100644 --- a/src/gc-stock.c +++ b/src/gc-stock.c @@ -570,15 +570,31 @@ void jl_gc_count_allocd(size_t sz) JL_NOTSAFEPOINT } // Only safe to update the heap inside the GC +// How many threads allocated since the last collection, counted by their share of the bytes: +// (sum a_i)^2 / sum a_i^2. One thread that allocates alone gives 1, n threads that allocate the +// same amount give n. Updated when a collection starts. +static double gc_alloc_participation = 1.0; + +// Experimental: the heap may grow by this many bytes per allocating thread before the next +// collection, if that is more than the heuristic allows. Set with +// --heap-target-increment-per-thread or JULIA_HEAP_TARGET_INCREMENT_PER_THREAD; 0 means off. +static uint64_t gc_heap_target_increment_per_thread = 0; + static void combine_thread_gc_counts(jl_gc_num_t *dest, int update_heap) JL_NOTSAFEPOINT { int gc_n_threads; jl_ptls_t* gc_all_tls_states; gc_n_threads = jl_atomic_load_acquire(&jl_n_threads); gc_all_tls_states = jl_atomic_load_relaxed(&jl_all_tls_states); + double sum_allocd = 0, sum_allocd_sq = 0; for (int i = 0; i < gc_n_threads; i++) { jl_ptls_t ptls = gc_all_tls_states[i]; if (ptls) { + double thread_allocd = (double)(jl_atomic_load_relaxed(&ptls->gc_tls_common.gc_num.allocd) + (int64_t)gc_num.interval); + if (thread_allocd > 0) { + sum_allocd += thread_allocd; + sum_allocd_sq += thread_allocd * thread_allocd; + } dest->allocd += (jl_atomic_load_relaxed(&ptls->gc_tls_common.gc_num.allocd) + gc_num.interval); dest->malloc += jl_atomic_load_relaxed(&ptls->gc_tls_common.gc_num.malloc); dest->realloc += jl_atomic_load_relaxed(&ptls->gc_tls_common.gc_num.realloc); @@ -594,6 +610,8 @@ static void combine_thread_gc_counts(jl_gc_num_t *dest, int update_heap) JL_NOTS } } } + if (update_heap && sum_allocd_sq > 0) + gc_alloc_participation = sum_allocd * sum_allocd / sum_allocd_sq; } static void reset_thread_gc_counts(void) JL_NOTSAFEPOINT @@ -3394,6 +3412,23 @@ static int _jl_gc_collect(jl_ptls_t ptls, jl_gc_collection_t collection) JL_NOTS target_heap = heap_size + jl_options.heap_target_increment; jl_atomic_store_relaxed(&gc_heap_stats.heap_target, target_heap); } + else if (gc_heap_target_increment_per_thread != 0) { + uint64_t mem_limit = max_total_memory; +#ifdef _P64 + if (total_mem != 0 && total_mem < mem_limit) + mem_limit = total_mem; +#endif + double growth = (double)gc_heap_target_increment_per_thread * gc_alloc_participation; + if (growth > (double)(mem_limit / 16)) + growth = (double)(mem_limit / 16); + uint64_t scaled = heap_size + (uint64_t)growth; + if (scaled > user_max) + scaled = user_max; + if (scaled > target_heap) { + target_heap = scaled; + jl_atomic_store_relaxed(&gc_heap_stats.heap_target, target_heap); + } + } if (sweep_full) { // these are the difference between the number of gc-perm bytes scanned // on the first collection after sweep_full, and the current scan @@ -3512,6 +3547,9 @@ static int _jl_gc_collect(jl_ptls_t ptls, jl_gc_collection_t collection) JL_NOTS return recollect; } +extern int jl_heartbeat_pause(void); +extern int jl_heartbeat_resume(void); + JL_DLLEXPORT void jl_gc_collect(jl_gc_collection_t collection) { JL_PROBE_GC_BEGIN(collection); @@ -3556,6 +3594,7 @@ JL_DLLEXPORT void jl_gc_collect(jl_gc_collection_t collection) // existence of the thread in the jl_n_threads count. // // TODO: concurrently queue objects + jl_heartbeat_pause(); jl_fence(); gc_n_threads = jl_atomic_load_acquire(&jl_n_threads); gc_all_tls_states = jl_atomic_load_relaxed(&jl_all_tls_states); @@ -3587,6 +3626,7 @@ JL_DLLEXPORT void jl_gc_collect(jl_gc_collection_t collection) gc_n_threads = 0; gc_all_tls_states = NULL; + jl_heartbeat_resume(); jl_safepoint_end_gc(); jl_gc_state_set(ptls, old_state, JL_GC_STATE_WAITING); JL_PROBE_GC_END(); @@ -3843,6 +3883,23 @@ void jl_gc_init(void) hint = min_heap_size_hint; jl_gc_set_max_memory(hint - mem_reserve); } + + uint64_t per_thread = jl_options.heap_target_increment_per_thread; + const char *per_thread_env = getenv("JULIA_HEAP_TARGET_INCREMENT_PER_THREAD"); + if (per_thread == 0 && per_thread_env != NULL && + (jl_parse_heap_size(per_thread_env, 0, &per_thread) != 0 || per_thread == 0)) { + jl_safe_printf("WARNING: ignoring invalid JULIA_HEAP_TARGET_INCREMENT_PER_THREAD=\"%s\"\n", per_thread_env); + per_thread = 0; + } + if (per_thread != 0 && jl_options.hard_heap_limit != 0) { + jl_safe_printf("WARNING: heap target increment per thread is ignored with --hard-heap-limit\n"); + per_thread = 0; + } + if (per_thread != 0 && jl_options.heap_target_increment != 0) { + jl_safe_printf("WARNING: heap target increment per thread is ignored with --heap-target-increment\n"); + per_thread = 0; + } + gc_heap_target_increment_per_thread = per_thread; } JL_DLLEXPORT void jl_gc_set_max_memory(uint64_t max_mem) @@ -4029,6 +4086,9 @@ void *jl_gc_perm_alloc_nolock(size_t sz, int zero, unsigned align, unsigned offs errno = last_errno; if (__unlikely(pool == MAP_FAILED)) return NULL; +#ifdef MADV_NOHUGEPAGE + madvise(pool, GC_PERM_POOL_SIZE, MADV_NOHUGEPAGE); +#endif #endif gc_perm_pool = (uintptr_t)pool; gc_perm_end = gc_perm_pool + GC_PERM_POOL_SIZE; diff --git a/src/gc-stock.h b/src/gc-stock.h index 5d04bf4639d50..6db36de61ab62 100644 --- a/src/gc-stock.h +++ b/src/gc-stock.h @@ -491,6 +491,9 @@ extern uv_sem_t gc_sweep_assists_needed; extern _Atomic(int) gc_n_threads_marking; extern _Atomic(int) gc_n_threads_sweeping_pools; extern _Atomic(int) n_threads_running; +extern _Atomic(int) gc_n_threads_sweeping_stacks; +extern _Atomic(int) gc_ptls_sweep_idx; +extern _Atomic(int) gc_stack_free_idx; extern uv_barrier_t thread_init_done; void gc_mark_queue_all_roots(jl_ptls_t ptls, jl_gc_markqueue_t *mq); void gc_mark_finlist_(jl_gc_markqueue_t *mq, jl_value_t *fl_parent, jl_value_t **fl_begin, jl_value_t **fl_end) JL_NOTSAFEPOINT; diff --git a/src/gf.c b/src/gf.c index d35af6bc0b42c..f8b7a0aad5116 100644 --- a/src/gf.c +++ b/src/gf.c @@ -124,6 +124,14 @@ void jl_call_tracer(tracer_cb callback, jl_value_t *tracee) } } +// Returns 1 the first time it is called in a process. `Compiler.ReinferUtils` uses it to drop a +// lookup cache that was saved into a system image. +JL_DLLEXPORT int jl_reinfer_cache_first_use(void) +{ + static _Atomic(int) used = 0; + return !jl_atomic_exchange(&used, 1); +} + /// ----- Definitions for various internal TypeMaps ----- /// static int8_t jl_cachearg_offset(void) @@ -134,13 +142,23 @@ static int8_t jl_cachearg_offset(void) /// ----- Insertion logic for special entries ----- /// +// The key of a specialization signature in `speckeyset`: the cached hash of the signature if it +// has one, otherwise the hash that the type cache computes for a type without a cached hash +// (it contains a Union or a type variable). Never 0, so every signature is indexed. Equal +// signatures written differently can get different keys, and then different MethodInstances, +// as in stock Julia for signatures without a cached hash. +uint_t jl_spec_index_hash(jl_value_t *sig) JL_NOTSAFEPOINT +{ + uint_t h = ((jl_datatype_t*)jl_unwrap_unionall(sig))->hash; + if (!h) + h = jl_type_hash_nofail(sig); + return h ? h : 1; +} + uint_t speccache_hash(size_t idx, jl_value_t *data) { jl_method_instance_t *ml = (jl_method_instance_t*)jl_svecref(data, idx); // This must always happen inside the lock - jl_value_t *sig = ml->specTypes; - if (jl_is_unionall(sig)) - sig = jl_unwrap_unionall(sig); - return ((jl_datatype_t*)sig)->hash; + return jl_spec_index_hash(ml->specTypes); } static int speccache_eq(size_t idx, const void *ty, jl_value_t *data, uint_t hv) @@ -153,32 +171,35 @@ static int speccache_eq(size_t idx, const void *ty, jl_value_t *data, uint_t hv) jl_value_t *sig = ml->specTypes; if (ty == sig) return 1; - uint_t h2 = ((jl_datatype_t*)(jl_is_unionall(sig) ? jl_unwrap_unionall(sig) : sig))->hash; - if (h2 != hv) + if (jl_spec_index_hash(sig) != hv) return 0; return jl_types_equal(sig, (jl_value_t*)ty); } // get or create the MethodInstance for a specialization +// +// Every entry of `specializations` is indexed in `speckeyset`, and entries are stored from the +// front and never move, so the index stays valid for every version of the array. The index is +// only appended to, after the entry is stored. static jl_method_instance_t *jl_specializations_get_linfo_(jl_method_t *m JL_PROPAGATES_ROOT, jl_value_t *type, jl_svec_t *sparams, jl_method_instance_t *mi_insert) { if (m->source == NULL && m->generator == NULL && jl_atomic_load_relaxed(&m->unspecialized) != NULL && m != jl_opaque_closure_method && !m->is_for_opaque_closure) return jl_atomic_load_relaxed(&m->unspecialized); // handle builtin methods jl_value_t *ut = jl_is_unionall(type) ? jl_unwrap_unionall(type) : type; JL_TYPECHK(specializations, datatype, ut); - uint_t hv = ((jl_datatype_t*)ut)->hash; + uint_t hv = jl_spec_index_hash(type); jl_genericmemory_t *speckeyset = NULL; jl_value_t *specializations = NULL; - size_t i = -1, cl = 0, lastcl; for (int locked = 0; locked < 2; locked++) { if (locked) { if (!sparams) // can't insert without knowing this return NULL; JL_LOCK(&m->writelock); } - lastcl = cl; + // load the array before the index: an entry in a singleton or in any array + // version is then in the index loaded after it + specializations = jl_atomic_load_acquire(&m->specializations); speckeyset = jl_atomic_load_acquire(&m->speckeyset); - specializations = jl_atomic_load_relaxed(&m->specializations); if (specializations == (jl_value_t*)jl_emptysvec) continue; if (!jl_is_svec(specializations)) { @@ -190,33 +211,14 @@ static jl_method_instance_t *jl_specializations_get_linfo_(jl_method_t *m JL_PRO } continue; } - cl = jl_svec_len(specializations); - if (hv) { - ssize_t idx = jl_smallintset_lookup(speckeyset, speccache_eq, type, specializations, hv, 0); - if (idx != -1) { - jl_method_instance_t *mi = (jl_method_instance_t*)jl_svecref(specializations, idx); - if (locked) - JL_UNLOCK(&m->writelock); - return mi; - } - } - else { - _Atomic(jl_method_instance_t*) *data = (_Atomic(jl_method_instance_t*)*)jl_svec_data(specializations); - JL_GC_PUSH1(&specializations); // clang-sa doesn't realize this loop uses specializations - // the last lastcl-i-1 elements are already checked when locked, so start search with the new elements only - for (i += cl - lastcl; i > 0; i--) { - jl_method_instance_t *mi = jl_atomic_load_relaxed(&data[i]); - if ((jl_value_t*)mi == jl_nothing) - break; - if (jl_types_equal(mi->specTypes, type)) { - if (locked) - JL_UNLOCK(&m->writelock); - JL_GC_POP(); - return mi; - } - } - // i points to the first unchecked element, or the place to insert - JL_GC_POP(); + JL_GC_PUSH1(&specializations); // comparing types can reach a safepoint + ssize_t idx = jl_smallintset_lookup(speckeyset, speccache_eq, type, specializations, hv, 0); + jl_method_instance_t *found = idx != -1 ? (jl_method_instance_t*)jl_svecref(specializations, idx) : NULL; + JL_GC_POP(); + if (found) { + if (locked) + JL_UNLOCK(&m->writelock); + return found; } } jl_method_instance_t *mi = mi_insert ? mi_insert : jl_get_specialized(m, type, sparams); @@ -225,52 +227,40 @@ static jl_method_instance_t *jl_specializations_get_linfo_(jl_method_t *m JL_PRO jl_gc_wb(m, mi); } else { - JL_GC_PUSH1(&mi); + JL_GC_PUSH2(&mi, &specializations); + size_t cl; if (!jl_is_svec(specializations)) { jl_method_instance_t *mi = (jl_method_instance_t*)specializations; - jl_value_t *type = mi->specTypes; - jl_value_t *ut = jl_is_unionall(type) ? jl_unwrap_unionall(type) : type; - uint_t hv = ((jl_datatype_t*)ut)->hash; cl = 7; - i = cl - 1; specializations = (jl_value_t*)jl_svec_fill(cl, jl_nothing); - jl_svecset(specializations, hv ? 0 : i--, mi); + jl_svecset(specializations, 0, mi); + // index the entry before publishing the array, since it already exists + jl_smallintset_insert(&m->speckeyset, (jl_value_t*)m, speccache_hash, 0, specializations); jl_atomic_store_release(&m->specializations, specializations); jl_gc_wb(m, specializations); - if (hv) - jl_smallintset_insert(&m->speckeyset, (jl_value_t*)m, speccache_hash, 0, specializations); - } - if (hv) { - _Atomic(jl_method_instance_t*) *data = (_Atomic(jl_method_instance_t*)*)jl_svec_data(specializations); - for (i = 0; i < cl; i++) { - jl_method_instance_t *mi = jl_atomic_load_relaxed(&data[i]); - if ((jl_value_t*)mi == jl_nothing) - break; - assert(!jl_types_equal(mi->specTypes, type)); - } - // i points at the place to insert } - if (hv ? (i + 1 >= cl || jl_svecref(specializations, i + 1) != jl_nothing) : (i <= 1 || jl_svecref(specializations, i - 2) != jl_nothing)) { + cl = jl_svec_len(specializations); + _Atomic(jl_method_instance_t*) *data = (_Atomic(jl_method_instance_t*)*)jl_svec_data(specializations); + size_t i = 0; + while (i < cl && (jl_value_t*)jl_atomic_load_relaxed(&data[i]) != jl_nothing) + i++; + // keep a free slot after the new entry (an array compacted for an image has none) + if (i + 1 >= cl) { size_t ncl = cl < 7 ? 7 : (cl*3)>>1; jl_svec_t *nc = jl_alloc_svec_uninit(ncl); - if (i > 0) - memcpy((char*)jl_svec_data(nc), jl_svec_data(specializations), sizeof(void*) * i); - for (int j = 0; j < ncl - cl; j++) - jl_svecset(nc, j+i, jl_nothing); - if (i < cl) - memcpy((char*)jl_svec_data(nc) + sizeof(void*) * (i + ncl - cl), - (char*)jl_svec_data(specializations) + sizeof(void*) * i, - sizeof(void*) * (cl - i)); + memcpy((char*)jl_svec_data(nc), jl_svec_data(specializations), sizeof(void*) * i); + for (size_t j = i; j < ncl; j++) + jl_svecset(nc, j, jl_nothing); specializations = (jl_value_t*)nc; jl_atomic_store_release(&m->specializations, specializations); jl_gc_wb(m, specializations); - if (!hv) - i += ncl - cl; } assert(jl_svecref(specializations, i) == jl_nothing); - jl_svecset(specializations, i, mi); - if (hv) - jl_smallintset_insert(&m->speckeyset, (jl_value_t*)m, speccache_hash, i, specializations); + // release: lock-free readers find the entry through the index, but the store of the + // MethodInstance must still order its initialization before it + jl_atomic_store_release(&((_Atomic(jl_value_t*)*)jl_svec_data(specializations))[i], (jl_value_t*)mi); + jl_gc_wb(specializations, mi); + jl_smallintset_insert(&m->speckeyset, (jl_value_t*)m, speccache_hash, i, specializations); JL_GC_POP(); } JL_UNLOCK(&m->writelock); // may gc @@ -2424,6 +2414,12 @@ struct _typename_add_backedge { jl_value_t *caller; }; +// Missing-method backedges are recorded as a two-level map +// typename => (sig => Vector{CodeInstance}) +// so that adding an edge is a hash lookup (jl_object_id hashes types +// structurally), rather than a linear scan through every recorded edge with +// `jl_types_equal`, and so that invalidation intersects each distinct +// signature only once, no matter how many callers recorded it. static void _typename_add_backedge(jl_typename_t *tn, int explct, void *env0) { struct _typename_add_backedge *env = (struct _typename_add_backedge*)env0; @@ -2432,41 +2428,33 @@ static void _typename_add_backedge(jl_typename_t *tn, int explct, void *env0) if (!explct) return; jl_genericmemory_t *allbackedges = jl_method_table->backedges; - jl_array_t *backedges = (jl_array_t*)jl_eqtable_get(allbackedges, (jl_value_t*)tn, NULL); - if (backedges == NULL) { - backedges = jl_alloc_vec_any(2); - JL_GC_PUSH1(&backedges); - jl_array_del_end(backedges, 2); - jl_genericmemory_t *newtable = jl_eqtable_put(allbackedges, (jl_value_t*)tn, (jl_value_t*)backedges, NULL); - JL_GC_POP(); - if (newtable != allbackedges) { - jl_method_table->backedges = newtable; - jl_gc_wb(jl_method_table, newtable); - } - } - // check if the edge is already present and avoid adding a duplicate - size_t i, l = jl_array_nrows(backedges); - // reuse an already cached instance of this type, if possible - // TODO: use jl_cache_type_(tt) like cache_method does, instead of this linear scan? - // TODO: use as_global_root and de-dup edges array too - for (i = 1; i < l; i += 2) { - if (jl_array_ptr_ref(backedges, i) == env->caller) { - if (jl_types_equal(jl_array_ptr_ref(backedges, i - 1), env->typ)) { - env->typ = jl_array_ptr_ref(backedges, i - 1); - return; // this edge already recorded - } - } - } - for (i = 1; i < l; i += 2) { - if (jl_array_ptr_ref(backedges, i) != env->caller) { - if (jl_types_equal(jl_array_ptr_ref(backedges, i - 1), env->typ)) { - env->typ = jl_array_ptr_ref(backedges, i - 1); - break; + jl_genericmemory_t *table = (jl_genericmemory_t*)jl_eqtable_get(allbackedges, (jl_value_t*)tn, NULL); + jl_array_t *callers = table == NULL ? NULL : (jl_array_t*)jl_eqtable_get(table, env->typ, NULL); + if (callers == NULL) { + // first edge for this signature: add a callers list to the + // per-typename table, creating the table itself if necessary + jl_array_t *newcallers = jl_alloc_vec_any(0); + jl_genericmemory_t *oldtable = table; + JL_GC_PUSH2(&newcallers, &table); + if (table == NULL) + table = (jl_genericmemory_t*)jl_an_empty_memory_any; + table = jl_eqtable_put(table, env->typ, (jl_value_t*)newcallers, NULL); + if (table != oldtable) { + jl_genericmemory_t *newtable = jl_eqtable_put(allbackedges, (jl_value_t*)tn, (jl_value_t*)table, NULL); + if (newtable != allbackedges) { + jl_method_table->backedges = newtable; + jl_gc_wb(jl_method_table, newtable); } } + JL_GC_POP(); + callers = newcallers; } - jl_array_ptr_1d_push(backedges, env->typ); - jl_array_ptr_1d_push(backedges, env->caller); + // avoid adding a duplicate edge; a single caller records each signature at + // most once in immediate succession, so checking the last entry suffices + size_t n = jl_array_nrows(callers); + if (n > 0 && jl_array_ptr_ref(callers, n - 1) == env->caller) + return; // this edge already recorded + jl_array_ptr_1d_push(callers, env->caller); } // add a backedge from a non-existent signature to caller @@ -2502,15 +2490,19 @@ static void _typename_invalidate_backedges(jl_typename_t *tn, int explct, void * JL_GC_PROMISE_ROOTED(env->type); JL_GC_PROMISE_ROOTED(env->isect); // isJuliaType considers jl_value_t** to be a julia object too JL_GC_PROMISE_ROOTED(env->isect2); // isJuliaType considers jl_value_t** to be a julia object too - jl_array_t *backedges = (jl_array_t*)jl_eqtable_get(jl_method_table->backedges, (jl_value_t*)tn, NULL); - if (backedges == NULL) + jl_genericmemory_t *table = (jl_genericmemory_t*)jl_eqtable_get(jl_method_table->backedges, (jl_value_t*)tn, NULL); + if (table == NULL) return; - jl_value_t **d = jl_array_ptr_data(backedges); - size_t i, na = jl_array_nrows(backedges); - size_t ins = 0; - for (i = 1; i < na; i += 2) { - jl_value_t *backedgetyp = d[i - 1]; + _Atomic(jl_value_t*) *tab = (_Atomic(jl_value_t*)*)table->ptr; + size_t i, na = table->length; + size_t alive = 0; + for (i = 0; i < na; i += 2) { + jl_value_t *backedgetyp = jl_atomic_load_relaxed(&tab[i]); + jl_value_t *callers = jl_atomic_load_relaxed(&tab[i + 1]); + if (callers == NULL) + continue; // empty or deleted slot JL_GC_PROMISE_ROOTED(backedgetyp); + JL_GC_PROMISE_ROOTED(callers); int missing = 0; if (jl_type_intersection2(backedgetyp, (jl_value_t*)env->type, env->isect, env->isect2)) { // See if the intersection was actually already fully @@ -2540,22 +2532,25 @@ static void _typename_invalidate_backedges(jl_typename_t *tn, int explct, void * } *env->isect = *env->isect2 = NULL; if (missing) { - jl_code_instance_t *backedge = (jl_code_instance_t*)d[i]; - JL_GC_PROMISE_ROOTED(backedge); - invalidate_code_instance(backedge, env->max_world, 0); - env->invalidated = 1; - if (_jl_debug_method_invalidation) - jl_array_ptr_1d_push(_jl_debug_method_invalidation, (jl_value_t*)backedgetyp); + size_t j, l = jl_array_nrows(callers); + for (j = 0; j < l; j++) { + jl_code_instance_t *backedge = (jl_code_instance_t*)jl_array_ptr_ref(callers, j); + JL_GC_PROMISE_ROOTED(backedge); + invalidate_code_instance(backedge, env->max_world, 0); + env->invalidated = 1; + if (_jl_debug_method_invalidation) + jl_array_ptr_1d_push(_jl_debug_method_invalidation, (jl_value_t*)backedgetyp); + } + // remove this entry (cf. `jl_eqtable_pop`) + jl_atomic_store_relaxed(&tab[i], jl_nothing); // clear the key + jl_atomic_store_relaxed(&tab[i + 1], NULL); // and the value } else { - d[ins++] = d[i - 1]; - d[ins++] = d[i - 0]; + alive++; } } - if (ins == 0) + if (alive == 0) jl_eqtable_pop(jl_method_table->backedges, (jl_value_t*)tn, NULL, NULL); - else if (na != ins) - jl_array_del_end(backedges, na - ins); } static void invalidate_missing_backedges(struct _typename_invalidate_backedge *env) @@ -2680,13 +2675,13 @@ static void jl_method_table_invalidate(jl_method_t *replaced, size_t max_world, assert(jl_atomic_load_relaxed(&jl_world_counter) == max_world); // Invalidate the backedges int invalidated = 0; - jl_value_t *specializations = jl_atomic_load_relaxed(&replaced->specializations); + jl_value_t *specializations = jl_atomic_load_acquire(&replaced->specializations); JL_GC_PUSH1(&specializations); if (!jl_is_svec(specializations)) specializations = (jl_value_t*)jl_svec1(specializations); size_t i, l = jl_svec_len(specializations); for (i = 0; i < l; i++) { - jl_method_instance_t *mi = (jl_method_instance_t*)jl_svecref(specializations, i); + jl_method_instance_t *mi = jl_atomic_load_acquire((_Atomic(jl_method_instance_t*)*)jl_svec_data(specializations) + i); if ((jl_value_t*)mi != jl_nothing) { invalidated = 1; invalidate_backedges(mi, max_world, "jl_method_table_disable"); @@ -3058,7 +3053,7 @@ void jl_method_table_activate(jl_typemap_entry_t *newentry) jl_gc_wb(m2, m2_interferences); } } - loctag = jl_atomic_load_relaxed(&m->specializations); // use loctag for a gcroot + loctag = jl_atomic_load_acquire(&m->specializations); // use loctag for a gcroot _Atomic(jl_method_instance_t*) *data; size_t l; if (jl_is_svec(loctag)) { @@ -3070,7 +3065,7 @@ void jl_method_table_activate(jl_typemap_entry_t *newentry) l = 1; } for (size_t i = 0; i < l; i++) { - jl_method_instance_t *mi = jl_atomic_load_relaxed(&data[i]); + jl_method_instance_t *mi = jl_atomic_load_acquire(&data[i]); if ((jl_value_t*)mi == jl_nothing) continue; jl_array_ptr_1d_push(oldmi, (jl_value_t*)mi); @@ -3113,7 +3108,7 @@ void jl_method_table_activate(jl_typemap_entry_t *newentry) continue; // Now examine if this caused any invalidations. - loctag = jl_atomic_load_relaxed(&m->specializations); // use loctag for a gcroot + loctag = jl_atomic_load_acquire(&m->specializations); // use loctag for a gcroot _Atomic(jl_method_instance_t*) *data; size_t l; if (jl_is_svec(loctag)) { @@ -3125,7 +3120,7 @@ void jl_method_table_activate(jl_typemap_entry_t *newentry) l = 1; } for (size_t i = 0; i < l; i++) { - jl_method_instance_t *mi = jl_atomic_load_relaxed(&data[i]); + jl_method_instance_t *mi = jl_atomic_load_acquire(&data[i]); if ((jl_value_t*)mi == jl_nothing) continue; if (jl_type_intersection2(type, mi->specTypes, &isect, &isect2)) { diff --git a/src/iddict.c b/src/iddict.c index 0a0895d048c32..d6f65dd3cd7fa 100644 --- a/src/iddict.c +++ b/src/iddict.c @@ -2,14 +2,27 @@ #define hash_size(h) (h->length / 2) -// compute empirical max-probe for a given size -#define max_probe(size) ((size) <= 1024 ? 16 : (size) >> 6) +// past this many probes an insert grows the table, unless it is under half full +#define IDTABLE_PROBE 8 #define keyhash(k) jl_object_id_(jl_typetagof(k), k) #define h2index(hv, sz) (size_t)(((hv) & ((sz)-1)) * 2) static inline int jl_table_assign_bp(jl_genericmemory_t **pa, jl_value_t *key, jl_value_t *val); +// Whether at least half of the `npairs` slots hold a value, estimated from up to 64 +// evenly spaced ones, since the count is kept only by the caller. A run of colliding +// keys mostly falls between the samples, so it does not make a sparse table grow, +// and doubling a table only from half full leaves it at least a quarter full. +static int idtable_half_full(_Atomic(jl_value_t*) *tab, size_t npairs) JL_NOTSAFEPOINT +{ + size_t step = npairs > 64 ? npairs / 64 : 1; + size_t i, n = 0, m = 0; + for (i = 0; i < npairs; i += step, m++) + n += jl_atomic_load_relaxed(&tab[2 * i + 1]) != NULL; + return n * 2 >= m; +} + JL_DLLEXPORT jl_genericmemory_t *jl_idtable_rehash(jl_genericmemory_t *a, size_t newsz) { size_t sz = a->length; @@ -41,7 +54,6 @@ static inline int jl_table_assign_bp(jl_genericmemory_t **pa, jl_value_t *key, j sz = hash_size(a); *pa = a; } - size_t maxprobe = max_probe(sz); _Atomic(jl_value_t*) *tab = (_Atomic(jl_value_t*)*) a->ptr; hv = keyhash(key); @@ -52,6 +64,7 @@ static inline int jl_table_assign_bp(jl_genericmemory_t **pa, jl_value_t *key, j orig = index; empty_slot = -1; + int tombstones = 0; do { jl_value_t *k2 = jl_atomic_load_relaxed(&tab[index]); if (k2 == NULL) { @@ -67,18 +80,28 @@ static inline int jl_table_assign_bp(jl_genericmemory_t **pa, jl_value_t *key, j } // `nothing` is our sentinel value for deletion, so need to keep searching if it's also our search key assert(key == jl_nothing); + } + if (jl_atomic_load_relaxed(&tab[index + 1]) == NULL) { // a tombstone + assert(k2 == jl_nothing); + tombstones = 1; if (empty_slot == -1) empty_slot = index; } - if (empty_slot == -1 && jl_atomic_load_relaxed(&tab[index + 1]) == NULL) { - assert(jl_atomic_load_relaxed(&tab[index]) == jl_nothing); - empty_slot = index; - } index = (index + 2) & (sz - 1); iter++; - } while (iter <= maxprobe && index != orig); - + } while (index != orig); + + // a lookup that misses scans as far as this did (`iter`), and nothing else empties a + // tombstone: past a long probe, grow a table at least half full, or rehash one with + // tombstones on the way at the same size + int same_size = 0; + if (empty_slot != -1 && iter > IDTABLE_PROBE) { + if (idtable_half_full(tab, sz / 2)) + empty_slot = -1; + else if (tombstones) + empty_slot = -1, same_size = 1; + } if (empty_slot != -1) { jl_atomic_store_release(&tab[empty_slot], key); jl_gc_wb(a, key); @@ -87,23 +110,17 @@ static inline int jl_table_assign_bp(jl_genericmemory_t **pa, jl_value_t *key, j return 1; } - /* table full */ - /* quadruple size, rehash, retry the insert */ - /* it's important to grow the table really fast; otherwise we waste */ - /* lots of time rehashing all the keys over and over. */ + /* table full, or a long probe: double it (or drop its tombstones) and retry */ sz = a -> length; if (sz < HT_N_INLINE) newsz = HT_N_INLINE; - else if (sz >= (1 << 19) || (sz <= (1 << 8))) - newsz = sz << 1; else - newsz = sz << 2; + newsz = same_size ? sz : sz << 1; *pa = jl_idtable_rehash(*pa, newsz); a = *pa; tab = (_Atomic(jl_value_t*)*) a->ptr; sz = hash_size(a); - maxprobe = max_probe(sz); } } @@ -113,13 +130,11 @@ inline _Atomic(jl_value_t*) *jl_table_peek_bp(jl_genericmemory_t *a, jl_value_t size_t sz = hash_size(a); if (sz == 0) return NULL; - size_t maxprobe = max_probe(sz); _Atomic(jl_value_t*) *tab = (_Atomic(jl_value_t*)*) a->ptr; uint_t hv = keyhash(key); size_t index = h2index(hv, sz); sz *= 2; size_t orig = index; - size_t iter = 0; do { jl_value_t *k2 = jl_atomic_load_relaxed(&tab[index]); // just to ensure the load doesn't get duplicated @@ -134,8 +149,7 @@ inline _Atomic(jl_value_t*) *jl_table_peek_bp(jl_genericmemory_t *a, jl_value_t } index = (index + 2) & (sz - 1); - iter++; - } while (iter <= maxprobe && index != orig); + } while (index != orig); return NULL; } @@ -192,5 +206,5 @@ size_t jl_eqtable_nextind(jl_genericmemory_t *t, size_t i) } #undef hash_size -#undef max_probe +#undef IDTABLE_PROBE #undef h2index diff --git a/src/idset.c b/src/idset.c index 1d66cf310d073..5bcacd39efc77 100644 --- a/src/idset.c +++ b/src/idset.c @@ -67,12 +67,37 @@ static ssize_t idset_compact(jl_genericmemory_t *keys) return rehash ? -j : j; } +// Find a free slot: gallop back from the end over the free tail, then bisect. +// Any NULL slot whose predecessor is used (or index 0) is a valid slot, so holes +// left by jl_idset_pop don't matter; returns l when the last slot is used. +static ssize_t idset_free_slot(jl_genericmemory_t *keys) JL_NOTSAFEPOINT +{ + ssize_t l = keys->length; + if (l == 0 || jl_genericmemory_ptr_ref(keys, l - 1) != NULL) + return l; + ssize_t hi = l - 1; // known NULL + ssize_t step = 1; + while (hi - step >= 0 && jl_genericmemory_ptr_ref(keys, hi - step) == NULL) { + hi -= step; + step <<= 1; + } + ssize_t lo = hi - step < 0 ? -1 : hi - step; // known used (or -1) + while (hi - lo > 1) { + ssize_t mid = lo + (hi - lo) / 2; + if (jl_genericmemory_ptr_ref(keys, mid) == NULL) + hi = mid; + else + lo = mid; + } + return hi; +} + +// Insert `key` into the first free slot at the end of the ordered set +// `keys` (growing and compacting are insertion-order-preserving). jl_genericmemory_t *jl_idset_put_key(jl_genericmemory_t *keys, jl_value_t *key, ssize_t *newidx) { ssize_t l = keys->length; - ssize_t i = l; - while (i > 0 && jl_genericmemory_ptr_ref(keys, i - 1) == NULL) - i--; + ssize_t i = idset_free_slot(keys); // i points to the place to insert *newidx = i; if (i == l) { diff --git a/src/init.c b/src/init.c index 0142365cad676..519eaf0f52694 100644 --- a/src/init.c +++ b/src/init.c @@ -197,7 +197,16 @@ void jl_task_frame_noreturn(jl_task_t *ct) JL_NOTSAFEPOINT; JL_DLLEXPORT void jl_exit(int exitcode) { jl_atexit_hook(exitcode); - exit(exitcode); + jl_exit_after_atexit_hook(exitcode); +} + +// Threads that were in a GC-safe region (e.g. compiling) keep running after jl_atexit_hook, +// and threads parked at a safepoint may hold locks. Running C++ static destructors and +// library finalizers next to them can deadlock or corrupt the heap, so skip them. +JL_DLLEXPORT void JL_NORETURN jl_exit_after_atexit_hook(int exitcode) +{ + fflush(NULL); + _exit(exitcode); } // cause this process to exit with WTERMSIG(signo), @@ -560,6 +569,8 @@ extern jl_mutex_t global_roots_lock; extern jl_mutex_t profile_show_peek_cond_lock; extern jl_mutex_t jl_typeinf_lock; +extern void jl_init_heartbeat(void); + static void restore_fp_env(void) { if (jl_set_zero_subnormals(0) || jl_set_default_nans(0)) { @@ -623,6 +634,11 @@ static NOINLINE void _finish_jl_init_(jl_image_buf_t sysimage, jl_ptls_t ptls, j jl_start_gc_threads(); uv_barrier_wait(&thread_init_done); + if (jl_base_module != NULL) { + // requires code in Base + jl_init_heartbeat(); + } + jl_gc_enable(1); if ((sysimage.kind != JL_IMAGE_KIND_NONE) && @@ -705,6 +721,12 @@ JL_DLLEXPORT void jl_init_(jl_image_buf_t sysimage) init_global_mutexes(); jl_precompile_toplevel_module = NULL; ios_set_io_wait_func = jl_set_io_wait; +#ifdef _OS_LINUX_ + // Keep libuv's fs requests off io_uring: in libuv 1.48 uv__iou_submit has no full barrier + // before it checks IORING_SQ_NEED_WAKEUP, so a request can stay unsubmitted while the SQPOLL + // thread sleeps. libuv 1.49 made SQPOLL opt-in (libuv#4492). An explicit setting wins. + setenv("UV_USE_IO_URING", "0", 0); +#endif jl_io_loop = uv_default_loop(); // this loop will internal events (spawning process etc.), // best to call this first, since it also initializes libuv jl_init_uv(); @@ -752,6 +774,15 @@ JL_DLLEXPORT void jl_init_(jl_image_buf_t sysimage) if (jl_options.handle_signals == JL_OPTIONS_HANDLE_SIGNALS_ON) jl_install_default_signal_handlers(); +#if (defined(_OS_LINUX_) && defined(_CPU_X86_64_)) || (defined(_OS_DARWIN_) && defined(_CPU_AARCH64_)) + if (jl_options.safe_crash_log_file != NULL) { + jl_sig_fd = open(jl_options.safe_crash_log_file, O_WRONLY | O_CREAT | O_APPEND, 0600); + if (jl_sig_fd == -1) { + jl_error("fatal error: could not open safe crash log file for writing"); + } + } +#endif + jl_gc_init(); arraylist_new(&jl_linkage_blobs, 0); diff --git a/src/jitlayers.cpp b/src/jitlayers.cpp index b2125b8012852..6418b397a2376 100644 --- a/src/jitlayers.cpp +++ b/src/jitlayers.cpp @@ -336,8 +336,11 @@ static std::mutex engine_lock; static std::condition_variable engine_wait; static int threads_in_compiler_phase; // the TSM for each codeinst -static SmallVector sharedmodules; -static DenseMap emittedmodules; + // These hold ThreadSafeModules, whose destructors take the lock of their context. They are + // never destroyed: at exit the other threads are suspended at a safepoint, possibly while + // compiling with such a lock held, and a static destructor would then wait for it forever. +static auto &sharedmodules = *new SmallVector(); +static auto &emittedmodules = *new DenseMap(); // the invoke and specsig function names in the JIT static DenseMap invokenames; // everything that any thread wants to compile right now @@ -350,7 +353,7 @@ static DenseMap> complet // really need this once JITLink is available everywhere, since every module // is automatically complete, and we can emit any required fixups later as a // separate module) -static DenseMap> incompletemodules; +static auto &incompletemodules = *new DenseMap>(); // the set of incoming unresolved edges resolved by a codeinstance static DenseMap> incomplete_rgraph; diff --git a/src/jl_exported_funcs.inc b/src/jl_exported_funcs.inc index c5372f5e0739b..0e7916eb4c113 100644 --- a/src/jl_exported_funcs.inc +++ b/src/jl_exported_funcs.inc @@ -122,6 +122,7 @@ XX(jl_exception_occurred) \ XX(jl_excstack_state) \ XX(jl_exit) \ + XX(jl_exit_after_atexit_hook) \ XX(jl_exit_on_sigint) \ XX(jl_exit_threaded_region) \ XX(jl_field_index) \ diff --git a/src/jl_uv.c b/src/jl_uv.c index 5c2262f1da73b..b3c6b3142c7bd 100644 --- a/src/jl_uv.c +++ b/src/jl_uv.c @@ -18,6 +18,7 @@ #include "errno.h" #include #include +#include #endif #include "julia.h" @@ -824,6 +825,83 @@ JL_DLLEXPORT int jl_printf(uv_stream_t *s, const char *format, ...) return c; } +STATIC_INLINE int copystp(char *dest, const char *src) +{ + char *d = stpcpy(dest, src); + return (int)(d - dest); +} + +// RAI-specific +STATIC_INLINE void write_to_safe_crash_log(char *buf) JL_NOTSAFEPOINT +{ + int buflen = strlen(buf); + // Our telemetry on SPCS expects a JSON object per line. + // We ignore write failures because there is nothing we can do. + // We'll use a 2K byte buffer: 69 bytes for JSON message decorations, + // 1 byte for the terminating NUL character, and 3 bytes for an + // ellipsis if we have to truncate the message leaves `max_b` bytes + // for the message. + const int wbuflen = 2048; + const int max_b = wbuflen - 70 - 3; + char wbuf[wbuflen]; + bzero(wbuf, wbuflen); + int wlen = 0; + + // JSON preamble (32 bytes) + wlen += copystp(&wbuf[wlen], "\n{\"level\":\"Error\", \"timestamp\":\""); + + // Timestamp (19 bytes) + struct timeval tv; + struct tm* tm_info; + gettimeofday(&tv, NULL); + tm_info = gmtime(&tv.tv_sec); + wlen += strftime(&wbuf[wlen], 42, "%Y-%m-%dT%H:%M:%S", tm_info); + sprintf(&wbuf[wlen], ".%03ld", (long)tv.tv_usec / 1000); + wlen += 4; + + // JSON preamble to message (15 bytes) + wlen += copystp(&wbuf[wlen], "\", \"message\": \""); + + // Message + // Each iteration will advance wlen by 1 or 2 + for (size_t i = 0; i < buflen; i++) { + // Truncate the message if the write buffer is full + if (wlen == max_b || wlen == max_b - 1) { + wlen += copystp(&wbuf[wlen], "..."); + break; + } + switch (buf[i]) { + case '"': + wlen += copystp(&wbuf[wlen], "\\\""); + break; + case '\b': + wlen += copystp(&wbuf[wlen], "\\b"); + break; + case '\n': + wlen += copystp(&wbuf[wlen], "\\n"); + break; + case '\r': + wlen += copystp(&wbuf[wlen], "\\r"); + break; + case '\t': + wlen += copystp(&wbuf[wlen], "\\t"); + break; + case '\\': + wlen += copystp(&wbuf[wlen], "\\\\"); + break; + default: + wbuf[wlen++] = buf[i]; + break; + } + } + // JSON completion (3 bytes) + wlen += copystp(&wbuf[wlen], "\"}\n"); + write(jl_sig_fd, wbuf, wlen); + fdatasync(jl_sig_fd); +} + +extern int jl_inside_heartbeat_thread(void); + static void jl_safe_vfprintf(ios_t *s, const char *fmt, va_list args) JL_NOTSAFEPOINT { char buf[1000]; @@ -836,6 +914,12 @@ static void jl_safe_vfprintf(ios_t *s, const char *fmt, va_list args) JL_NOTSAFE vsnprintf(buf, sizeof(buf), fmt, args); buf[999] = '\0'; + // order is important here: we want to ensure that the threading infra + // has been initialized before we start trying to print to the + // safe crash log file + if (s == ios_safe_stderr && jl_sig_fd != 0 && (jl_inside_signal_handler() || jl_inside_heartbeat_thread())) { + write_to_safe_crash_log(buf); + } if (!ios_write(s, buf, strlen(buf))) { // nothing we can do; ignore the failure } diff --git a/src/jlapi.c b/src/jlapi.c index 4da5a2d3b468e..fb3fdb5c4de2c 100644 --- a/src/jlapi.c +++ b/src/jlapi.c @@ -1151,6 +1151,7 @@ JL_DLLEXPORT int jl_repl_entrypoint(int argc, char *argv[]) } int ret = true_main(argc, (char**)new_argv); jl_atexit_hook(ret); + jl_exit_after_atexit_hook(ret); return ret; } diff --git a/src/jloptions.c b/src/jloptions.c index 84dece8d94c81..79729a3500151 100644 --- a/src/jloptions.c +++ b/src/jloptions.c @@ -34,16 +34,16 @@ JL_DLLEXPORT const char *jl_get_default_sysimg_path(void) return &system_image_path[1]; } -/* This function is also used by gc-stock.c to parse the - * JULIA_HEAP_SIZE_HINT environment variable. */ -uint64_t parse_heap_size_option(const char *optarg, const char *option_name, int allow_pct) +// Returns 0 on success, -1 for an invalid value and 1 for a value that does not fit in 64 bits +// (with *out set to UINT64_MAX). +int jl_parse_heap_size(const char *str, int allow_pct, uint64_t *out) { long double value = 0.0; char unit[4] = {0}; - int nparsed = sscanf(optarg, "%Lf%3s", &value, unit); - if (nparsed == 0 || strlen(unit) > 2 || (strlen(unit) == 2 && ascii_tolower(unit[1]) != 'b')) { - jl_errorf("julia: invalid argument to %s (%s)", option_name, optarg); - } + *out = 0; + int nparsed = sscanf(str, "%Lf%3s", &value, unit); + if (nparsed == 0 || strlen(unit) > 2 || (strlen(unit) == 2 && ascii_tolower(unit[1]) != 'b')) + return -1; uint64_t multiplier = 1ull; switch (ascii_tolower(unit[0])) { case '\0': @@ -62,9 +62,7 @@ uint64_t parse_heap_size_option(const char *optarg, const char *option_name, int multiplier <<= 40; break; case '%': - if (allow_pct) { - if (value > 100) - jl_errorf("julia: invalid percentage specified in %s", option_name); + if (allow_pct && value <= 100) { uint64_t mem = uv_get_total_memory(); uint64_t cmem = uv_get_constrained_memory(); if (cmem > 0 && cmem < mem) @@ -72,16 +70,30 @@ uint64_t parse_heap_size_option(const char *optarg, const char *option_name, int multiplier = mem/100; break; } + return -1; default: - jl_errorf("julia: invalid argument to %s (%s)", option_name, optarg); - break; + return -1; } long double sz = value * multiplier; - if (isnan(sz) || sz < 0) { - jl_errorf("julia: invalid argument to %s (%s)", option_name, optarg); - } + if (isnan(sz) || sz < 0) + return -1; const long double limit = ldexpl(1.0, 64); // UINT64_MAX + 1 - return sz < limit ? (uint64_t)sz : UINT64_MAX; + if (sz >= limit) { + *out = UINT64_MAX; + return 1; + } + *out = (uint64_t)sz; + return 0; +} + +/* This function is also used by gc-stock.c to parse the + * JULIA_HEAP_SIZE_HINT environment variable. */ +uint64_t parse_heap_size_option(const char *optarg, const char *option_name, int allow_pct) +{ + uint64_t sz; + if (jl_parse_heap_size(optarg, allow_pct, &sz) < 0) + jl_errorf("julia: invalid argument to %s (%s)", option_name, optarg); + return sz; } static int jl_options_initialized = 0; @@ -155,6 +167,7 @@ JL_DLLEXPORT void jl_init_options(void) 0, // heap-size-hint 0, // hard-heap-limit 0, // heap-target-increment + 0, // heap-target-increment-per-thread 0, // trace_compile_timing JL_TRIM_NO, // trim 0, // trace-eval @@ -163,6 +176,7 @@ JL_DLLEXPORT void jl_init_options(void) 0, // gc_sweep_always_full 0, // compress_sysimage 0, // alert_on_critical_error + NULL, // safe_crash_log_file }; jl_options_initialized = 1; } @@ -358,6 +372,15 @@ static const char opts_hidden[] = " a number of bytes, optionally in units of:\n" " B, K (kibibytes), M (mebibytes), G (gibibytes)\n" " or T (tebibytes).\n" + " --heap-target-increment-per-thread=[]\n" + " Let the heap grow by this much per thread that\n" + " allocated since the last collection, if that is\n" + " more than the heuristic allows. The growth stays\n" + " below 1/16 of the memory limit and below the\n" + " --heap-size-hint limit. Ignored with\n" + " --hard-heap-limit or --heap-target-increment.\n" + " Also read from the environment variable\n" + " JULIA_HEAP_TARGET_INCREMENT_PER_THREAD.\n" " --gc-sweep-always-full Makes the GC always do a full sweep of the heap\n" ; @@ -409,6 +432,7 @@ JL_DLLEXPORT void jl_parse_opts(int *argcp, char ***argvp) opt_heap_size_hint, opt_hard_heap_limit, opt_heap_target_increment, + opt_heap_target_increment_per_thread, opt_gc_sweep_always_full, opt_gc_threads, opt_permalloc_pkgimg, @@ -416,6 +440,7 @@ JL_DLLEXPORT void jl_parse_opts(int *argcp, char ***argvp) opt_trace_eval, opt_experimental_features, opt_compress_sysimage, + opt_safe_crash_log_file, }; static const char* const shortopts = "+vhqH:e:E:L:J:C:it:p:O:g:m:"; static const struct option longopts[] = { @@ -485,10 +510,12 @@ JL_DLLEXPORT void jl_parse_opts(int *argcp, char ***argvp) { "heap-size-hint", required_argument, 0, opt_heap_size_hint }, { "hard-heap-limit", required_argument, 0, opt_hard_heap_limit }, { "heap-target-increment", required_argument, 0, opt_heap_target_increment }, + { "heap-target-increment-per-thread", required_argument, 0, opt_heap_target_increment_per_thread }, { "gc-sweep-always-full", no_argument, 0, opt_gc_sweep_always_full }, { "trim", optional_argument, 0, opt_trim }, { "compress-sysimage", required_argument, 0, opt_compress_sysimage }, { "trace-eval", optional_argument, 0, opt_trace_eval }, + { "safe-crash-log-file", required_argument, 0, opt_safe_crash_log_file }, { 0, 0, 0, 0 } }; @@ -1021,6 +1048,11 @@ JL_DLLEXPORT void jl_parse_opts(int *argcp, char ***argvp) if (jl_options.heap_target_increment == 0) jl_errorf("julia: invalid memory size specified in --heap-target-increment=[]"); break; + case opt_heap_target_increment_per_thread: + if (optarg == NULL || jl_parse_heap_size(optarg, 0, &jl_options.heap_target_increment_per_thread) != 0 || + jl_options.heap_target_increment_per_thread == 0) + jl_errorf("julia: invalid memory size specified in --heap-target-increment-per-thread=[]"); + break; case opt_gc_threads: { errno = 0; @@ -1089,6 +1121,11 @@ JL_DLLEXPORT void jl_parse_opts(int *argcp, char ***argvp) else jl_errorf("julia: invalid argument to --task-metrics={yes|no} (%s)", optarg); break; + case opt_safe_crash_log_file: + jl_options.safe_crash_log_file = strdup(optarg); + if (jl_options.safe_crash_log_file == NULL) + jl_error("julia: failed to allocate memory for --safe-crash-log-file"); + break; case opt_compress_sysimage: if (!strcmp(optarg,"yes")) jl_options.compress_sysimage = 1; diff --git a/src/jloptions.h b/src/jloptions.h index 3a410f42d4d30..8f3acbbfd8f59 100644 --- a/src/jloptions.h +++ b/src/jloptions.h @@ -66,6 +66,7 @@ typedef struct { uint64_t heap_size_hint; uint64_t hard_heap_limit; uint64_t heap_target_increment; + uint64_t heap_target_increment_per_thread; int8_t trace_compile_timing; int8_t trim; int8_t trace_eval; @@ -74,6 +75,7 @@ typedef struct { int8_t gc_sweep_always_full; int8_t compress_sysimage; int8_t alert_on_critical_error; + const char *safe_crash_log_file; } jl_options_t; #endif diff --git a/src/jltypes.c b/src/jltypes.c index 885f87c769fec..fc839cbc6c7e4 100644 --- a/src/jltypes.c +++ b/src/jltypes.c @@ -30,7 +30,9 @@ struct jl_internal_global internal_global; #endif // compute empirical max-probe for a given size -#define max_probe(size) ((size) <= 1024 ? 16 : (size) >> 6) +// The table grows when an insert needs more than this many probes, unless it is less than half +// full. Without the cap a large table fills to about 95% before it grows, and lookups walk long runs. +#define max_probe(size) ((size) <= 1024 ? 16 : (size) <= 4096 ? (size) >> 6 : 64) #define h2index(hv, sz) (size_t)((hv) & ((sz)-1)) // --- type properties and predicates --- @@ -1039,11 +1041,9 @@ static jl_datatype_t *lookup_type_set(jl_svec_t *cache, jl_value_t **key, size_t size_t sz = jl_svec_len(cache); if (sz == 0) return NULL; - size_t maxprobe = max_probe(sz); _Atomic(jl_datatype_t*) *tab = (_Atomic(jl_datatype_t*)*)jl_svec_data(cache); size_t index = h2index(hv, sz); size_t orig = index; - size_t iter = 0; do { jl_datatype_t *val = jl_atomic_load_relaxed(&tab[index]); if ((jl_value_t*)val == jl_nothing) @@ -1051,8 +1051,7 @@ static jl_datatype_t *lookup_type_set(jl_svec_t *cache, jl_value_t **key, size_t if (val->hash == hv && typekey_eq(val, key, n)) return val; index = (index + 1) & (sz - 1); - iter++; - } while (iter <= maxprobe && index != orig); + } while (index != orig); return NULL; } @@ -1062,11 +1061,9 @@ static jl_datatype_t *lookup_type_setvalue(jl_svec_t *cache, jl_value_t *key1, j size_t sz = jl_svec_len(cache); if (sz == 0) return NULL; - size_t maxprobe = max_probe(sz); _Atomic(jl_datatype_t*) *tab = (_Atomic(jl_datatype_t*)*)jl_svec_data(cache); size_t index = h2index(hv, sz); size_t orig = index; - size_t iter = 0; do { jl_datatype_t *val = jl_atomic_load_relaxed(&tab[index]); if ((jl_value_t*)val == jl_nothing) @@ -1074,8 +1071,7 @@ static jl_datatype_t *lookup_type_setvalue(jl_svec_t *cache, jl_value_t *key1, j if (val->hash == hv && typekeyvalue_eq(val, key1, key, n, leaf)) return val; index = (index + 1) & (sz - 1); - iter++; - } while (iter <= maxprobe && index != orig); + } while (index != orig); return NULL; } @@ -1178,7 +1174,24 @@ static int cache_insert_type_set_(jl_svec_t *a, jl_datatype_t *val, uint_t hv, i iter++; } while (iter <= maxprobe && index != orig); - return 0; + // Types with equal hashes can form a run longer than any probe limit, which no table size + // fixes. Lookups probe until an empty slot, so place the type past the limit unless the + // table is at least half full. + if (index == orig) + return 0; + size_t used = 0; + for (size_t i = 0; i < sz; i++) + used += jl_atomic_load_relaxed(&tab[i]) != jl_nothing; + if (2 * used >= sz) + return 0; + while (jl_atomic_load_relaxed(&tab[index]) != jl_nothing) + index = (index + 1) & (sz - 1); + if (atomic) + jl_atomic_store_release(&tab[index], (jl_value_t*)val); + else + jl_atomic_store_relaxed(&tab[index], (jl_value_t*)val); + jl_gc_wb(a, val); + return 1; } static void cache_insert_type_set(jl_datatype_t *val, uint_t hv) @@ -1209,9 +1222,15 @@ static void cache_insert_type_set(jl_datatype_t *val, uint_t hv) jl_svec_t *cache_rehash_set(jl_svec_t *a, size_t newsz) { - newsz = newsz ? next_power_of_two(newsz) : 0; jl_value_t **ol = jl_svec_data(a); size_t sz = jl_svec_len(a); + size_t used = 0; + for (size_t i = 0; i < sz; i++) + used += ol[i] != jl_nothing; + // inserts place types past the probe limit only while the table is less than half full + if (newsz < 2 * used) + newsz = 2 * used; + newsz = newsz ? next_power_of_two(newsz) : 0; while (1) { size_t i; jl_svec_t *newa = jl_svec_fill(newsz, jl_nothing); @@ -1791,6 +1810,14 @@ JL_DLLEXPORT uintptr_t jl_type_hash(jl_value_t *v) JL_NOTSAFEPOINT return type_hash(v, &failed); } +// Like `jl_type_hash`, but also computes a hash for types that have no cached one (they +// contain a Union or a type variable). Equal types get equal values. +uintptr_t jl_type_hash_nofail(jl_value_t *v) JL_NOTSAFEPOINT +{ + int failed = 1; + return type_hash(v, &failed); +} + static unsigned typekey_hash(jl_typename_t *tn, jl_value_t **key, size_t n, int nofail) JL_NOTSAFEPOINT { if (tn == jl_type_typename && key[0] == jl_bottom_type) diff --git a/src/julia.h b/src/julia.h index 27eb3cc51004b..e78e3f38b42e4 100644 --- a/src/julia.h +++ b/src/julia.h @@ -2199,6 +2199,7 @@ JL_DLLEXPORT void jl_atexit_hook(int status); JL_DLLEXPORT void jl_task_wait_empty(void); JL_DLLEXPORT void jl_postoutput_hook(void); JL_DLLEXPORT void JL_NORETURN jl_exit(int status); +JL_DLLEXPORT void JL_NORETURN jl_exit_after_atexit_hook(int status); JL_DLLEXPORT void JL_NORETURN jl_raise(int signo); JL_DLLEXPORT const char *jl_pathname_for_handle(void *handle) JL_NOTSAFEPOINT; JL_DLLEXPORT const char *jl_pathname_for_symbol(void *symbol) JL_NOTSAFEPOINT; @@ -2560,6 +2561,7 @@ JL_DLLEXPORT void jl_parse_opts(int *argcp, char ***argvp); JL_DLLEXPORT char *jl_format_filename(const char *output_pattern) JL_NOTSAFEPOINT; uint64_t parse_heap_size_option(const char *optarg, const char *option_name, int allow_pct); +int jl_parse_heap_size(const char *str, int allow_pct, uint64_t *out); // Set julia-level ARGS array according to the arguments provided in // argc/argv diff --git a/src/julia_internal.h b/src/julia_internal.h index 82bac338847a1..8f6d0013569e3 100644 --- a/src/julia_internal.h +++ b/src/julia_internal.h @@ -267,6 +267,7 @@ extern volatile size_t profile_bt_size_max; extern volatile size_t profile_bt_size_cur; extern volatile int profile_running; extern volatile int profile_all_tasks; +extern int heartbeat_tid; // Mostly used to ensure we skip this thread in the CPU profiler. XXX: not implemented on Windows // Ensures that we can safely read the `live_tasks`field of every TLS when profiling. // We want to avoid the case that a GC gets interleaved with `jl_profile_task` and shrinks // the `live_tasks` array while we are reading it or frees tasks that are being profiled. @@ -282,6 +283,7 @@ extern uv_mutex_t bt_data_prof_lock; #define PROFILE_STATE_THREAD_NOT_SLEEPING (1) #define PROFILE_STATE_THREAD_SLEEPING (2) #define PROFILE_STATE_WALL_TIME_PROFILING (3) +extern _Atomic(int) n_threads_running; void jl_profile_task(void); #if defined(_OS_WINDOWS_) && defined(_CPU_X86_64_) JL_DLLEXPORT void jl_set_profile_abort_ptr(_Atomic(int) *abort_ptr) JL_NOTSAFEPOINT; @@ -844,6 +846,33 @@ JL_CALLABLE(jl_f_tuple); void jl_install_default_signal_handlers(void); void restore_signals(void); void jl_install_thread_signal_handler(jl_ptls_t ptls); +extern const size_t sig_stack_size; +STATIC_INLINE int jl_inside_signal_handler(void) +{ +#if (defined(_OS_LINUX_) && defined(_CPU_X86_64_)) || (defined(_OS_DARWIN_) && defined(_CPU_AARCH64_)) + // Read the stack pointer + size_t sp; +#if defined(_OS_LINUX_) && defined(_CPU_X86_64_) + __asm__ __volatile__("movq %%rsp, %0" : "=r"(sp)); +#elif defined(_OS_DARWIN_) && defined(_CPU_AARCH64_) + __asm__ __volatile__("mov %0, sp" : "=r"(sp)); +#endif + // Check if the stack pointer is within the signal stack + jl_task_t *ct = jl_get_current_task(); + if (ct == NULL || ct->ptls == NULL) + return 0; + char *stk = (char*)ct->ptls->signal_stack; + if (stk == NULL) + return 0; + size_t ssize = ct->ptls->signal_stack_size ? ct->ptls->signal_stack_size : sig_stack_size; + // One guard page for signal_stack. + return (char*)sp >= stk - jl_page_size && (char*)sp <= stk + ssize; +#else + return 0; +#endif +} +// File-descriptor for safe logging on signal handling +extern int jl_sig_fd; extern uv_loop_t *jl_io_loop; JL_DLLEXPORT void jl_uv_flush(uv_stream_t *stream); @@ -900,6 +929,7 @@ int jl_find_union_component(jl_value_t *haystack, jl_value_t *needle, unsigned * jl_datatype_t *jl_new_abstracttype(jl_value_t *name, jl_module_t *module, jl_datatype_t *super, jl_svec_t *parameters); jl_datatype_t *jl_new_uninitialized_datatype(void); +uintptr_t jl_type_hash_nofail(jl_value_t *v) JL_NOTSAFEPOINT; void jl_precompute_memoized_dt(jl_datatype_t *dt, int cacheable); JL_DLLEXPORT jl_datatype_t *jl_wrap_Type(jl_value_t *t); // x -> Type{x} jl_vararg_t *jl_wrap_vararg(jl_value_t *t, jl_value_t *n, int check, int nothrow); @@ -1564,8 +1594,8 @@ void jl_fprint_critical_error(ios_t *t, int sig, int si_code, bt_context_t *cont JL_DLLEXPORT void jl_raise_debugger(void) JL_NOTSAFEPOINT; JL_DLLEXPORT void jl_gdblookup(void* ip) JL_NOTSAFEPOINT; JL_DLLEXPORT void jl_print_task_backtraces(int show_done) JL_NOTSAFEPOINT; -void jl_fprint_native_codeloc(ios_t *s, uintptr_t ip) JL_NOTSAFEPOINT; -void jl_fprint_bt_entry_codeloc(ios_t *s, jl_bt_element_t *bt_data) JL_NOTSAFEPOINT; +void jl_fprint_native_codeloc(ios_t *s, const char *pre_str, uintptr_t ip) JL_NOTSAFEPOINT; +void jl_fprint_bt_entry_codeloc(ios_t *s, int sig, jl_bt_element_t *bt_data) JL_NOTSAFEPOINT; void jl_thread_resume(int tid) JL_NOTSAFEPOINT; int jl_thread_suspend(int16_t tid, bt_context_t *ctx) JL_NOTSAFEPOINT; diff --git a/src/options.h b/src/options.h index 0715069faab32..fb2797ffd0336 100644 --- a/src/options.h +++ b/src/options.h @@ -144,6 +144,9 @@ #define MACHINE_EXCLUSIVE_NAME "JULIA_EXCLUSIVE" #define DEFAULT_MACHINE_EXCLUSIVE 0 +// heartbeats +#define JL_HEARTBEAT_THREAD + // sanitizer defaults --------------------------------------------------------- // Automatically enable MEMDEBUG and KEEP_BODIES for the sanitizers diff --git a/src/processor.cpp b/src/processor.cpp index 9694b8d02e2f0..89abd1ca219d2 100644 --- a/src/processor.cpp +++ b/src/processor.cpp @@ -669,7 +669,7 @@ static inline jl_image_t parse_sysimg(jl_image_buf_t image, F &&callback, void * } JL_GC_POP(); - if (pointers->header->version != 1) { + if (pointers->header->version != JL_IMAGE_FORMAT_VERSION) { jl_error("Image file is not compatible with this version of Julia"); } diff --git a/src/processor.h b/src/processor.h index a80d6b9a27d23..0d670ab936839 100644 --- a/src/processor.h +++ b/src/processor.h @@ -92,11 +92,19 @@ struct _jl_image_t { void **jl_small_typeof; }; +// The version of the image format. 2: the layout of Method.specializations that +// jl_specializations_get_linfo_ expects (indexed entries first), which older images lack. +// 3: Unions with a Tuple or Core.TypeofBottom member no longer make a specialization indexed. +// 4: every specialization is indexed, by the type cache hash of its signature. +#define JL_IMAGE_FORMAT_VERSION 4 +// Marks the serialized data of a system image of that version, which a raw .ji has without +// the native header +#define JL_SYSIMG_STREAM_TAG (0x4a4c5300u | JL_IMAGE_FORMAT_VERSION) + // The header for each image // Details important counts about the image typedef struct { - // The version of the image format - // Most up-to-date version is 1 + // The version of the image format, JL_IMAGE_FORMAT_VERSION uint32_t version; // The number of shards in this image uint32_t nshards; diff --git a/src/safepoint.c b/src/safepoint.c index 8860d761e1574..75969b244eb37 100644 --- a/src/safepoint.c +++ b/src/safepoint.c @@ -172,7 +172,7 @@ void jl_gc_wait_for_the_world(jl_ptls_t* gc_all_tls_states, int gc_n_threads) size_t bt_size = jl_try_record_thread_backtrace(ptls2, ptls->bt_data, JL_MAX_BT_SIZE); // Print the backtrace of the straggler for (size_t i = 0; i < bt_size; i += jl_bt_entry_size(ptls->bt_data + i)) { - jl_fprint_bt_entry_codeloc(ios_safe_stderr, ptls->bt_data + i); + jl_fprint_bt_entry_codeloc(ios_safe_stderr, -1, ptls->bt_data + i); } } } diff --git a/src/signal-handling.c b/src/signal-handling.c index 1da687654dd81..b44d2a93b2540 100644 --- a/src/signal-handling.c +++ b/src/signal-handling.c @@ -30,6 +30,8 @@ static const uint64_t GIGA = 1000000000ULL; // Timers to take samples at intervals JL_DLLEXPORT void jl_profile_stop_timer(void); JL_DLLEXPORT int jl_profile_start_timer(uint8_t); +// File-descriptor for safe logging on signal handling +int jl_sig_fd; /////////////////////// // Utility functions // @@ -650,7 +652,7 @@ void jl_fprint_critical_error(ios_t *s, int sig, int si_code, bt_context_t *cont *bt_size = n = rec_backtrace_ctx(bt_data, JL_MAX_BT_SIZE, context, NULL); } for (i = 0; i < n; i += jl_bt_entry_size(bt_data + i)) { - jl_fprint_bt_entry_codeloc(s, bt_data + i); + jl_fprint_bt_entry_codeloc(s, sig, bt_data + i); } jl_gc_debug_fprint_status(s); jl_gc_debug_fprint_critical_error(s); diff --git a/src/signals-mach.c b/src/signals-mach.c index 72d2c3fe02fbb..a01c81dffb280 100644 --- a/src/signals-mach.c +++ b/src/signals-mach.c @@ -834,6 +834,10 @@ void *mach_profile_listener(void *arg) for (int idx = nthreads; idx-- > 0; ) { // Stop the threads in random order. int i = randperm[idx]; + // skip heartbeat thread + if (i == heartbeat_tid) { + continue; + } jl_profile_thread_mach(i); } } diff --git a/src/signals-unix.c b/src/signals-unix.c index f4acefa3e922e..f1eb8a116558c 100644 --- a/src/signals-unix.c +++ b/src/signals-unix.c @@ -42,7 +42,7 @@ #endif // 8M signal stack, same as default stack size (though we barely use this) -static const size_t sig_stack_size = 8 * 1024 * 1024; +const size_t sig_stack_size = 8 * 1024 * 1024; #include "julia_assert.h" @@ -991,6 +991,10 @@ static void do_profile(void) for (int idx = nthreads; idx-- > 0; ) { // Stop the threads in the random order. int tid = randperm[idx]; + // skip heartbeat thread + if (tid == heartbeat_tid) { + return; + } // do backtrace for profiler if (!profile_running) return; @@ -1229,7 +1233,7 @@ static void *signal_listener(void *arg) jl_safe_printf("\nsignal (%d): %s\n", sig, strsignal(sig)); size_t i; for (i = 0; i < signal_bt_size; i += jl_bt_entry_size(signal_bt_data + i)) { - jl_fprint_bt_entry_codeloc(ios_safe_stderr, signal_bt_data + i); + jl_fprint_bt_entry_codeloc(ios_safe_stderr, sig, signal_bt_data + i); } jl_safe_printf("\n"); // Enable trace compilation to stderr with timing during profile collection diff --git a/src/signals-win.c b/src/signals-win.c index dd5a5bcf05c50..fb898c6bd4e0c 100644 --- a/src/signals-win.c +++ b/src/signals-win.c @@ -4,7 +4,7 @@ // Note that this file is `#include`d by "signal-handling.c" #include // hidden by LEAN_AND_MEAN -static const size_t sig_stack_size = 131072; // 128k reserved for backtrace_fiber for stack overflow handling +const size_t sig_stack_size = 131072; // 128k reserved for backtrace_fiber for stack overflow handling // Copied from MINGW_FLOAT_H which may not be found due to a collision with the builtin gcc float.h // eventually we can probably integrate this into OpenLibm. @@ -361,7 +361,7 @@ LONG WINAPI jl_exception_handler(struct _EXCEPTION_POINTERS *ExceptionInfo) jl_safe_fprintf(&summary, "UNKNOWN"); break; } jl_safe_fprintf(&summary, " at 0x%zx -- ", (size_t)ExceptionInfo->ExceptionRecord->ExceptionAddress); - jl_fprint_native_codeloc(&summary, (uintptr_t)ExceptionInfo->ExceptionRecord->ExceptionAddress); + jl_fprint_native_codeloc(&summary, "", (uintptr_t)ExceptionInfo->ExceptionRecord->ExceptionAddress); ios_write(&full_error, summary.buf, ios_pos(&summary)); ios_puts("\nSee Application log in Event Viewer for more information.\n", &summary); diff --git a/src/smallintset.c b/src/smallintset.c index a80a18009c9db..cbd3bea1ab2ba 100644 --- a/src/smallintset.c +++ b/src/smallintset.c @@ -9,8 +9,6 @@ #endif #include "julia_assert.h" -// compute empirical max-probe for a given size -#define max_probe(size) ((size) <= 1024 ? 16 : (size) >> 6) #define h2index(hv, sz) (size_t)((hv) & ((sz)-1)) // a set of small positive integers representing the indices into another set @@ -124,10 +122,10 @@ ssize_t jl_smallintset_lookup(jl_genericmemory_t *cache, smallintset_eq eq, cons if (sz == 0) return -1; JL_GC_PUSH1(&cache); - size_t maxprobe = max_probe(sz); size_t index = h2index(hv, sz); size_t orig = index; - size_t iter = 0; + // no slot is ever emptied again (a pop leaves a tombstone), so every key is found + // before the first empty slot, however far its insertion had to probe do { size_t val1 = jl_intref_acquire(cache, index); if (val1 == 0) { @@ -141,31 +139,61 @@ ssize_t jl_smallintset_lookup(jl_genericmemory_t *cache, smallintset_eq eq, cons return val1 - 1; } index = (index + 1) & (sz - 1); - iter++; - } while (iter <= maxprobe && index != orig); + } while (index != orig); JL_GC_POP(); return -1; } +#define SMALLINTSET_PROBE 8 // the longest linear search in a typemap list + +static inline size_t smallintset_rawref(const jl_genericmemory_t *arr, size_t idx) JL_NOTSAFEPOINT +{ + jl_value_t *el = (jl_value_t*)jl_typetagof(arr); + if (el == jl_memory_uint8_type) + return jl_atomic_load_relaxed(&((_Atomic(uint8_t)*)arr->ptr)[idx]); + else if (el == jl_memory_uint16_type) + return jl_atomic_load_relaxed(&((_Atomic(uint16_t)*)arr->ptr)[idx]); + else + return jl_atomic_load_relaxed(&((_Atomic(uint32_t)*)arr->ptr)[idx]); +} + +// Insert `val1` into the first free slot (empty or a tombstone) of its probe: 1 when done, +// else 0 to grow the table or -1 to rehash it at the same size. The probe is measured to the +// first empty slot, where a lookup that misses stops. Past the length of a typemap list, a +// table at least half full (`val1` approximates the count) grows rather than probing further, +// so that doubling it leaves it at least a quarter full however many keys share a hash, and +// one with tombstones on the way is rehashed instead, since nothing else empties them. static int smallintset_insert_(jl_genericmemory_t *a, uint_t hv, size_t val1) JL_NOTSAFEPOINT { size_t sz = a->length; if (sz <= 1) return 0; - size_t orig, index, iter; - iter = 0; - index = h2index(hv, sz); - orig = index; - size_t maxprobe = max_probe(sz); + size_t tombstone = jl_max_int(a); + size_t index = h2index(hv, sz), orig = index, iter = 0; + ssize_t slot = -1; + int tombstones = 0; do { - if (jl_intref(a, index) == 0) { - jl_intset_release(a, index, val1); - return 1; + size_t v = smallintset_rawref(a, index); + if (v == 0 || v == tombstone) { + if (slot == -1) + slot = index; + if (v == 0) + break; + tombstones = 1; } index = (index + 1) & (sz - 1); iter++; - } while (iter <= maxprobe && index != orig); - return 0; + } while (index != orig); + if (slot == -1) + return 0; // no free slot + if (iter > SMALLINTSET_PROBE) { + if (val1 * 2 >= sz) + return 0; + if (tombstones) + return -1; + } + jl_intset_release(a, slot, val1); + return 1; } //} @@ -178,23 +206,21 @@ void jl_smallintset_insert(_Atomic(jl_genericmemory_t*) *pcache, jl_value_t *par if (parent) jl_gc_wb(parent, a); } while (1) { - if (smallintset_insert_(a, hash(val, data), val + 1)) + int r = smallintset_insert_(a, hash(val, data), val + 1); + if (r > 0) return; - /* table full */ - /* rehash to grow and retry the insert */ - /* it's important to grow the table really fast; otherwise we waste */ - /* lots of time rehashing all the keys over and over. */ + /* no free slot, or a long probe: double the table, or (for a table under half full + with tombstones on the way) rehash it at the same size to drop them */ size_t newsz; a = jl_atomic_load_relaxed(pcache); size_t sz = a->length; if (sz < HT_N_INLINE) newsz = HT_N_INLINE; - else if (sz >= (1 << 19) || (sz <= (1 << 8))) - newsz = sz << 1; else - newsz = sz << 2; - a = smallintset_rehash(a, hash, data, newsz, 0); + newsz = r < 0 ? sz : sz << 1; + // size the element type for `val` too: it can be the first and largest entry + a = smallintset_rehash(a, hash, data, newsz, val + 1); jl_atomic_store_release(pcache, a); if (parent) jl_gc_wb(parent, a); } @@ -215,7 +241,7 @@ jl_genericmemory_t* smallintset_rehash(jl_genericmemory_t* a, smallintset_hash h for (i = 0; i < sz; i += 1) { size_t val1 = jl_intref(a, i); if (val1 != 0) { - if (!smallintset_insert_(newa, hash(val1 - 1, data), val1)) { + if (smallintset_insert_(newa, hash(val1 - 1, data), val1) <= 0) { break; } } diff --git a/src/stackwalk.c b/src/stackwalk.c index 39cfe5c13ff3a..b8a26c15d63fe 100644 --- a/src/stackwalk.c +++ b/src/stackwalk.c @@ -823,22 +823,23 @@ JL_DLLEXPORT jl_value_t *jl_lookup_code_address(void *ip, int skipC) return rs; } -static void jl_safe_fprint_codeloc(ios_t *s, const char* func_name, const char* file_name, +static void jl_safe_fprint_codeloc(ios_t *s, const char *pre_str, + const char* func_name, const char* file_name, int line, int inlined) JL_NOTSAFEPOINT { const char *inlined_str = inlined ? " [inlined]" : ""; if (line != -1) { - jl_safe_fprintf(s, "%s at %s:%d%s\n", func_name, file_name, line, inlined_str); + jl_safe_fprintf(s, "%s%s at %s:%d%s\n", pre_str, func_name, file_name, line, inlined_str); } else { - jl_safe_fprintf(s, "%s at %s (unknown line)%s\n", func_name, file_name, inlined_str); + jl_safe_fprintf(s, "%s%s at %s (unknown line)%s\n", pre_str, func_name, file_name, inlined_str); } } // Print function, file and line containing native instruction pointer `ip` by // looking up debug info. Prints multiple such frames when `ip` points to // inlined code. -void jl_fprint_native_codeloc(ios_t *s, uintptr_t ip) JL_NOTSAFEPOINT +void jl_fprint_native_codeloc(ios_t *s, const char *pre_str, uintptr_t ip) JL_NOTSAFEPOINT { // This function is not allowed to reference any TLS variables since // it can be called from an unmanaged thread on OSX. @@ -850,10 +851,10 @@ void jl_fprint_native_codeloc(ios_t *s, uintptr_t ip) JL_NOTSAFEPOINT for (i = 0; i < n; i++) { jl_frame_t frame = frames[i]; if (!frame.func_name) { - jl_safe_fprintf(s, "unknown function (ip: %p) at %s\n", (void*)ip, frame.file_name ? frame.file_name : "(unknown file)"); + jl_safe_fprintf(s, "%sunknown function (ip: %p) at %s\n", pre_str, (void*)ip, frame.file_name ? frame.file_name : "(unknown file)"); } else { - jl_safe_fprint_codeloc(s, frame.func_name, frame.file_name, frame.line, frame.inlined); + jl_safe_fprint_codeloc(s, pre_str, frame.func_name, frame.file_name, frame.line, frame.inlined); free(frame.func_name); } free(frame.file_name); @@ -911,7 +912,7 @@ const char *jl_debuginfo_name(jl_value_t *func) // func == module : top-level // func == NULL : macro expansion -static void jl_fprint_debugloc(ios_t *s, jl_debuginfo_t *debuginfo, jl_value_t *func, size_t ip, int inlined) JL_NOTSAFEPOINT +static void jl_fprint_debugloc(ios_t *s, const char *pre_str, jl_debuginfo_t *debuginfo, jl_value_t *func, size_t ip, int inlined) JL_NOTSAFEPOINT { if (!jl_is_symbol(debuginfo->def)) // this is a path or func = debuginfo->def; // this is inlined code @@ -920,26 +921,39 @@ static void jl_fprint_debugloc(ios_t *s, jl_debuginfo_t *debuginfo, jl_value_t * if (edges_idx) { jl_debuginfo_t *edge = (jl_debuginfo_t*)jl_svecref(debuginfo->edges, edges_idx - 1); assert(jl_typetagis(edge, jl_debuginfo_type)); - jl_fprint_debugloc(s, edge, NULL, stmt.pc, 1); + jl_fprint_debugloc(s, pre_str, edge, NULL, stmt.pc, 1); } intptr_t ip2 = stmt.line; if (ip2 >= 0 && ip > 0 && (jl_value_t*)debuginfo->linetable != jl_nothing) { - jl_fprint_debugloc(s, debuginfo->linetable, func, ip2, 0); + jl_fprint_debugloc(s, pre_str, debuginfo->linetable, func, ip2, 0); } else { if (ip2 < 0) // set broken debug info to ignored ip2 = 0; const char *func_name = jl_debuginfo_name(func); const char *file = jl_debuginfo_file(debuginfo); - jl_safe_fprint_codeloc(s, func_name, file, ip2, inlined); + jl_safe_fprint_codeloc(s, pre_str, func_name, file, ip2, inlined); } } // Print code location for backtrace buffer entry at *bt_entry -void jl_fprint_bt_entry_codeloc(ios_t *s, jl_bt_element_t *bt_entry) JL_NOTSAFEPOINT +void jl_fprint_bt_entry_codeloc(ios_t *s, int sig, jl_bt_element_t *bt_entry) JL_NOTSAFEPOINT { + char sig_str[32], pre_str[64]; + sig_str[0] = pre_str[0] = '\0'; + if (sig != -1) { + snprintf(sig_str, 32, "signal (%d) ", sig); + } + // do not call jl_threadid if there's no current task + if (jl_get_current_task()) { + snprintf(pre_str, 64, "%sthread (%d) ", sig_str, jl_threadid() + 1); + } + else { + snprintf(pre_str, 64, "%s", sig_str); + } + if (jl_bt_is_native(bt_entry)) { - jl_fprint_native_codeloc(s, bt_entry[0].uintptr); + jl_fprint_native_codeloc(s, pre_str, bt_entry[0].uintptr); } else if (jl_bt_entry_tag(bt_entry) == JL_BT_INTERP_FRAME_TAG) { size_t ip = jl_bt_entry_header(bt_entry); // zero-indexed @@ -958,7 +972,7 @@ void jl_fprint_bt_entry_codeloc(ios_t *s, jl_bt_element_t *bt_entry) JL_NOTSAFEP if (jl_is_code_info(code)) { jl_code_info_t *src = (jl_code_info_t*)code; // See also the debug info handling in codegen.cpp. - jl_fprint_debugloc(s, src->debuginfo, def, ip + 1, 0); + jl_fprint_debugloc(s, pre_str, src->debuginfo, def, ip + 1, 0); } else { // If we're using this function something bad has already happened; @@ -1608,7 +1622,13 @@ JL_DLLEXPORT jl_record_backtrace_result_t jl_record_backtrace(jl_task_t *t, jl_b JL_DLLEXPORT void jl_gdblookup(void* ip) { - jl_fprint_native_codeloc(ios_safe_stderr, (uintptr_t)ip); + char pre_str[64]; + pre_str[0] = '\0'; + // do not call jl_threadid if there's no current task + if (jl_get_current_task()) { + snprintf(pre_str, 64, "thread (%d) ", jl_threadid() + 1); + } + jl_fprint_native_codeloc(ios_safe_stderr, pre_str, (uintptr_t)ip); } // Print backtrace for current exception in catch block @@ -1623,7 +1643,7 @@ JL_DLLEXPORT void jl_fprint_backtrace(ios_t *s) JL_NOTSAFEPOINT size_t i, bt_size = jl_excstack_bt_size(stack, stack->top); jl_bt_element_t *bt_data = jl_excstack_bt_data(stack, stack->top); for (i = 0; i < bt_size; i += jl_bt_entry_size(bt_data + i)) { - jl_fprint_bt_entry_codeloc(s, bt_data + i); + jl_fprint_bt_entry_codeloc(s, -1, bt_data + i); } } @@ -1656,7 +1676,7 @@ JL_DLLEXPORT void jl_fprint_backtracet(ios_t *s, jl_task_t *t) JL_NOTSAFEPOINT size_t bt_size = r.bt_size; size_t i; for (i = 0; i < bt_size; i += jl_bt_entry_size(bt_data + i)) { - jl_fprint_bt_entry_codeloc(s, bt_data + i); + jl_fprint_bt_entry_codeloc(s, -1, bt_data + i); } if (bt_size == 0) jl_safe_fprintf(s, " no backtrace recorded\n"); @@ -1667,11 +1687,30 @@ JL_DLLEXPORT void jlbacktracet(jl_task_t *t) JL_NOTSAFEPOINT jl_fprint_backtracet(ios_safe_stderr, t); } -// Print backtraces for all live tasks, for all threads, to jl_safe_printf stderr +extern int jl_inside_heartbeat_thread(void); +extern int jl_heartbeat_pause(void); +extern int jl_heartbeat_resume(void); + +// Print backtraces for all live tasks, for all threads, to jl_safe_printf +// stderr. This can take a _long_ time! JL_DLLEXPORT void jl_fprint_task_backtraces(ios_t *s, int show_done) JL_NOTSAFEPOINT { + // disable heartbeats to prevent heartbeat loss while running this, + // unless this is called from the heartbeat thread itself; in that + // situation, the thread is busy running this and it will not be + // updating the missed heartbeats counter + if (!jl_inside_heartbeat_thread()) { + jl_heartbeat_pause(); + } + size_t nthreads = jl_atomic_load_acquire(&jl_n_threads); jl_ptls_t *allstates = jl_atomic_load_relaxed(&jl_all_tls_states); + int ctid = -1; + // do not call jl_threadid if there's no current task + if (jl_get_current_task()) { + ctid = jl_threadid() + 1; + } + jl_safe_fprintf(s, "thread (%d) ++++ Task backtraces\n", ctid); for (size_t i = 0; i < nthreads; i++) { jl_ptls_t ptls2 = allstates[i]; if (gc_is_collector_thread(i)) { @@ -1687,17 +1726,22 @@ JL_DLLEXPORT void jl_fprint_task_backtraces(ios_t *s, int show_done) JL_NOTSAFEP jl_task_t *t = ptls2->root_task; if (t != NULL) t_state = jl_atomic_load_relaxed(&t->_state); - jl_safe_fprintf(s, "==== Thread %d created %zu live tasks\n", + jl_safe_fprintf(s, "thread (%d) ==== Thread %d created %zu live tasks\n", ctid, ptls2->tid + 1, n + (t_state != JL_TASK_STATE_DONE)); if (show_done || t_state != JL_TASK_STATE_DONE) { - jl_safe_fprintf(s, " ---- Root task (%p)\n", ptls2->root_task); + jl_safe_fprintf(s, "thread (%d) ---- Root task (%p)\n", ctid, ptls2->root_task); if (t != NULL) { - jl_safe_fprintf(s, " (sticky: %d, started: %d, state: %d, tid: %d)\n", + jl_safe_fprintf(s, "thread (%d) (sticky: %d, started: %d, state: %d, tid: %d)\n", ctid, t->sticky, t->ctx.started, t_state, jl_atomic_load_relaxed(&t->tid) + 1); - jl_fprint_backtracet(s, t); + if (t->ctx.stkbuf != NULL) { + jl_fprint_backtracet(s, t); + } + else { + jl_safe_fprintf(s, "thread (%d) no stack\n", ctid); + } } - jl_safe_fprintf(s, " ---- End root task\n"); + jl_safe_fprintf(s, "thread (%d) ---- End root task\n", ctid); } for (size_t j = 0; j < n; j++) { @@ -1707,17 +1751,24 @@ JL_DLLEXPORT void jl_fprint_task_backtraces(ios_t *s, int show_done) JL_NOTSAFEP int t_state = jl_atomic_load_relaxed(&t->_state); if (!show_done && t_state == JL_TASK_STATE_DONE) continue; - jl_safe_fprintf(s, " ---- Task %zu (%p)\n", j + 1, t); + jl_safe_fprintf(s, "thread (%d) ---- Task %zu (%p)\n", ctid, j + 1, t); // n.b. this information might not be consistent with the stack printing after it, since it could start running or change tid, etc. - jl_safe_fprintf(s, " (sticky: %d, started: %d, state: %d, tid: %d)\n", + jl_safe_fprintf(s, "thread (%d) (sticky: %d, started: %d, state: %d, tid: %d)\n", ctid, t->sticky, t->ctx.started, t_state, jl_atomic_load_relaxed(&t->tid) + 1); - jl_fprint_backtracet(ios_safe_stderr, t); - jl_safe_fprintf(s, " ---- End task %zu\n", j + 1); + if (t->ctx.stkbuf != NULL) + jl_fprint_backtracet(s, t); + else + jl_safe_fprintf(s, "thread (%d) no stack\n", ctid); + jl_safe_fprintf(s, "thread (%d) ---- End task %zu\n", ctid, j + 1); } - jl_safe_fprintf(s, "==== End thread %d\n", ptls2->tid + 1); + jl_safe_fprintf(s, "thread (%d) ==== End thread %d\n", ctid, ptls2->tid + 1); + } + jl_safe_fprintf(s, "thread (%d) ++++ Done\n", ctid); + + if (!jl_inside_heartbeat_thread()) { + jl_heartbeat_resume(); } - jl_safe_fprintf(s, "==== Done\n"); } // Print backtraces for all live tasks, for all threads, to jl_safe_printf stderr diff --git a/src/staticdata.c b/src/staticdata.c index 4a7aa830fdb97..8c39e30a486af 100644 --- a/src/staticdata.c +++ b/src/staticdata.c @@ -746,14 +746,21 @@ static void jl_insert_into_serialization_queue(jl_serializer_state *s, jl_value_ for (size_t i = 0, n = ((jl_genericmemory_t*)allbackedges)->length; i < n; i += 2) { jl_value_t *tn = jl_genericmemory_ptr_ref(allbackedges, i); jl_queue_for_serialization(s, tn); - jl_value_t *backedges = jl_genericmemory_ptr_ref(allbackedges, i + 1); - if (backedges && backedges != jl_nothing) { - jl_queue_for_serialization_(s, (jl_value_t*)((jl_array_t*)backedges)->ref.mem, 0, 1); - jl_queue_for_serialization(s, backedges); - for (size_t i = 0, n = jl_array_nrows(backedges); i < n; i += 2) { - jl_value_t *t = jl_array_ptr_ref(backedges, i); + jl_value_t *table = jl_genericmemory_ptr_ref(allbackedges, i + 1); + if (table && table != jl_nothing) { + // per-typename eqtable of sig => callers + jl_queue_for_serialization_(s, table, 0, 1); + for (size_t j = 0, m = ((jl_genericmemory_t*)table)->length; j < m; j += 2) { + jl_value_t *t = jl_genericmemory_ptr_ref(table, j); + jl_value_t *callers = jl_genericmemory_ptr_ref(table, j + 1); + if (callers == NULL) + continue; assert(!jl_is_code_instance(t)); jl_queue_for_serialization(s, t); + // serialize the callers list without forcing the CodeInstances + // in it to be serialized (unreachable ones are pruned later) + jl_queue_for_serialization_(s, (jl_value_t*)((jl_array_t*)callers)->ref.mem, 0, 1); + jl_queue_for_serialization(s, callers); } } } @@ -2450,26 +2457,37 @@ static void jl_prune_mi_backedges(jl_array_t *backedges) jl_array_del_end(backedges, n - ins); } -static void jl_prune_tn_backedges(jl_array_t *backedges) +static void jl_prune_tn_backedges(jl_genericmemory_t *table) { - size_t i = 0, ins = 0, n = jl_array_nrows(backedges); - for (i = 1; i < n; i += 2) { - jl_value_t *ci = jl_array_ptr_ref(backedges, i); - if (ptrhash_get(&serialization_order, ci) != HT_NOTFOUND) { - jl_array_ptr_set(backedges, ins++, jl_array_ptr_ref(backedges, i - 1)); - jl_array_ptr_set(backedges, ins++, ci); + _Atomic(jl_value_t*) *tab = (_Atomic(jl_value_t*)*)table->ptr; + for (size_t i = 0, n = table->length; i < n; i += 2) { + jl_value_t *callers = jl_atomic_load_relaxed(&tab[i + 1]); + if (callers == NULL) + continue; // empty or deleted slot + size_t j, ins = 0, l = jl_array_nrows(callers); + for (j = 0; j < l; j++) { + jl_value_t *ci = jl_array_ptr_ref(callers, j); + if (ptrhash_get(&serialization_order, ci) != HT_NOTFOUND) + jl_array_ptr_set((jl_array_t*)callers, ins++, ci); + } + // compact in place: the array was already queued for serialization, so + // pruned CodeInstances must not remain reachable from it + jl_array_del_end((jl_array_t*)callers, l - ins); + if (ins == 0) { + // no caller is being serialized: drop the entry (cf. `jl_eqtable_pop`) + jl_atomic_store_relaxed(&tab[i], jl_nothing); // clear the key + jl_atomic_store_relaxed(&tab[i + 1], NULL); // and the value } } - jl_array_del_end(backedges, n - ins); } static void jl_prune_mt_backedges(jl_genericmemory_t *allbackedges) { for (size_t i = 0, n = allbackedges->length; i < n; i += 2) { jl_value_t *tn = jl_genericmemory_ptr_ref(allbackedges, i); - jl_value_t *backedges = jl_genericmemory_ptr_ref(allbackedges, i + 1); - if (tn && tn != jl_nothing && backedges) - jl_prune_tn_backedges((jl_array_t*)backedges); + jl_value_t *table = jl_genericmemory_ptr_ref(allbackedges, i + 1); + if (tn && tn != jl_nothing && table && table != jl_nothing) + jl_prune_tn_backedges((jl_genericmemory_t*)table); } } @@ -2520,14 +2538,21 @@ static void jl_prune_idset(_Atomic(jl_svec_t*) *pkeys, _Atomic(jl_genericmemory_ assert(serialization_queue.items[(char*)idx - 1 - (char*)HT_NOTFOUND] == keys); ptrhash_put(&serialization_order, keys2, idx); serialization_queue.items[(char*)idx - 1 - (char*)HT_NOTFOUND] = keys2; + jl_atomic_store_relaxed(pkeys, keys2); + jl_gc_wb(parent, keys2); idx = ptrhash_get(&serialization_order, keyset); - assert(idx != HT_NOTFOUND && idx != (void*)(uintptr_t)-1); + if (idx == HT_NOTFOUND) { + // the shared empty keyset, which belongs to an earlier image and is not serialized + // here; every kept key is indexed, so there are none + assert(keyset == (jl_genericmemory_t*)jl_an_empty_memory_any); + assert(keys_list.len == 0); + return; + } + assert(idx != (void*)(uintptr_t)-1); assert(serialization_queue.items[(char*)idx - 1 - (char*)HT_NOTFOUND] == keyset); ptrhash_put(&serialization_order, jl_atomic_load_relaxed(&keyset2), idx); serialization_queue.items[(char*)idx - 1 - (char*)HT_NOTFOUND] = jl_atomic_load_relaxed(&keyset2); - jl_atomic_store_relaxed(pkeys, keys2); - jl_gc_wb(parent, keys2); jl_atomic_store_relaxed(pkeyset, jl_atomic_load_relaxed(&keyset2)); jl_gc_wb(parent, jl_atomic_load_relaxed(&keyset2)); } @@ -3259,6 +3284,7 @@ static void jl_save_system_image_to_stream(ios_t *f, jl_array_t *mod_array, write_padding(f, LLT_ALIGN(ios_pos(f), 8) - ios_pos(f)); s.s = f; if (worklist == NULL) { + write_uint32(f, JL_SYSIMG_STREAM_TAG); size_t i; for (i = 0; tags[i] != NULL; i++) { jl_value_t *tag = *tags[i]; @@ -3881,6 +3907,10 @@ static void jl_restore_system_image_from_stream_(ios_t *f, jl_image_t *image, s.s = f; uintptr_t offset_restored = 0, offset_init_order = 0, offset_extext_methods = 0, offset_new_ext_cis = 0, offset_method_roots_list = 0; if (!s.incremental) { + if (read_uint32(f) != JL_SYSIMG_STREAM_TAG) { + jl_safe_printf("ERROR: System image file is not compatible with this version of Julia\n"); + jl_exit(1); + } size_t i; for (i = 0; tags[i] != NULL; i++) { jl_value_t **tag = tags[i]; diff --git a/src/threading.c b/src/threading.c index 96495fef44c2b..f0478b2e9f461 100644 --- a/src/threading.c +++ b/src/threading.c @@ -1155,6 +1155,295 @@ JL_DLLEXPORT int jl_setaffinity(int16_t tid, char *mask, int cpumasksize) { return 0; // success } +// Heartbeat mechanism for Julia's task scheduler +// --- +// Start a thread that does not participate in running Julia's tasks. This +// thread simply sleeps until the heartbeat mechanism is enabled. When +// enabled, the heartbeat thread enters a loop in which it blocks waiting +// for the specified heartbeat interval. If, within that interval, +// `jl_heartbeat()` is *not* called at least once, then the thread calls +// `jl_print_task_backtraces(0)`. + +#ifdef JL_HEARTBEAT_THREAD + +#include + +volatile int heartbeat_enabled; +int heartbeat_tid; // Mostly used to ensure we skip this thread in the CPU profiler. XXX: not implemented on Windows +uv_thread_t heartbeat_uvtid; +uv_sem_t heartbeat_on_sem, // jl_heartbeat_enable -> thread + heartbeat_off_sem; // thread -> jl_heartbeat_enable +int heartbeat_interval_s, + tasks_after_n, + reset_tasks_after_n; +int tasks_showed, n_hbs_missed, n_hbs_recvd; +_Atomic(int) heartbeats; + +JL_DLLEXPORT void jl_print_task_backtraces(int show_done) JL_NOTSAFEPOINT; +void jl_heartbeat_threadfun(void *arg); + +// start the heartbeat thread with heartbeats disabled +void jl_init_heartbeat(void) +{ + heartbeat_enabled = 0; + uv_sem_init(&heartbeat_on_sem, 0); + uv_sem_init(&heartbeat_off_sem, 0); + uv_thread_create(&heartbeat_uvtid, jl_heartbeat_threadfun, NULL); + uv_thread_detach(&heartbeat_uvtid); +} + +int jl_inside_heartbeat_thread(void) +{ + uv_thread_t curr_uvtid = uv_thread_self(); + return curr_uvtid == heartbeat_uvtid; +} + +// enable/disable heartbeats +// heartbeat_s: interval within which jl_heartbeat() must be called +// show_tasks_after_n: number of heartbeats missed before printing task backtraces +// reset_after_n: number of heartbeats after which to reset +// +// When disabling heartbeats, the heartbeat thread must wake up, +// find out that heartbeats are now disabled, and reset. For now, we +// handle this by preventing re-enabling of heartbeats until this +// completes. +JL_DLLEXPORT int jl_heartbeat_enable(int heartbeat_s, int show_tasks_after_n, + int reset_after_n) +{ + if (heartbeat_s <= 0) { + heartbeat_enabled = 0; + heartbeat_interval_s = tasks_after_n = reset_tasks_after_n = 0; + } + else { + // must disable before enabling + if (heartbeat_enabled) { + return -1; + } + // heartbeat thread must be ready + if (uv_sem_trywait(&heartbeat_off_sem) != 0) { + return -1; + } + + jl_atomic_store_relaxed(&heartbeats, 0); + heartbeat_interval_s = heartbeat_s; + tasks_after_n = show_tasks_after_n; + reset_tasks_after_n = reset_after_n; + tasks_showed = 0; + n_hbs_missed = 0; + n_hbs_recvd = 0; + heartbeat_enabled = 1; + uv_sem_post(&heartbeat_on_sem); // wake the heartbeat thread + } + return 0; +} + +// temporarily pause the heartbeat thread +JL_DLLEXPORT int jl_heartbeat_pause(void) +{ + if (!heartbeat_enabled) { + return -1; + } + heartbeat_enabled = 0; + return 0; +} + +// resume the paused heartbeat thread +JL_DLLEXPORT int jl_heartbeat_resume(void) +{ + // cannot resume if the heartbeat thread is already running + if (heartbeat_enabled) { + return -1; + } + + // cannot resume if we weren't paused (disabled != paused) + if (heartbeat_interval_s == 0) { + return -1; + } + + // heartbeat thread must be ready + if (uv_sem_trywait(&heartbeat_off_sem) != 0) { + return -1; + } + + // reset state as we've been paused + n_hbs_missed = 0; + n_hbs_recvd = 0; + tasks_showed = 0; + + // resume + heartbeat_enabled = 1; + uv_sem_post(&heartbeat_on_sem); // wake the heartbeat thread + return 0; +} + +// heartbeat +JL_DLLEXPORT void jl_heartbeat(void) +{ + jl_atomic_fetch_add(&heartbeats, 1); +} + +// sleep the thread for the specified interval +void sleep_for(int secs, int nsecs) +{ + struct timespec rqtp, rmtp; + rqtp.tv_sec = secs; + rqtp.tv_nsec = nsecs; + rmtp.tv_sec = 0; + rmtp.tv_nsec = 0; + for (; ;) { + // this suspends the thread so we aren't using CPU + if (nanosleep(&rqtp, &rmtp) == 0) { + return; + } + // TODO: else if (errno == EINTR) + // this could be SIGTERM and we should shutdown but how to find out? + rqtp = rmtp; + } +} + +// check for heartbeats and maybe report loss +uint8_t check_heartbeats(uint8_t gc_state) +{ + int hb = jl_atomic_exchange(&heartbeats, 0); + + if (hb <= 0) { + // we didn't get a heartbeat + n_hbs_recvd = 0; + n_hbs_missed++; + + // if we've printed task backtraces already, do nothing + if (!tasks_showed) { + // otherwise, at least show this message + jl_safe_printf("==== heartbeat loss (%ds) ====\n", + n_hbs_missed * heartbeat_interval_s); + // if we've missed enough heartbeats, print task backtraces + if (n_hbs_missed >= tasks_after_n) { + jl_task_t *ct = jl_current_task; + jl_ptls_t ptls = ct->ptls; + + // exit GC-safe region to report then re-enter + jl_gc_safe_leave(ptls, gc_state); + jl_print_task_backtraces(0); + gc_state = jl_gc_safe_enter(ptls); + + // we printed task backtraces + tasks_showed = 1; + } + } + } + else { + // got a heartbeat + n_hbs_recvd++; + // if we'd printed task backtraces, check for reset + if (tasks_showed && n_hbs_recvd >= reset_tasks_after_n) { + tasks_showed = 0; + jl_safe_printf("==== heartbeats recovered (lost for %ds) ====\n", + n_hbs_missed * heartbeat_interval_s); + } + n_hbs_missed = 0; + } + + return gc_state; +} + +// heartbeat thread function +void jl_heartbeat_threadfun(void *arg) +{ + int s = 59, ns = 1e9 - 1, rs; + uint64_t t0, tchb; + + // We need a TLS because backtraces are accumulated into ptls->bt_size + // and ptls->bt_data, so we need to call jl_adopt_thread(). + jl_adopt_thread(); + if (jl_atomic_fetch_add_relaxed(&n_threads_running, -1) == 1) { + // jl_task_wait_empty on thread 0 may already be asleep waiting for n_threads_running == 0 + jl_ptls_t ptls0 = jl_atomic_load_relaxed(&jl_all_tls_states)[0]; + uv_mutex_lock(&ptls0->sleep_lock); + uv_cond_signal(&ptls0->wake_signal); + uv_mutex_unlock(&ptls0->sleep_lock); + } + jl_task_t *ct = jl_current_task; + jl_ptls_t ptls = ct->ptls; + heartbeat_tid = ptls->tid; + + // Don't hold up GC, this thread doesn't participate. + uint8_t gc_state = jl_gc_safe_enter(ptls); + + for (;;) { + if (!heartbeat_enabled) { + // post the off semaphore to indicate we're ready to enable + uv_sem_post(&heartbeat_off_sem); + + // sleep the thread here; this semaphore is posted in + // jl_heartbeat_enable() or jl_heartbeat_resume() + uv_sem_wait(&heartbeat_on_sem); + + // Set the sleep duration. + s = heartbeat_interval_s - 1; + ns = 1e9 - 1; + continue; + } + + // heartbeat is enabled; sleep, waiting for the desired interval + sleep_for(s, ns); + + // if heartbeats were turned off/paused while we were sleeping, reset + if (!heartbeat_enabled) { + continue; + } + + // check if any heartbeats have happened, report as appropriate + t0 = jl_hrtime(); + gc_state = check_heartbeats(gc_state); + tchb = jl_hrtime() - t0; + + // adjust the next sleep duration based on how long the heartbeat + // check took, but if it took too long then use the normal duration + rs = 1; + while (tchb > 1e9) { + rs++; + tchb -= 1e9; + } + if (rs < heartbeat_interval_s) { + s = heartbeat_interval_s - rs; + } + ns = 1e9 - tchb; + } +} + +#else // !JL_HEARTBEAT_THREAD + +void jl_init_heartbeat(void) +{ +} + +int jl_inside_heartbeat_thread(void) +{ + return 0; +} + +JL_DLLEXPORT int jl_heartbeat_enable(int heartbeat_s, int show_tasks_after_n, + int reset_after_n) +{ + return -1; +} + +JL_DLLEXPORT int jl_heartbeat_pause(void) +{ + return -1; +} + +JL_DLLEXPORT int jl_heartbeat_resume(void) +{ + return -1; +} + +JL_DLLEXPORT void jl_heartbeat(void) +{ +} + +#endif // JL_HEARTBEAT_THREAD + #ifdef __cplusplus } #endif diff --git a/test/cmdlineargs.jl b/test/cmdlineargs.jl index 9afb31bd2e017..e7d0757f751a1 100644 --- a/test/cmdlineargs.jl +++ b/test/cmdlineargs.jl @@ -1445,6 +1445,31 @@ end end end +@testset "--heap-target-increment-per-thread" begin + exename = `$(Base.julia_cmd())` + @test errors_not_signals(`$exename --heap-target-increment-per-thread -e "exit(0)"`) + @testset "--heap-target-increment-per-thread=$str" for str in ["asdf","","0","-256M","-1","1.2gb2","2GiB","NaNt","1e30T"] + @test errors_not_signals(`$exename --heap-target-increment-per-thread=$str -e "exit(0)"`) + end + m = UInt64(1) << 20 + @testset "--heap-target-increment-per-thread=$str" for (str, val) in [("512M", 512m), ("0.5G", 512m), ("256 M", 256m)] + @test test_read_success(`$exename --heap-target-increment-per-thread=$str -E "Base.JLOptions().heap_target_increment_per_thread"`, UInt64) == val + end + function stderr_of(cmd) + err = IOBuffer() + ok = success(pipeline(cmd; stderr=err)) + return ok, String(take!(err)) + end + @testset "JULIA_HEAP_TARGET_INCREMENT_PER_THREAD=$str" for str in ["abc","","-256M","-1","1e30T"] + ok, err = stderr_of(addenv(`$exename --startup-file=no -e "exit(0)"`, "JULIA_HEAP_TARGET_INCREMENT_PER_THREAD" => str)) + @test ok + @test occursin("ignoring invalid JULIA_HEAP_TARGET_INCREMENT_PER_THREAD", err) + end + ok, err = stderr_of(`$exename --startup-file=no --heap-target-increment-per-thread=512M --hard-heap-limit=4G -e "exit(0)"`) + @test ok + @test occursin("ignored with --hard-heap-limit", err) +end + @testset "--timeout-for-safepoint-straggler" begin exename = `$(Base.julia_cmd())` timeout = 120