1 /*
2 * Copyright (c) 2018, 2026, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "classfile/javaClasses.inline.hpp"
26 #include "classfile/vmSymbols.hpp"
27 #include "code/codeCache.inline.hpp"
28 #include "code/nmethod.inline.hpp"
29 #include "code/vmreg.inline.hpp"
30 #include "compiler/oopMap.inline.hpp"
31 #include "cppstdlib/type_traits.hpp"
32 #include "gc/shared/barrierSet.hpp"
33 #include "gc/shared/continuationGCSupport.inline.hpp"
34 #include "gc/shared/gc_globals.hpp"
35 #include "gc/shared/memAllocator.hpp"
36 #include "gc/shared/threadLocalAllocBuffer.inline.hpp"
37 #include "interpreter/bytecodeStream.hpp"
38 #include "interpreter/interpreter.hpp"
39 #include "interpreter/interpreterRuntime.hpp"
40 #include "jfr/jfrEvents.hpp"
41 #include "logging/log.hpp"
42 #include "logging/logStream.hpp"
43 #include "oops/access.inline.hpp"
44 #include "oops/constantPool.inline.hpp"
45 #include "oops/method.inline.hpp"
46 #include "oops/objArrayOop.inline.hpp"
47 #include "oops/oopsHierarchy.hpp"
48 #include "oops/stackChunkOop.inline.hpp"
49 #include "prims/jvmtiThreadState.hpp"
50 #include "runtime/arguments.hpp"
51 #include "runtime/continuation.hpp"
52 #include "runtime/continuationEntry.inline.hpp"
53 #include "runtime/continuationHelper.inline.hpp"
54 #include "runtime/continuationJavaClasses.inline.hpp"
55 #include "runtime/continuationWrapper.inline.hpp"
56 #include "runtime/frame.inline.hpp"
57 #include "runtime/interfaceSupport.inline.hpp"
58 #include "runtime/javaThread.inline.hpp"
59 #include "runtime/jniHandles.inline.hpp"
60 #include "runtime/keepStackGCProcessed.hpp"
61 #include "runtime/mountUnmountDisabler.hpp"
62 #include "runtime/objectMonitor.inline.hpp"
63 #include "runtime/orderAccess.hpp"
64 #include "runtime/prefetch.inline.hpp"
65 #include "runtime/sharedRuntime.hpp"
66 #include "runtime/smallRegisterMap.inline.hpp"
67 #include "runtime/stackChunkFrameStream.inline.hpp"
68 #include "runtime/stackFrameStream.inline.hpp"
69 #include "runtime/stackOverflow.hpp"
70 #include "runtime/stackWatermarkSet.inline.hpp"
71 #include "runtime/vframe.inline.hpp"
72 #include "runtime/vframe_hp.hpp"
73 #include "utilities/debug.hpp"
74 #include "utilities/exceptions.hpp"
75 #include "utilities/macros.hpp"
76 #include "utilities/vmError.hpp"
77 #if INCLUDE_ZGC
78 #include "gc/z/zStackChunkGCData.inline.hpp"
79 #endif
80 #if INCLUDE_JFR
81 #include "jfr/jfr.inline.hpp"
82 #endif
83 #ifdef COMPILER1
84 #include "c1/c1_Runtime1.hpp"
85 #endif
86 #ifdef COMPILER2
87 #include "opto/runtime.hpp"
88 #endif
89
90 /*
91 * This file contains the implementation of continuation freezing (yield) and thawing (run).
92 *
93 * This code is very latency-critical and very hot. An ordinary and well-behaved server application
94 * would likely call these operations many thousands of times per second second, on every core.
95 *
96 * Freeze might be called every time the application performs any I/O operation, every time it
97 * acquires a j.u.c. lock, every time it takes a message from a queue, and thaw can be called
98 * multiple times in each of those cases, as it is called by the return barrier, which may be
99 * invoked on method return.
100 *
101 * The amortized budget for each of those two operations is ~100-150ns. That is why, for
102 * example, every effort is made to avoid Java-VM transitions as much as possible.
103 *
104 * On the fast path, all frames are known to be compiled, and the chunk requires no barriers
105 * and so frames simply copied, and the bottom-most one is patched.
106 * On the slow path, internal pointers in interpreted frames are de/relativized to/from offsets
107 * and absolute pointers, and barriers invoked.
108 */
109
110 /************************************************
111
112 Thread-stack layout on freeze/thaw.
113 See corresponding stack-chunk layout in instanceStackChunkKlass.hpp
114
115 +----------------------------+
116 | . |
117 | . |
118 | . |
119 | carrier frames |
120 | |
121 |----------------------------|
122 | |
123 | Continuation.run |
124 | |
125 |============================|
126 | enterSpecial frame |
127 | pc |
128 | rbp |
129 | ----- |
130 ^ | int argsize | = ContinuationEntry
131 | | oopDesc* cont |
132 | | oopDesc* chunk |
133 | | ContinuationEntry* parent |
134 | | ... |
135 | |============================| <------ JavaThread::_cont_entry = entry->sp()
136 | | ? alignment word ? |
137 | |----------------------------| <--\
138 | | | |
139 | | ? caller stack args ? | | argsize (might not be 2-word aligned) words
140 Address | | | | Caller is still in the chunk.
141 | |----------------------------| |
142 | | pc (? return barrier ?) | | This pc contains the return barrier when the bottom-most frame
143 | | rbp | | isn't the last one in the continuation.
144 | | | |
145 | | frame | |
146 | | | |
147 +----------------------------| \__ Continuation frames to be frozen/thawed
148 | | /
149 | frame | |
150 | | |
151 |----------------------------| |
152 | | |
153 | frame | |
154 | | |
155 |----------------------------| <--/
156 | |
157 | doYield/safepoint stub | When preempting forcefully, we could have a safepoint stub
158 | | instead of a doYield stub
159 |============================| <- the sp passed to freeze
160 | |
161 | Native freeze/thaw frames |
162 | . |
163 | . |
164 | . |
165 +----------------------------+
166
167 ************************************************/
168
169 #define CONT_JFR false // emit low-level JFR events that count slow/fast path for continuation performance debugging only
170 #if CONT_JFR
171 #define CONT_JFR_ONLY(code) code
172 #else
173 #define CONT_JFR_ONLY(code)
174 #endif
175
176 // TODO: See AbstractAssembler::generate_stack_overflow_check,
177 // Compile::bang_size_in_bytes(), m->as_SafePoint()->jvms()->interpreter_frame_size()
178 // when we stack-bang, we need to update a thread field with the lowest (farthest) bang point.
179
180 // Data invariants are defined by Continuation::debug_verify_continuation and Continuation::debug_verify_stack_chunk
181
182 // Used to just annotatate cold/hot branches
183 #define LIKELY(condition) (condition)
184 #define UNLIKELY(condition) (condition)
185
186 // debugging functions
187 #ifdef ASSERT
188 extern "C" bool dbg_is_safe(const void* p, intptr_t errvalue); // address p is readable and *(intptr_t*)p != errvalue
189
190 static void verify_continuation(oop continuation) { Continuation::debug_verify_continuation(continuation); }
191
192 static void do_deopt_after_thaw(JavaThread* thread);
193 static bool do_verify_after_thaw(JavaThread* thread, stackChunkOop chunk, outputStream* st);
194 static bool verify_deopt_state(const frame& f);
195 static void log_frames(JavaThread* thread);
196 static void log_frames_after_thaw(JavaThread* thread, ContinuationWrapper& cont, intptr_t* sp);
197 static void print_frame_layout(const frame& f, bool callee_complete, outputStream* st = tty);
198 static void verify_frame_kind(frame& top, Continuation::preempt_kind preempt_kind, Method** m_ptr = nullptr, const char** code_name_ptr = nullptr, int* bci_ptr = nullptr, stackChunkOop chunk = nullptr);
199
200 #define assert_pfl(p, ...) \
201 do { \
202 if (!(p)) { \
203 JavaThread* t = JavaThread::active(); \
204 if (t->has_last_Java_frame()) { \
205 tty->print_cr("assert(" #p ") failed:"); \
206 t->print_frame_layout(); \
207 } \
208 } \
209 vmassert(p, __VA_ARGS__); \
210 } while(0)
211
212 #else
213 static void verify_continuation(oop continuation) { }
214 #define assert_pfl(p, ...)
215 #endif
216
217 static freeze_result is_pinned0(JavaThread* thread, oop cont_scope, bool safepoint);
218 template<typename ConfigT, bool preempt> static inline freeze_result freeze_internal(JavaThread* current, intptr_t* const sp);
219
220 static inline int prepare_thaw_internal(JavaThread* thread, bool return_barrier);
221 template<typename ConfigT> static inline intptr_t* thaw_internal(JavaThread* thread, const Continuation::thaw_kind kind);
222
223 // Entry point to freeze. Transitions are handled manually
224 // Called from gen_continuation_yield() in sharedRuntime_<cpu>.cpp through Continuation::freeze_entry();
225 template<typename ConfigT>
226 static JRT_BLOCK_ENTRY(int, freeze(JavaThread* current, intptr_t* sp))
227 assert(sp == current->frame_anchor()->last_Java_sp(), "");
228
229 if (current->raw_cont_fastpath() > current->last_continuation()->entry_sp() || current->raw_cont_fastpath() < sp) {
230 current->set_cont_fastpath(nullptr);
231 }
232
233 return checked_cast<int>(ConfigT::freeze(current, sp));
234 JRT_END
235
236 JRT_LEAF(int, Continuation::prepare_thaw(JavaThread* thread, bool return_barrier))
237 return prepare_thaw_internal(thread, return_barrier);
238 JRT_END
239
240 template<typename ConfigT>
241 static JRT_LEAF(intptr_t*, thaw(JavaThread* thread, int kind))
242 // TODO: JRT_LEAF and NoHandleMark is problematic for JFR events.
243 // vFrameStreamCommon allocates Handles in RegisterMap for continuations.
244 // Also the preemption case with JVMTI events enabled might safepoint so
245 // undo the NoSafepointVerifier here and rely on handling by ContinuationWrapper.
246 // JRT_ENTRY instead?
247 ResetNoHandleMark rnhm;
248 DEBUG_ONLY(PauseNoSafepointVerifier pnsv(&__nsv);)
249
250 // we might modify the code cache via BarrierSetNMethod::nmethod_entry_barrier
251 MACOS_AARCH64_ONLY(ThreadWXEnable __wx(WXWrite, thread));
252 return ConfigT::thaw(thread, (Continuation::thaw_kind)kind);
253 JRT_END
254
255 JVM_ENTRY(jint, CONT_isPinned0(JNIEnv* env, jobject cont_scope)) {
256 JavaThread* thread = JavaThread::thread_from_jni_environment(env);
257 return is_pinned0(thread, JNIHandles::resolve(cont_scope), false);
258 }
259 JVM_END
260
261 ///////////
262
263 enum class oop_kind { NARROW, WIDE };
264 template <oop_kind oops, typename BarrierSetT>
265 class Config {
266 public:
267 typedef Config<oops, BarrierSetT> SelfT;
268 using OopT = std::conditional_t<oops == oop_kind::NARROW, narrowOop, oop>;
269
270 static freeze_result freeze(JavaThread* thread, intptr_t* const sp) {
271 freeze_result res = freeze_internal<SelfT, false>(thread, sp);
272 JFR_ONLY(assert((res == freeze_ok) || (res == thread->last_freeze_fail_result()), "freeze failure not set"));
273 return res;
274 }
275
276 static freeze_result freeze_preempt(JavaThread* thread, intptr_t* const sp) {
277 return freeze_internal<SelfT, true>(thread, sp);
278 }
279
280 static intptr_t* thaw(JavaThread* thread, Continuation::thaw_kind kind) {
281 return thaw_internal<SelfT>(thread, kind);
282 }
283 };
284
285 #ifdef _WINDOWS
286 static void map_stack_pages(JavaThread* thread, size_t size, address sp) {
287 address new_sp = sp - size;
288 address watermark = thread->stack_overflow_state()->shadow_zone_growth_watermark();
289
290 if (new_sp < watermark) {
291 size_t page_size = os::vm_page_size();
292 address last_touched_page = watermark - StackOverflow::stack_shadow_zone_size();
293 size_t pages_to_touch = align_up(watermark - new_sp, page_size) / page_size;
294 while (pages_to_touch-- > 0) {
295 last_touched_page -= page_size;
296 *last_touched_page = 0;
297 }
298 thread->stack_overflow_state()->set_shadow_zone_growth_watermark(new_sp);
299 }
300 }
301 #endif
302
303 static bool stack_overflow_check(JavaThread* thread, size_t size, address sp) {
304 const size_t page_size = os::vm_page_size();
305 if (size > page_size) {
306 if (sp - size < thread->stack_overflow_state()->shadow_zone_safe_limit()) {
307 return false;
308 }
309 WINDOWS_ONLY(map_stack_pages(thread, size, sp));
310 }
311 return true;
312 }
313
314 #ifdef ASSERT
315 static oop get_continuation(JavaThread* thread) {
316 assert(thread != nullptr, "");
317 assert(thread->threadObj() != nullptr, "");
318 return java_lang_Thread::continuation(thread->threadObj());
319 }
320 #endif // ASSERT
321
322 inline void clear_anchor(JavaThread* thread) {
323 thread->frame_anchor()->clear();
324 }
325
326 static void set_anchor(JavaThread* thread, intptr_t* sp, address pc) {
327 assert(pc != nullptr, "");
328
329 JavaFrameAnchor* anchor = thread->frame_anchor();
330 anchor->set_last_Java_sp(sp);
331 anchor->set_last_Java_pc(pc);
332 ContinuationHelper::set_anchor_pd(anchor, sp);
333
334 assert(thread->has_last_Java_frame(), "");
335 assert(thread->last_frame().cb() != nullptr, "");
336 }
337
338 static void set_anchor(JavaThread* thread, intptr_t* sp) {
339 address pc = ContinuationHelper::return_address_at(
340 sp - frame::sender_sp_ret_address_offset());
341 set_anchor(thread, sp, pc);
342 }
343
344 static void set_anchor_to_entry(JavaThread* thread, ContinuationEntry* entry) {
345 JavaFrameAnchor* anchor = thread->frame_anchor();
346 anchor->set_last_Java_sp(entry->entry_sp());
347 anchor->set_last_Java_pc(entry->entry_pc());
348 ContinuationHelper::set_anchor_to_entry_pd(anchor, entry);
349
350 assert(thread->has_last_Java_frame(), "");
351 assert(thread->last_frame().cb() != nullptr, "");
352 }
353
354 #if CONT_JFR
355 class FreezeThawJfrInfo : public StackObj {
356 short _e_size;
357 short _e_num_interpreted_frames;
358 public:
359
360 FreezeThawJfrInfo() : _e_size(0), _e_num_interpreted_frames(0) {}
361 inline void record_interpreted_frame() { _e_num_interpreted_frames++; }
362 inline void record_size_copied(int size) { _e_size += size << LogBytesPerWord; }
363 template<typename Event> void post_jfr_event(Event *e, oop continuation, JavaThread* jt);
364 };
365
366 template<typename Event> void FreezeThawJfrInfo::post_jfr_event(Event* e, oop continuation, JavaThread* jt) {
367 if (e->should_commit()) {
368 log_develop_trace(continuations)("JFR event: iframes: %d size: %d", _e_num_interpreted_frames, _e_size);
369 e->set_carrierThread(JFR_JVM_THREAD_ID(jt));
370 e->set_continuationClass(continuation->klass());
371 e->set_interpretedFrames(_e_num_interpreted_frames);
372 e->set_size(_e_size);
373 e->commit();
374 }
375 }
376 #endif // CONT_JFR
377
378 /////////////// FREEZE ////
379
380 class FreezeBase : public StackObj {
381 protected:
382 JavaThread* const _thread;
383 ContinuationWrapper& _cont;
384 bool _barriers; // only set when we allocate a chunk
385
386 intptr_t* _bottom_address;
387
388 // Used for preemption only
389 const bool _preempt;
390 frame _last_frame;
391
392 // Used to support freezing with held monitors
393 int _monitors_in_lockstack;
394
395 int _freeze_size; // total size of all frames plus metadata in words.
396 int _total_align_size;
397
398 intptr_t* _cont_stack_top;
399 intptr_t* _cont_stack_bottom;
400
401 CONT_JFR_ONLY(FreezeThawJfrInfo _jfr_info;)
402
403 #ifdef ASSERT
404 intptr_t* _orig_chunk_sp;
405 int _fast_freeze_size;
406 bool _empty;
407 #endif
408
409 JvmtiSampledObjectAllocEventCollector* _jvmti_event_collector;
410
411 NOT_PRODUCT(int _frames;)
412 DEBUG_ONLY(intptr_t* _last_write;)
413
414 inline FreezeBase(JavaThread* thread, ContinuationWrapper& cont, intptr_t* sp, bool preempt);
415
416 public:
417 NOINLINE freeze_result freeze_slow();
418 void freeze_fast_existing_chunk();
419
420 CONT_JFR_ONLY(FreezeThawJfrInfo& jfr_info() { return _jfr_info; })
421 void set_jvmti_event_collector(JvmtiSampledObjectAllocEventCollector* jsoaec) { _jvmti_event_collector = jsoaec; }
422
423 inline int size_if_fast_freeze_available();
424
425 inline frame& last_frame() { return _last_frame; }
426
427 #ifdef ASSERT
428 bool check_valid_fast_path();
429 #endif
430
431 protected:
432 inline void init_rest();
433 void throw_stack_overflow_on_humongous_chunk();
434
435 // fast path
436 inline void copy_to_chunk(intptr_t* from, intptr_t* to, int size);
437 inline void unwind_frames();
438 inline void patch_stack_pd(intptr_t* frame_sp, intptr_t* heap_sp);
439
440 // slow path
441 virtual stackChunkOop allocate_chunk_slow(size_t stack_size, int argsize_md) = 0;
442
443 int cont_size() { return pointer_delta_as_int(_cont_stack_bottom, _cont_stack_top); }
444
445 private:
446 // slow path
447 frame freeze_start_frame();
448 frame freeze_start_frame_on_preempt();
449 NOINLINE freeze_result recurse_freeze(frame& f, frame& caller, int callee_argsize, bool callee_interpreted, bool top);
450 inline frame freeze_start_frame_yield_stub();
451 template<typename FKind>
452 inline freeze_result recurse_freeze_java_frame(const frame& f, frame& caller, int fsize, int argsize);
453 inline void before_freeze_java_frame(const frame& f, const frame& caller, int fsize, int argsize, bool is_bottom_frame);
454 inline void after_freeze_java_frame(const frame& hf, bool is_bottom_frame);
455 freeze_result finalize_freeze(const frame& callee, frame& caller, int argsize);
456 void patch(const frame& f, frame& hf, const frame& caller, bool is_bottom_frame);
457 NOINLINE freeze_result recurse_freeze_interpreted_frame(frame& f, frame& caller, int callee_argsize, bool callee_interpreted);
458 freeze_result recurse_freeze_compiled_frame(frame& f, frame& caller, int callee_argsize, bool callee_interpreted);
459 NOINLINE freeze_result recurse_freeze_stub_frame(frame& f, frame& caller);
460 NOINLINE freeze_result recurse_freeze_native_frame(frame& f, frame& caller);
461 NOINLINE void finish_freeze(const frame& f, const frame& top);
462
463 void freeze_lockstack(stackChunkOop chunk);
464
465 inline bool stack_overflow();
466
467 static frame sender(const frame& f) { return f.is_interpreted_frame() ? sender<ContinuationHelper::InterpretedFrame>(f)
468 : sender<ContinuationHelper::NonInterpretedUnknownFrame>(f); }
469 template<typename FKind> static inline frame sender(const frame& f);
470 template<typename FKind> frame new_heap_frame(frame& f, frame& caller, int size_adjust = 0);
471 inline void set_top_frame_metadata_pd(const frame& hf);
472 inline void patch_pd(frame& callee, const frame& caller, bool is_bottom_frame);
473 inline void patch_pd_unused(intptr_t* sp);
474 void adjust_interpreted_frame_unextended_sp(frame& f);
475 inline void prepare_freeze_interpreted_top_frame(frame& f);
476 static inline void relativize_interpreted_frame_metadata(const frame& f, const frame& hf);
477
478 protected:
479 void freeze_fast_copy(stackChunkOop chunk, int chunk_start_sp CONT_JFR_ONLY(COMMA bool chunk_is_allocated));
480 bool freeze_fast_new_chunk(stackChunkOop chunk);
481 };
482
483 template <typename ConfigT>
484 class Freeze : public FreezeBase {
485 private:
486 stackChunkOop allocate_chunk(size_t stack_size, int argsize_md);
487
488 public:
489 inline Freeze(JavaThread* thread, ContinuationWrapper& cont, intptr_t* frame_sp, bool preempt)
490 : FreezeBase(thread, cont, frame_sp, preempt) {}
491
492 freeze_result try_freeze_fast();
493
494 protected:
495 virtual stackChunkOop allocate_chunk_slow(size_t stack_size, int argsize_md) override { return allocate_chunk(stack_size, argsize_md); }
496 };
497
498 FreezeBase::FreezeBase(JavaThread* thread, ContinuationWrapper& cont, intptr_t* frame_sp, bool preempt) :
499 _thread(thread), _cont(cont), _barriers(false), _preempt(preempt), _last_frame(false /* no initialization */) {
500 DEBUG_ONLY(_jvmti_event_collector = nullptr;)
501
502 assert(_thread != nullptr, "");
503 assert(_thread->last_continuation()->entry_sp() == _cont.entrySP(), "");
504
505 DEBUG_ONLY(_cont.entry()->verify_cookie();)
506
507 assert(!Interpreter::contains(_cont.entryPC()), "");
508
509 _bottom_address = align_down(_cont.entrySP() - _cont.entry_frame_extension(), frame::frame_alignment);
510
511 log_develop_trace(continuations)("bottom_address: " INTPTR_FORMAT " entrySP: " INTPTR_FORMAT " argsize: " PTR_FORMAT,
512 p2i(_bottom_address), p2i(_cont.entrySP()), (_cont.entrySP() - _bottom_address) << LogBytesPerWord);
513 assert(_bottom_address != nullptr, "");
514 assert(_bottom_address <= _cont.entrySP(), "");
515 DEBUG_ONLY(_last_write = nullptr;)
516
517 assert(_cont.chunk_invariant(), "");
518 assert(!Interpreter::contains(_cont.entryPC()), "");
519 #if defined(PPC64) && !defined(ZERO)
520 static const int doYield_stub_frame_size = frame::native_abi_reg_args_size >> LogBytesPerWord;
521 #elif defined(S390) && !defined(ZERO)
522 static const int doYield_stub_frame_size = frame::z_abi_160_base_size >> LogBytesPerWord;
523 #else
524 static const int doYield_stub_frame_size = frame::metadata_words;
525 #endif
526 // With preemption doYield() might not have been resolved yet
527 assert(_preempt || SharedRuntime::cont_doYield_stub()->frame_size() == doYield_stub_frame_size,
528 "_preempt = %d, cont_doYield_stub()->frame_size() = %d, doYield_stub_frame_size = %d",
529 (_preempt ? 1 : 0), SharedRuntime::cont_doYield_stub()->frame_size(), doYield_stub_frame_size);
530
531 if (preempt) {
532 _last_frame = _thread->last_frame();
533 }
534
535 // properties of the continuation on the stack; all sizes are in words
536 _cont_stack_top = frame_sp + (!preempt ? doYield_stub_frame_size : 0); // we don't freeze the doYield stub frame
537 _cont_stack_bottom = _cont.entrySP() + (_cont.argsize() == 0 ? frame::metadata_words_at_top : 0)
538 - ContinuationHelper::frame_align_words(_cont.argsize()); // see alignment in thaw
539
540 log_develop_trace(continuations)("freeze size: %d argsize: %d top: " INTPTR_FORMAT " bottom: " INTPTR_FORMAT,
541 cont_size(), _cont.argsize(), p2i(_cont_stack_top), p2i(_cont_stack_bottom));
542 assert(cont_size() > 0, "");
543
544 _monitors_in_lockstack = _thread->lock_stack().monitor_count();
545 }
546
547 void FreezeBase::init_rest() { // we want to postpone some initialization after chunk handling
548 _freeze_size = 0;
549 _total_align_size = 0;
550 NOT_PRODUCT(_frames = 0;)
551 }
552
553 void FreezeBase::freeze_lockstack(stackChunkOop chunk) {
554 assert(chunk->sp_address() - chunk->start_address() >= _monitors_in_lockstack, "no room for lockstack");
555
556 _thread->lock_stack().move_to_address((oop*)chunk->start_address());
557 chunk->set_lockstack_size(checked_cast<uint8_t>(_monitors_in_lockstack));
558 chunk->set_has_lockstack(true);
559 }
560
561 void FreezeBase::copy_to_chunk(intptr_t* from, intptr_t* to, int size) {
562 stackChunkOop chunk = _cont.tail();
563 chunk->copy_from_stack_to_chunk(from, to, size);
564 CONT_JFR_ONLY(_jfr_info.record_size_copied(size);)
565
566 #ifdef ASSERT
567 if (_last_write != nullptr) {
568 assert(_last_write == to + size, "Missed a spot: _last_write: " INTPTR_FORMAT " to+size: " INTPTR_FORMAT
569 " stack_size: %d _last_write offset: " PTR_FORMAT " to+size: " PTR_FORMAT, p2i(_last_write), p2i(to+size),
570 chunk->stack_size(), _last_write-chunk->start_address(), to+size-chunk->start_address());
571 _last_write = to;
572 }
573 #endif
574 }
575
576 static void assert_frames_in_continuation_are_safe(JavaThread* thread) {
577 #ifdef ASSERT
578 StackWatermark* watermark = StackWatermarkSet::get(thread, StackWatermarkKind::gc);
579 if (watermark == nullptr) {
580 return;
581 }
582 ContinuationEntry* ce = thread->last_continuation();
583 RegisterMap map(thread,
584 RegisterMap::UpdateMap::include,
585 RegisterMap::ProcessFrames::skip,
586 RegisterMap::WalkContinuation::skip);
587 map.set_include_argument_oops(false);
588 for (frame f = thread->last_frame(); Continuation::is_frame_in_continuation(ce, f); f = f.sender(&map)) {
589 watermark->assert_is_frame_safe(f);
590 }
591 #endif // ASSERT
592 }
593
594 // Called _after_ the last possible safepoint during the freeze operation (chunk allocation)
595 void FreezeBase::unwind_frames() {
596 ContinuationEntry* entry = _cont.entry();
597 entry->flush_stack_processing(_thread);
598 assert_frames_in_continuation_are_safe(_thread);
599 JFR_ONLY(Jfr::check_and_process_sample_request(_thread);)
600 set_anchor_to_entry(_thread, entry);
601 }
602
603 template <typename ConfigT>
604 freeze_result Freeze<ConfigT>::try_freeze_fast() {
605 assert(_thread->thread_state() == _thread_in_vm, "");
606 assert(_thread->cont_fastpath(), "");
607
608 DEBUG_ONLY(_fast_freeze_size = size_if_fast_freeze_available();)
609 assert(_fast_freeze_size == 0, "");
610
611 stackChunkOop chunk = allocate_chunk(cont_size() + frame::metadata_words + _monitors_in_lockstack, _cont.argsize() + frame::metadata_words_at_top);
612 if (freeze_fast_new_chunk(chunk)) {
613 return freeze_ok;
614 }
615 if (_thread->has_pending_exception()) {
616 return freeze_exception;
617 }
618
619 // TODO R REMOVE when deopt change is fixed
620 assert(!_thread->cont_fastpath() || _barriers, "");
621 log_develop_trace(continuations)("-- RETRYING SLOW --");
622 return freeze_slow();
623 }
624
625 // Returns size needed if the continuation fits, otherwise 0.
626 int FreezeBase::size_if_fast_freeze_available() {
627 stackChunkOop chunk = _cont.tail();
628 if (chunk == nullptr || chunk->is_gc_mode() || chunk->requires_barriers() || chunk->has_mixed_frames()) {
629 log_develop_trace(continuations)("chunk available %s", chunk == nullptr ? "no chunk" : "chunk requires barriers");
630 return 0;
631 }
632
633 int total_size_needed = cont_size();
634 const int chunk_sp = chunk->sp();
635
636 // argsize can be nonzero if we have a caller, but the caller could be in a non-empty parent chunk,
637 // so we subtract it only if we overlap with the caller, i.e. the current chunk isn't empty.
638 // Consider leaving the chunk's argsize set when emptying it and removing the following branch,
639 // although that would require changing stackChunkOopDesc::is_empty
640 if (!chunk->is_empty()) {
641 total_size_needed -= _cont.argsize() + frame::metadata_words_at_top;
642 }
643
644 total_size_needed += _monitors_in_lockstack;
645
646 int chunk_free_room = chunk_sp - frame::metadata_words_at_bottom;
647 bool available = chunk_free_room >= total_size_needed;
648 log_develop_trace(continuations)("chunk available: %s size: %d argsize: %d top: " INTPTR_FORMAT " bottom: " INTPTR_FORMAT,
649 available ? "yes" : "no" , total_size_needed, _cont.argsize(), p2i(_cont_stack_top), p2i(_cont_stack_bottom));
650 return available ? total_size_needed : 0;
651 }
652
653 void FreezeBase::freeze_fast_existing_chunk() {
654 stackChunkOop chunk = _cont.tail();
655
656 DEBUG_ONLY(_fast_freeze_size = size_if_fast_freeze_available();)
657 assert(_fast_freeze_size > 0, "");
658
659 if (!chunk->is_empty()) { // we are copying into a non-empty chunk
660 DEBUG_ONLY(_empty = false;)
661 DEBUG_ONLY(_orig_chunk_sp = chunk->sp_address();)
662 #ifdef ASSERT
663 {
664 intptr_t* retaddr_slot = (chunk->sp_address()
665 - frame::sender_sp_ret_address_offset());
666 assert(ContinuationHelper::return_address_at(retaddr_slot) == chunk->pc(),
667 "unexpected saved return address");
668 }
669 #endif
670
671 // the chunk's sp before the freeze, adjusted to point beyond the stack-passed arguments in the topmost frame
672 // we overlap; we'll overwrite the chunk's top frame's callee arguments
673 const int chunk_start_sp = chunk->sp() + _cont.argsize() + frame::metadata_words_at_top;
674 assert(chunk_start_sp <= chunk->stack_size(), "sp not pointing into stack");
675
676 // increase max_size by what we're freezing minus the overlap
677 chunk->set_max_thawing_size(chunk->max_thawing_size() + cont_size() - _cont.argsize() - frame::metadata_words_at_top);
678
679 intptr_t* const bottom_sp = _cont_stack_bottom - _cont.argsize() - frame::metadata_words_at_top;
680 assert(bottom_sp == _bottom_address, "");
681 // Because the chunk isn't empty, we know there's a caller in the chunk, therefore the bottom-most frame
682 // should have a return barrier (installed back when we thawed it).
683 #ifdef ASSERT
684 {
685 intptr_t* retaddr_slot = (bottom_sp
686 - frame::sender_sp_ret_address_offset());
687 assert(ContinuationHelper::return_address_at(retaddr_slot)
688 == StubRoutines::cont_returnBarrier(),
689 "should be the continuation return barrier");
690 }
691 #endif
692 // We copy the fp from the chunk back to the stack because it contains some caller data,
693 // including, possibly, an oop that might have gone stale since we thawed.
694 patch_stack_pd(bottom_sp, chunk->sp_address());
695 // we don't patch the return pc at this time, so as not to make the stack unwalkable for async walks
696
697 freeze_fast_copy(chunk, chunk_start_sp CONT_JFR_ONLY(COMMA false));
698 } else { // the chunk is empty
699 const int chunk_start_sp = chunk->stack_size();
700
701 DEBUG_ONLY(_empty = true;)
702 DEBUG_ONLY(_orig_chunk_sp = chunk->start_address() + chunk_start_sp;)
703
704 chunk->set_max_thawing_size(cont_size());
705 chunk->set_bottom(chunk_start_sp - _cont.argsize() - frame::metadata_words_at_top);
706 chunk->set_sp(chunk->bottom());
707
708 freeze_fast_copy(chunk, chunk_start_sp CONT_JFR_ONLY(COMMA false));
709 }
710 }
711
712 bool FreezeBase::freeze_fast_new_chunk(stackChunkOop chunk) {
713 DEBUG_ONLY(_empty = true;)
714
715 // Install new chunk
716 _cont.set_tail(chunk);
717
718 if (UNLIKELY(chunk == nullptr || !_thread->cont_fastpath() || _barriers)) { // OOME/probably humongous
719 log_develop_trace(continuations)("Retrying slow. Barriers: %d", _barriers);
720 return false;
721 }
722
723 chunk->set_max_thawing_size(cont_size());
724
725 // in a fresh chunk, we freeze *with* the bottom-most frame's stack arguments.
726 // They'll then be stored twice: in the chunk and in the parent chunk's top frame
727 const int chunk_start_sp = cont_size() + frame::metadata_words + _monitors_in_lockstack;
728 assert(chunk_start_sp == chunk->stack_size(), "");
729
730 DEBUG_ONLY(_orig_chunk_sp = chunk->start_address() + chunk_start_sp;)
731
732 freeze_fast_copy(chunk, chunk_start_sp CONT_JFR_ONLY(COMMA true));
733
734 return true;
735 }
736
737 void FreezeBase::freeze_fast_copy(stackChunkOop chunk, int chunk_start_sp CONT_JFR_ONLY(COMMA bool chunk_is_allocated)) {
738 assert(chunk != nullptr, "");
739 assert(!chunk->has_mixed_frames(), "");
740 assert(!chunk->is_gc_mode(), "");
741 assert(!chunk->has_bitmap(), "");
742 assert(!chunk->requires_barriers(), "");
743 assert(chunk == _cont.tail(), "");
744
745 // We unwind frames after the last safepoint so that the GC will have found the oops in the frames, but before
746 // writing into the chunk. This is so that an asynchronous stack walk (not at a safepoint) that suspends us here
747 // will either see no continuation on the stack, or a consistent chunk.
748 unwind_frames();
749
750 log_develop_trace(continuations)("freeze_fast start: chunk " INTPTR_FORMAT " size: %d orig sp: %d argsize: %d",
751 p2i((oopDesc*)chunk), chunk->stack_size(), chunk_start_sp, _cont.argsize());
752 assert(chunk_start_sp <= chunk->stack_size(), "");
753 assert(chunk_start_sp >= cont_size(), "no room in the chunk");
754
755 const int chunk_new_sp = chunk_start_sp - cont_size(); // the chunk's new sp, after freeze
756 assert(!(_fast_freeze_size > 0) || (_orig_chunk_sp - (chunk->start_address() + chunk_new_sp)) == (_fast_freeze_size - _monitors_in_lockstack), "");
757
758 intptr_t* chunk_top = chunk->start_address() + chunk_new_sp;
759 #ifdef ASSERT
760 if (!_empty) {
761 intptr_t* retaddr_slot = (_orig_chunk_sp
762 - frame::sender_sp_ret_address_offset());
763 assert(ContinuationHelper::return_address_at(retaddr_slot) == chunk->pc(),
764 "unexpected saved return address");
765 }
766 #endif
767
768 log_develop_trace(continuations)("freeze_fast start: " INTPTR_FORMAT " sp: %d chunk_top: " INTPTR_FORMAT,
769 p2i(chunk->start_address()), chunk_new_sp, p2i(chunk_top));
770
771 int adjust = frame::metadata_words_at_bottom;
772 #if INCLUDE_ASAN && defined(AARCH64)
773 // Reading at offset frame::metadata_words_at_bottom from _cont_stack_top
774 // will accesss memory at the callee frame, which on preemption cases will
775 // be the VM native method being called. The Arm 64-bit ABI doesn't specify
776 // a location where the frame record (returnpc+fp) has to be stored within
777 // a stack frame, and GCC currently chooses to save it at the top of the
778 // frame (lowest address). ASan treats this memory access in the callee as
779 // an overflow access to one of the locals stored in that frame. For these
780 // preemption cases we don't need to read these words anyways so we avoid it.
781 if (_preempt) {
782 adjust = 0;
783 }
784 #endif
785 intptr_t* from = _cont_stack_top - adjust;
786 intptr_t* to = chunk_top - adjust;
787 copy_to_chunk(from, to, cont_size() + adjust);
788 // Because we're not patched yet, the chunk is now in a bad state
789
790 // patch return pc of the bottom-most frozen frame (now in the chunk)
791 // with the actual caller's return address
792 intptr_t* chunk_bottom_retaddr_slot = (chunk_top + cont_size()
793 - _cont.argsize()
794 - frame::metadata_words_at_top
795 - frame::sender_sp_ret_address_offset());
796 #ifdef ASSERT
797 if (!_empty) {
798 assert(ContinuationHelper::return_address_at(chunk_bottom_retaddr_slot)
799 == StubRoutines::cont_returnBarrier(),
800 "should be the continuation return barrier");
801 }
802 #endif
803 ContinuationHelper::patch_return_address_at(chunk_bottom_retaddr_slot,
804 chunk->pc());
805
806 // We're always writing to a young chunk, so the GC can't see it until the next safepoint.
807 chunk->set_sp(chunk_new_sp);
808
809 // set chunk->pc to the return address of the topmost frame in the chunk
810 if (_preempt) {
811 // On aarch64/riscv64, the return pc of the top frame won't necessarily be at sp[-1].
812 // Also, on x64, if the top frame is the native wrapper frame, sp[-1] will not
813 // be the pc we used when creating the oopmap. Get the top's frame last pc from
814 // the anchor instead.
815 address last_pc = _last_frame.pc();
816 ContinuationHelper::patch_return_address_at(chunk_top - frame::sender_sp_ret_address_offset(), last_pc);
817 chunk->set_pc(last_pc);
818 // For stub/native frames the fp is not used while frozen, and will be constructed
819 // again when thawing the frame (see ThawBase::handle_preempted_continuation). We
820 // patch it with a special bad address to help with debugging, particularly when
821 // inspecting frames and identifying invalid accesses.
822 patch_pd_unused(chunk_top);
823 } else {
824 chunk->set_pc(ContinuationHelper::return_address_at(
825 _cont_stack_top - frame::sender_sp_ret_address_offset()));
826 }
827
828 if (_monitors_in_lockstack > 0) {
829 freeze_lockstack(chunk);
830 }
831
832 _cont.write();
833
834 log_develop_trace(continuations)("FREEZE CHUNK #" INTPTR_FORMAT " (young)", _cont.hash());
835 LogTarget(Trace, continuations) lt;
836 if (lt.develop_is_enabled()) {
837 LogStream ls(lt);
838 chunk->print_on(true, &ls);
839 }
840
841 // Verification
842 assert(_cont.chunk_invariant(), "");
843 chunk->verify();
844
845 #if CONT_JFR
846 EventContinuationFreezeFast e;
847 if (e.should_commit()) {
848 e.set_id(cast_from_oop<u8>(chunk));
849 DEBUG_ONLY(e.set_allocate(chunk_is_allocated);)
850 e.set_size(cont_size() << LogBytesPerWord);
851 e.commit();
852 }
853 #endif
854 }
855
856 NOINLINE freeze_result FreezeBase::freeze_slow() {
857 #ifdef ASSERT
858 ResourceMark rm;
859 #endif
860
861 log_develop_trace(continuations)("freeze_slow #" INTPTR_FORMAT, _cont.hash());
862 assert(_thread->thread_state() == _thread_in_vm || _thread->thread_state() == _thread_blocked, "");
863
864 #if CONT_JFR
865 EventContinuationFreezeSlow e;
866 if (e.should_commit()) {
867 e.set_id(cast_from_oop<u8>(_cont.continuation()));
868 e.commit();
869 }
870 #endif
871
872 init_rest();
873
874 HandleMark hm(Thread::current());
875
876 frame f = freeze_start_frame();
877
878 LogTarget(Debug, continuations) lt;
879 if (lt.develop_is_enabled()) {
880 LogStream ls(lt);
881 f.print_on(&ls);
882 }
883
884 frame caller; // the frozen caller in the chunk
885 freeze_result res = recurse_freeze(f, caller, 0, false, true);
886
887 if (res == freeze_ok) {
888 finish_freeze(f, caller);
889 _cont.write();
890 }
891
892 return res;
893 }
894
895 frame FreezeBase::freeze_start_frame() {
896 if (LIKELY(!_preempt)) {
897 return freeze_start_frame_yield_stub();
898 } else {
899 return freeze_start_frame_on_preempt();
900 }
901 }
902
903 frame FreezeBase::freeze_start_frame_yield_stub() {
904 frame f = _thread->last_frame();
905 assert(SharedRuntime::cont_doYield_stub()->contains(f.pc()), "must be");
906 f = sender<ContinuationHelper::NonInterpretedUnknownFrame>(f);
907 assert(Continuation::is_frame_in_continuation(_thread->last_continuation(), f), "");
908 return f;
909 }
910
911 frame FreezeBase::freeze_start_frame_on_preempt() {
912 assert(_last_frame.sp() == _thread->last_frame().sp(), "_last_frame should be already initialized");
913 assert(Continuation::is_frame_in_continuation(_thread->last_continuation(), _last_frame), "");
914 return _last_frame;
915 }
916
917 // The parameter callee_argsize includes metadata that has to be part of caller/callee overlap.
918 NOINLINE freeze_result FreezeBase::recurse_freeze(frame& f, frame& caller, int callee_argsize, bool callee_interpreted, bool top) {
919 assert(f.unextended_sp() < _bottom_address, ""); // see recurse_freeze_java_frame
920 assert(f.is_interpreted_frame() || ((top && _preempt) == ContinuationHelper::Frame::is_stub(f.cb()))
921 || ((top && _preempt) == f.is_native_frame()), "");
922
923 if (stack_overflow()) {
924 return freeze_exception;
925 }
926
927 if (f.is_compiled_frame()) {
928 if (UNLIKELY(f.oop_map() == nullptr)) {
929 // special native frame
930 return freeze_pinned_native;
931 }
932 return recurse_freeze_compiled_frame(f, caller, callee_argsize, callee_interpreted);
933 } else if (f.is_interpreted_frame()) {
934 assert(!f.interpreter_frame_method()->is_native() || (top && _preempt), "");
935 return recurse_freeze_interpreted_frame(f, caller, callee_argsize, callee_interpreted);
936 } else if (top && _preempt) {
937 assert(f.is_native_frame() || f.is_runtime_frame(), "");
938 return f.is_native_frame() ? recurse_freeze_native_frame(f, caller) : recurse_freeze_stub_frame(f, caller);
939 } else {
940 // Frame can't be frozen. Most likely the call_stub or upcall_stub
941 // which indicates there are further natives frames up the stack.
942 return freeze_pinned_native;
943 }
944 }
945
946 // The parameter callee_argsize includes metadata that has to be part of caller/callee overlap.
947 // See also StackChunkFrameStream<frame_kind>::frame_size()
948 template<typename FKind>
949 inline freeze_result FreezeBase::recurse_freeze_java_frame(const frame& f, frame& caller, int fsize, int argsize) {
950 assert(FKind::is_instance(f), "");
951
952 assert(fsize > 0, "");
953 assert(argsize >= 0, "");
954 _freeze_size += fsize;
955 NOT_PRODUCT(_frames++;)
956
957 assert(FKind::frame_bottom(f) <= _bottom_address, "");
958
959 // We don't use FKind::frame_bottom(f) == _bottom_address because on x64 there's sometimes an extra word between
960 // enterSpecial and an interpreted frame
961 if (FKind::frame_bottom(f) >= _bottom_address - 1) {
962 return finalize_freeze(f, caller, argsize); // recursion end
963 } else {
964 frame senderf = sender<FKind>(f);
965 assert(FKind::interpreted || senderf.sp() == senderf.unextended_sp(), "");
966 freeze_result result = recurse_freeze(senderf, caller, argsize, FKind::interpreted, false); // recursive call
967 return result;
968 }
969 }
970
971 inline void FreezeBase::before_freeze_java_frame(const frame& f, const frame& caller, int fsize, int argsize, bool is_bottom_frame) {
972 LogTarget(Trace, continuations) lt;
973 if (lt.develop_is_enabled()) {
974 LogStream ls(lt);
975 ls.print_cr("======== FREEZING FRAME interpreted: %d bottom: %d", f.is_interpreted_frame(), is_bottom_frame);
976 ls.print_cr("fsize: %d argsize: %d", fsize, argsize);
977 f.print_value_on(&ls);
978 }
979 assert(caller.is_interpreted_frame() == Interpreter::contains(caller.pc()), "");
980 }
981
982 inline void FreezeBase::after_freeze_java_frame(const frame& hf, bool is_bottom_frame) {
983 LogTarget(Trace, continuations) lt;
984 if (lt.develop_is_enabled()) {
985 LogStream ls(lt);
986 DEBUG_ONLY(hf.print_value_on(&ls);)
987 assert(hf.is_heap_frame(), "should be");
988 DEBUG_ONLY(print_frame_layout(hf, false, &ls);)
989 if (is_bottom_frame) {
990 ls.print_cr("bottom h-frame:");
991 hf.print_on(&ls);
992 }
993 }
994 }
995
996 // The parameter argsize_md includes metadata that has to be part of caller/callee overlap.
997 // See also StackChunkFrameStream<frame_kind>::frame_size()
998 freeze_result FreezeBase::finalize_freeze(const frame& callee, frame& caller, int argsize_md) {
999 int argsize = argsize_md - frame::metadata_words_at_top;
1000 assert(callee.is_interpreted_frame()
1001 || ContinuationHelper::Frame::is_stub(callee.cb())
1002 || callee.cb()->as_nmethod()->is_osr_method()
1003 || argsize == _cont.argsize(), "argsize: %d cont.argsize: %d", argsize, _cont.argsize());
1004 log_develop_trace(continuations)("bottom: " INTPTR_FORMAT " count %d size: %d argsize: %d",
1005 p2i(_bottom_address), _frames, _freeze_size << LogBytesPerWord, argsize);
1006
1007 LogTarget(Trace, continuations) lt;
1008
1009 #ifdef ASSERT
1010 bool empty = _cont.is_empty();
1011 log_develop_trace(continuations)("empty: %d", empty);
1012 #endif
1013
1014 stackChunkOop chunk = _cont.tail();
1015
1016 assert(chunk == nullptr || (chunk->max_thawing_size() == 0) == chunk->is_empty(), "");
1017
1018 _freeze_size += frame::metadata_words; // for top frame's metadata
1019
1020 int overlap = 0; // the args overlap the caller -- if there is one in this chunk and is of the same kind
1021 int unextended_sp = -1;
1022 if (chunk != nullptr) {
1023 if (!chunk->is_empty()) {
1024 StackChunkFrameStream<ChunkFrames::Mixed> last(chunk);
1025 unextended_sp = chunk->to_offset(StackChunkFrameStream<ChunkFrames::Mixed>(chunk).unextended_sp());
1026 bool top_interpreted = Interpreter::contains(chunk->pc());
1027 if (callee.is_interpreted_frame() == top_interpreted) {
1028 overlap = argsize_md;
1029 }
1030 } else {
1031 unextended_sp = chunk->stack_size() - frame::metadata_words_at_top;
1032 }
1033 }
1034
1035 log_develop_trace(continuations)("finalize _size: %d overlap: %d unextended_sp: %d", _freeze_size, overlap, unextended_sp);
1036
1037 _freeze_size -= overlap;
1038 assert(_freeze_size >= 0, "");
1039
1040 assert(chunk == nullptr || chunk->is_empty()
1041 || unextended_sp == chunk->to_offset(StackChunkFrameStream<ChunkFrames::Mixed>(chunk).unextended_sp()), "");
1042 assert(chunk != nullptr || unextended_sp < _freeze_size, "");
1043
1044 _freeze_size += _monitors_in_lockstack;
1045
1046 // _barriers can be set to true by an allocation in freeze_fast, in which case the chunk is available
1047 bool allocated_old_in_freeze_fast = _barriers;
1048 assert(!allocated_old_in_freeze_fast || (unextended_sp >= _freeze_size && chunk->is_empty()),
1049 "Chunk allocated in freeze_fast is of insufficient size "
1050 "unextended_sp: %d size: %d is_empty: %d", unextended_sp, _freeze_size, chunk->is_empty());
1051 assert(!allocated_old_in_freeze_fast || (!UseZGC && !UseG1GC), "Unexpected allocation");
1052
1053 DEBUG_ONLY(bool empty_chunk = true);
1054 if (unextended_sp < _freeze_size || chunk->is_gc_mode() || (!allocated_old_in_freeze_fast && chunk->requires_barriers())) {
1055 // ALLOCATE NEW CHUNK
1056
1057 if (lt.develop_is_enabled()) {
1058 LogStream ls(lt);
1059 if (chunk == nullptr) {
1060 ls.print_cr("no chunk");
1061 } else {
1062 ls.print_cr("chunk barriers: %d _size: %d free size: %d",
1063 chunk->requires_barriers(), _freeze_size, chunk->sp() - frame::metadata_words);
1064 chunk->print_on(&ls);
1065 }
1066 }
1067
1068 _freeze_size += overlap; // we're allocating a new chunk, so no overlap
1069 // overlap = 0;
1070
1071 chunk = allocate_chunk_slow(_freeze_size, argsize_md);
1072 if (chunk == nullptr) {
1073 return freeze_exception;
1074 }
1075
1076 // Install new chunk
1077 _cont.set_tail(chunk);
1078 assert(chunk->is_empty(), "");
1079 } else {
1080 // REUSE EXISTING CHUNK
1081 log_develop_trace(continuations)("Reusing chunk mixed: %d empty: %d", chunk->has_mixed_frames(), chunk->is_empty());
1082 if (chunk->is_empty()) {
1083 int sp = chunk->stack_size() - argsize_md;
1084 chunk->set_sp(sp);
1085 chunk->set_bottom(sp);
1086 _freeze_size += overlap;
1087 assert(chunk->max_thawing_size() == 0, "");
1088 } DEBUG_ONLY(else empty_chunk = false;)
1089 }
1090 assert(!chunk->is_gc_mode(), "");
1091 assert(!chunk->has_bitmap(), "");
1092 chunk->set_has_mixed_frames(true);
1093
1094 assert(chunk->requires_barriers() == _barriers, "");
1095 assert(!_barriers || chunk->is_empty(), "");
1096
1097 assert(!chunk->is_empty() || StackChunkFrameStream<ChunkFrames::Mixed>(chunk).is_done(), "");
1098 assert(!chunk->is_empty() || StackChunkFrameStream<ChunkFrames::Mixed>(chunk).to_frame().is_empty(), "");
1099
1100 if (_preempt) {
1101 frame top_frame = _thread->last_frame();
1102 if (top_frame.is_interpreted_frame()) {
1103 // Some platforms do not save the last_sp in the top interpreter frame on VM calls.
1104 // We need it so that on resume we can restore the sp to the right place, since
1105 // thawing might add an alignment word to the expression stack (see finish_thaw()).
1106 // We do it now that we know freezing will be successful.
1107 prepare_freeze_interpreted_top_frame(top_frame);
1108 }
1109
1110 // Do this now so should_process_args_at_top() is set before calling finish_freeze
1111 // in case we might need to apply GC barriers to frames in this stackChunk.
1112 if (_thread->at_preemptable_init()) {
1113 assert(top_frame.is_interpreted_frame(), "only InterpreterRuntime::_new/resolve_from_cache allowed");
1114 chunk->set_at_klass_init(true);
1115 methodHandle m(_thread, top_frame.interpreter_frame_method());
1116 Bytecode_invoke call = Bytecode_invoke_check(m, top_frame.interpreter_frame_bci());
1117 assert(!call.is_valid() || call.is_invokestatic(), "only invokestatic allowed");
1118 if (call.is_invokestatic() && call.size_of_parameters() > 0) {
1119 assert(top_frame.interpreter_frame_expression_stack_size() > 0, "should have parameters in exp stack");
1120 chunk->set_has_args_at_top(true);
1121 }
1122 }
1123 }
1124
1125 // We unwind frames after the last safepoint so that the GC will have found the oops in the frames, but before
1126 // writing into the chunk. This is so that an asynchronous stack walk (not at a safepoint) that suspends us here
1127 // will either see no continuation or a consistent chunk.
1128 unwind_frames();
1129
1130 chunk->set_max_thawing_size(chunk->max_thawing_size() + _freeze_size - _monitors_in_lockstack - frame::metadata_words);
1131
1132 if (lt.develop_is_enabled()) {
1133 LogStream ls(lt);
1134 ls.print_cr("top chunk:");
1135 chunk->print_on(&ls);
1136 }
1137
1138 if (_monitors_in_lockstack > 0) {
1139 freeze_lockstack(chunk);
1140 }
1141
1142 // The topmost existing frame in the chunk; or an empty frame if the chunk is empty
1143 caller = StackChunkFrameStream<ChunkFrames::Mixed>(chunk).to_frame();
1144
1145 DEBUG_ONLY(_last_write = caller.unextended_sp() + (empty_chunk ? argsize_md : overlap);)
1146
1147 assert(chunk->is_in_chunk(_last_write - _freeze_size),
1148 "last_write-size: " INTPTR_FORMAT " start: " INTPTR_FORMAT, p2i(_last_write-_freeze_size), p2i(chunk->start_address()));
1149 #ifdef ASSERT
1150 if (lt.develop_is_enabled()) {
1151 LogStream ls(lt);
1152 ls.print_cr("top hframe before (freeze):");
1153 assert(caller.is_heap_frame(), "should be");
1154 caller.print_on(&ls);
1155 }
1156
1157 assert(!empty || Continuation::is_continuation_entry_frame(callee, nullptr), "");
1158
1159 frame entry = sender(callee);
1160
1161 assert((!empty && Continuation::is_return_barrier_entry(entry.pc())) || (empty && Continuation::is_continuation_enterSpecial(entry)), "");
1162 assert(callee.is_interpreted_frame() || entry.sp() == entry.unextended_sp(), "");
1163 #endif
1164
1165 return freeze_ok_bottom;
1166 }
1167
1168 // After freezing a frame we need to possibly adjust some values related to the caller frame.
1169 void FreezeBase::patch(const frame& f, frame& hf, const frame& caller, bool is_bottom_frame) {
1170 if (is_bottom_frame) {
1171 // If we're the bottom frame, we need to replace the return barrier with the real
1172 // caller's pc.
1173 address last_pc = caller.pc();
1174 assert((last_pc == nullptr) == _cont.tail()->is_empty(), "");
1175 ContinuationHelper::Frame::patch_pc(caller, last_pc);
1176 } else {
1177 assert(!caller.is_empty(), "");
1178 }
1179
1180 patch_pd(hf, caller, is_bottom_frame);
1181
1182 if (f.is_interpreted_frame()) {
1183 assert(hf.is_heap_frame(), "should be");
1184 ContinuationHelper::InterpretedFrame::patch_sender_sp(hf, caller);
1185 }
1186
1187 #ifdef ASSERT
1188 if (hf.is_compiled_frame()) {
1189 if (f.is_deoptimized_frame()) { // TODO DEOPT: long term solution: unroll on freeze and patch pc
1190 log_develop_trace(continuations)("Freezing deoptimized frame");
1191 assert(f.cb()->as_nmethod()->is_deopt_pc(f.raw_pc()), "");
1192 assert(f.cb()->as_nmethod()->is_deopt_pc(ContinuationHelper::Frame::real_pc(f)), "");
1193 }
1194 }
1195 #endif
1196 }
1197
1198 #ifdef ASSERT
1199 static void verify_frame_top(const frame& f, intptr_t* top) {
1200 ResourceMark rm;
1201 InterpreterOopMap mask;
1202 f.interpreted_frame_oop_map(&mask);
1203 assert(top <= ContinuationHelper::InterpretedFrame::frame_top(f, &mask),
1204 "frame_top: " INTPTR_FORMAT " Interpreted::frame_top: " INTPTR_FORMAT,
1205 p2i(top), p2i(ContinuationHelper::InterpretedFrame::frame_top(f, &mask)));
1206 }
1207 #endif // ASSERT
1208
1209 // The parameter callee_argsize includes metadata that has to be part of caller/callee overlap.
1210 // See also StackChunkFrameStream<frame_kind>::frame_size()
1211 NOINLINE freeze_result FreezeBase::recurse_freeze_interpreted_frame(frame& f, frame& caller,
1212 int callee_argsize /* incl. metadata */,
1213 bool callee_interpreted) {
1214 adjust_interpreted_frame_unextended_sp(f);
1215
1216 // The frame's top never includes the stack arguments to the callee
1217 intptr_t* const stack_frame_top = ContinuationHelper::InterpretedFrame::frame_top(f, callee_argsize, callee_interpreted);
1218 intptr_t* const stack_frame_bottom = ContinuationHelper::InterpretedFrame::frame_bottom(f);
1219 const int fsize = pointer_delta_as_int(stack_frame_bottom, stack_frame_top);
1220
1221 DEBUG_ONLY(verify_frame_top(f, stack_frame_top));
1222
1223 Method* frame_method = ContinuationHelper::Frame::frame_method(f);
1224 // including metadata between f and its args
1225 const int argsize = ContinuationHelper::InterpretedFrame::stack_argsize(f) + frame::metadata_words_at_top;
1226
1227 log_develop_trace(continuations)("recurse_freeze_interpreted_frame %s _size: %d fsize: %d argsize: %d callee_interpreted: %d",
1228 frame_method->name_and_sig_as_C_string(), _freeze_size, fsize, argsize, callee_interpreted);
1229 // we'd rather not yield inside methods annotated with @JvmtiMountTransition
1230 assert(!ContinuationHelper::Frame::frame_method(f)->jvmti_mount_transition(), "");
1231
1232 freeze_result result = recurse_freeze_java_frame<ContinuationHelper::InterpretedFrame>(f, caller, fsize, argsize);
1233 if (UNLIKELY(result > freeze_ok_bottom)) {
1234 return result;
1235 }
1236
1237 bool is_bottom_frame = result == freeze_ok_bottom;
1238 assert(!caller.is_empty() || is_bottom_frame, "");
1239
1240 DEBUG_ONLY(before_freeze_java_frame(f, caller, fsize, 0, is_bottom_frame);)
1241
1242 frame hf = new_heap_frame<ContinuationHelper::InterpretedFrame>(f, caller);
1243 _total_align_size += frame::align_wiggle; // add alignment room for internal interpreted frame alignment on AArch64/PPC64
1244
1245 intptr_t* heap_frame_top = ContinuationHelper::InterpretedFrame::frame_top(hf, callee_argsize, callee_interpreted);
1246 intptr_t* heap_frame_bottom = ContinuationHelper::InterpretedFrame::frame_bottom(hf);
1247 assert(heap_frame_bottom == heap_frame_top + fsize, "");
1248
1249 // Some architectures (like AArch64/PPC64/RISC-V) add padding between the locals and the fixed_frame to keep the fp 16-byte-aligned.
1250 // On those architectures we freeze the padding in order to keep the same fp-relative offsets in the fixed_frame.
1251 copy_to_chunk(stack_frame_top, heap_frame_top, fsize);
1252 assert(!is_bottom_frame || !caller.is_interpreted_frame() || (heap_frame_top + fsize) == (caller.unextended_sp() + argsize), "");
1253
1254 relativize_interpreted_frame_metadata(f, hf);
1255
1256 patch(f, hf, caller, is_bottom_frame);
1257
1258 CONT_JFR_ONLY(_jfr_info.record_interpreted_frame();)
1259 DEBUG_ONLY(after_freeze_java_frame(hf, is_bottom_frame);)
1260 caller = hf;
1261
1262 // Mark frame_method's GC epoch for class redefinition on_stack calculation.
1263 frame_method->record_gc_epoch();
1264
1265 return freeze_ok;
1266 }
1267
1268 // The parameter callee_argsize includes metadata that has to be part of caller/callee overlap.
1269 // See also StackChunkFrameStream<frame_kind>::frame_size()
1270 freeze_result FreezeBase::recurse_freeze_compiled_frame(frame& f, frame& caller,
1271 int callee_argsize /* incl. metadata */,
1272 bool callee_interpreted) {
1273 // The frame's top never includes the stack arguments to the callee
1274 intptr_t* const stack_frame_top = ContinuationHelper::CompiledFrame::frame_top(f, callee_argsize, callee_interpreted);
1275 intptr_t* const stack_frame_bottom = ContinuationHelper::CompiledFrame::frame_bottom(f);
1276 // including metadata between f and its stackargs
1277 int argsize = ContinuationHelper::CompiledFrame::stack_argsize(f) + frame::metadata_words_at_top;
1278 int fsize = pointer_delta_as_int(stack_frame_bottom + argsize, stack_frame_top);
1279
1280 int real_frame_size = 0;
1281 bool augmented = f.was_augmented_on_entry(real_frame_size);
1282 if (augmented) {
1283 assert(f.cb()->as_nmethod()->is_compiled_by_c2(), "should be c2 compiled");
1284 // The args reside inside the frame so clear argsize. If the caller is compiled,
1285 // this will cause the stack arguments passed by the caller to be freezed when
1286 // freezing the caller frame itself. If the caller is interpreted this will have
1287 // the effect of discarding the arg area created in the i2c stub.
1288 argsize = 0;
1289 fsize = real_frame_size - (callee_interpreted ? 0 : callee_argsize);
1290 }
1291
1292 log_develop_trace(continuations)("recurse_freeze_compiled_frame %s _size: %d fsize: %d argsize: %d augmented: %d",
1293 ContinuationHelper::Frame::frame_method(f) != nullptr ?
1294 ContinuationHelper::Frame::frame_method(f)->name_and_sig_as_C_string() : "",
1295 _freeze_size, fsize, argsize, augmented);
1296 // we'd rather not yield inside methods annotated with @JvmtiMountTransition
1297 assert(!ContinuationHelper::Frame::frame_method(f)->jvmti_mount_transition(), "");
1298
1299 freeze_result result = recurse_freeze_java_frame<ContinuationHelper::CompiledFrame>(f, caller, fsize, argsize);
1300 if (UNLIKELY(result > freeze_ok_bottom)) {
1301 return result;
1302 }
1303
1304 bool is_bottom_frame = result == freeze_ok_bottom;
1305 assert(!caller.is_empty() || is_bottom_frame, "");
1306 assert(!is_bottom_frame || !augmented, "thaw extended frame without caller?");
1307
1308 DEBUG_ONLY(before_freeze_java_frame(f, caller, fsize, argsize, is_bottom_frame);)
1309
1310 frame hf = new_heap_frame<ContinuationHelper::CompiledFrame>(f, caller, augmented ? real_frame_size - f.cb()->as_nmethod()->frame_size() : 0);
1311
1312 intptr_t* heap_frame_top = ContinuationHelper::CompiledFrame::frame_top(hf, callee_argsize, callee_interpreted);
1313
1314 copy_to_chunk(stack_frame_top, heap_frame_top, fsize);
1315 assert(!is_bottom_frame || !caller.is_compiled_frame() || (heap_frame_top + fsize) == (caller.unextended_sp() + argsize), "");
1316
1317 if (caller.is_interpreted_frame()) {
1318 // When thawing the frame we might need to add alignment (see Thaw::align)
1319 _total_align_size += frame::align_wiggle;
1320 }
1321
1322 patch(f, hf, caller, is_bottom_frame);
1323
1324 assert(is_bottom_frame || Interpreter::contains(ContinuationHelper::CompiledFrame::real_pc(caller)) == caller.is_interpreted_frame(), "");
1325
1326 DEBUG_ONLY(after_freeze_java_frame(hf, is_bottom_frame);)
1327 caller = hf;
1328 return freeze_ok;
1329 }
1330
1331 NOINLINE freeze_result FreezeBase::recurse_freeze_stub_frame(frame& f, frame& caller) {
1332 DEBUG_ONLY(frame fsender = sender(f);)
1333 assert(fsender.is_compiled_frame(), "sender should be compiled frame");
1334
1335 intptr_t* const stack_frame_top = ContinuationHelper::StubFrame::frame_top(f);
1336 const int fsize = f.cb()->frame_size();
1337
1338 log_develop_trace(continuations)("recurse_freeze_stub_frame %s _size: %d fsize: %d :: " INTPTR_FORMAT " - " INTPTR_FORMAT,
1339 f.cb()->name(), _freeze_size, fsize, p2i(stack_frame_top), p2i(stack_frame_top+fsize));
1340
1341 freeze_result result = recurse_freeze_java_frame<ContinuationHelper::StubFrame>(f, caller, fsize, 0);
1342 if (UNLIKELY(result > freeze_ok_bottom)) {
1343 return result;
1344 }
1345
1346 assert(result == freeze_ok, "should have caller");
1347 DEBUG_ONLY(before_freeze_java_frame(f, caller, fsize, 0, false /*is_bottom_frame*/);)
1348
1349 frame hf = new_heap_frame<ContinuationHelper::StubFrame>(f, caller);
1350 intptr_t* heap_frame_top = ContinuationHelper::StubFrame::frame_top(hf);
1351
1352 copy_to_chunk(stack_frame_top, heap_frame_top, fsize);
1353
1354 patch(f, hf, caller, false /*is_bottom_frame*/);
1355
1356 DEBUG_ONLY(after_freeze_java_frame(hf, false /*is_bottom_frame*/);)
1357
1358 caller = hf;
1359 return freeze_ok;
1360 }
1361
1362 NOINLINE freeze_result FreezeBase::recurse_freeze_native_frame(frame& f, frame& caller) {
1363 if (!f.cb()->as_nmethod()->method()->is_object_wait0()) {
1364 assert(f.cb()->as_nmethod()->method()->is_synchronized(), "");
1365 // Synchronized native method case. Unlike the interpreter native wrapper, the compiled
1366 // native wrapper tries to acquire the monitor after marshalling the arguments from the
1367 // caller into the native convention. This is so that we have a valid oopMap in case of
1368 // having to block in the slow path. But that would require freezing those registers too
1369 // and then fixing them back on thaw in case of oops. To avoid complicating things and
1370 // given that this would be a rare case anyways just pin the vthread to the carrier.
1371 return freeze_pinned_native;
1372 }
1373
1374 intptr_t* const stack_frame_top = ContinuationHelper::NativeFrame::frame_top(f);
1375 // There are no stackargs but argsize must include the metadata
1376 const int argsize = frame::metadata_words_at_top;
1377 const int fsize = f.cb()->frame_size() + argsize;
1378
1379 log_develop_trace(continuations)("recurse_freeze_native_frame %s _size: %d fsize: %d :: " INTPTR_FORMAT " - " INTPTR_FORMAT,
1380 f.cb()->name(), _freeze_size, fsize, p2i(stack_frame_top), p2i(stack_frame_top+fsize));
1381
1382 freeze_result result = recurse_freeze_java_frame<ContinuationHelper::NativeFrame>(f, caller, fsize, argsize);
1383 if (UNLIKELY(result > freeze_ok_bottom)) {
1384 return result;
1385 }
1386
1387 assert(result == freeze_ok, "should have caller frame");
1388 DEBUG_ONLY(before_freeze_java_frame(f, caller, fsize, argsize, false /* is_bottom_frame */);)
1389
1390 frame hf = new_heap_frame<ContinuationHelper::NativeFrame>(f, caller);
1391 intptr_t* heap_frame_top = ContinuationHelper::NativeFrame::frame_top(hf);
1392
1393 copy_to_chunk(stack_frame_top, heap_frame_top, fsize);
1394
1395 if (caller.is_interpreted_frame()) {
1396 // When thawing the frame we might need to add alignment (see Thaw::align)
1397 _total_align_size += frame::align_wiggle;
1398 }
1399
1400 patch(f, hf, caller, false /* is_bottom_frame */);
1401
1402 DEBUG_ONLY(after_freeze_java_frame(hf, false /* is_bottom_frame */);)
1403
1404 caller = hf;
1405 return freeze_ok;
1406 }
1407
1408 NOINLINE void FreezeBase::finish_freeze(const frame& f, const frame& top) {
1409 stackChunkOop chunk = _cont.tail();
1410
1411 LogTarget(Trace, continuations) lt;
1412 if (lt.develop_is_enabled()) {
1413 LogStream ls(lt);
1414 assert(top.is_heap_frame(), "should be");
1415 top.print_on(&ls);
1416 }
1417
1418 set_top_frame_metadata_pd(top);
1419
1420 chunk->set_sp(chunk->to_offset(top.sp()));
1421 chunk->set_pc(top.pc());
1422
1423 chunk->set_max_thawing_size(chunk->max_thawing_size() + _total_align_size);
1424
1425 assert(chunk->sp_address() - chunk->start_address() >= _monitors_in_lockstack, "clash with lockstack");
1426
1427 // At this point the chunk is consistent
1428
1429 if (UNLIKELY(_barriers)) {
1430 log_develop_trace(continuations)("do barriers on old chunk");
1431 // Serial and Parallel GC can allocate objects directly into the old generation.
1432 // Then we want to relativize the derived pointers eagerly so that
1433 // old chunks are all in GC mode.
1434 assert(!UseG1GC, "G1 can not deal with allocating outside of eden");
1435 assert(!UseZGC, "ZGC can not deal with allocating chunks visible to marking");
1436 if (UseShenandoahGC) {
1437 _cont.tail()->relativize_derived_pointers_concurrently();
1438 } else {
1439 ContinuationGCSupport::transform_stack_chunk(_cont.tail());
1440 }
1441 // For objects in the old generation we must maintain the remembered set
1442 _cont.tail()->do_barriers<stackChunkOopDesc::BarrierType::Store>();
1443 }
1444
1445 log_develop_trace(continuations)("finish_freeze: has_mixed_frames: %d", chunk->has_mixed_frames());
1446 if (lt.develop_is_enabled()) {
1447 LogStream ls(lt);
1448 chunk->print_on(true, &ls);
1449 }
1450
1451 if (lt.develop_is_enabled()) {
1452 LogStream ls(lt);
1453 ls.print_cr("top hframe after (freeze):");
1454 assert(_cont.last_frame().is_heap_frame(), "should be");
1455 _cont.last_frame().print_on(&ls);
1456 DEBUG_ONLY(print_frame_layout(top, false, &ls);)
1457 }
1458
1459 assert(_cont.chunk_invariant(), "");
1460 }
1461
1462 inline bool FreezeBase::stack_overflow() { // detect stack overflow in recursive native code
1463 JavaThread* t = !_preempt ? _thread : JavaThread::current();
1464 assert(t == JavaThread::current(), "");
1465 if (os::current_stack_pointer() < t->stack_overflow_state()->shadow_zone_safe_limit()) {
1466 if (!_preempt) {
1467 ContinuationWrapper::SafepointOp so(t, _cont); // could also call _cont.done() instead
1468 Exceptions::_throw_msg(t, __FILE__, __LINE__, vmSymbols::java_lang_StackOverflowError(), "Stack overflow while freezing");
1469 }
1470 return true;
1471 }
1472 return false;
1473 }
1474
1475 class StackChunkAllocator : public MemAllocator {
1476 const size_t _stack_size;
1477 int _argsize_md;
1478 ContinuationWrapper& _continuation_wrapper;
1479 JvmtiSampledObjectAllocEventCollector* const _jvmti_event_collector;
1480 mutable bool _took_slow_path;
1481
1482 // Does the minimal amount of initialization needed for a TLAB allocation.
1483 // We don't need to do a full initialization, as such an allocation need not be immediately walkable.
1484 virtual oop initialize(HeapWord* mem) const override {
1485 assert(_stack_size > 0, "");
1486 assert(_stack_size <= max_jint, "");
1487 assert(_word_size > _stack_size, "");
1488
1489 // zero out fields (but not the stack)
1490 const size_t hs = oopDesc::header_size();
1491 if (oopDesc::has_klass_gap()) {
1492 oopDesc::set_klass_gap(mem, 0);
1493 }
1494 Copy::fill_to_aligned_words(mem + hs, vmClasses::StackChunk_klass()->size_helper() - hs);
1495
1496 int bottom = (int)_stack_size - _argsize_md;
1497
1498 jdk_internal_vm_StackChunk::set_size(mem, (int)_stack_size);
1499 jdk_internal_vm_StackChunk::set_bottom(mem, bottom);
1500 jdk_internal_vm_StackChunk::set_sp(mem, bottom);
1501
1502 return finish(mem);
1503 }
1504
1505 stackChunkOop allocate_fast() const {
1506 if (!UseTLAB) {
1507 return nullptr;
1508 }
1509
1510 HeapWord* const mem = MemAllocator::mem_allocate_inside_tlab_fast();
1511 if (mem == nullptr) {
1512 return nullptr;
1513 }
1514
1515 oop obj = initialize(mem);
1516 return stackChunkOopDesc::cast(obj);
1517 }
1518
1519 public:
1520 StackChunkAllocator(Klass* klass,
1521 size_t word_size,
1522 Thread* thread,
1523 size_t stack_size,
1524 int argsize_md,
1525 ContinuationWrapper& continuation_wrapper,
1526 JvmtiSampledObjectAllocEventCollector* jvmti_event_collector)
1527 : MemAllocator(klass, word_size, thread),
1528 _stack_size(stack_size),
1529 _argsize_md(argsize_md),
1530 _continuation_wrapper(continuation_wrapper),
1531 _jvmti_event_collector(jvmti_event_collector),
1532 _took_slow_path(false) {}
1533
1534 // Provides it's own, specialized allocation which skips instrumentation
1535 // if the memory can be allocated without going to a slow-path.
1536 stackChunkOop allocate() const {
1537 // First try to allocate without any slow-paths or instrumentation.
1538 stackChunkOop obj = allocate_fast();
1539 if (obj != nullptr) {
1540 return obj;
1541 }
1542
1543 // Now try full-blown allocation with all expensive operations,
1544 // including potentially safepoint operations.
1545 _took_slow_path = true;
1546
1547 // Protect unhandled Loom oops
1548 ContinuationWrapper::SafepointOp so(_thread, _continuation_wrapper);
1549
1550 // Can safepoint
1551 _jvmti_event_collector->start();
1552
1553 // Can safepoint
1554 return stackChunkOopDesc::cast(MemAllocator::allocate());
1555 }
1556
1557 bool took_slow_path() const {
1558 return _took_slow_path;
1559 }
1560 };
1561
1562 template <typename ConfigT>
1563 stackChunkOop Freeze<ConfigT>::allocate_chunk(size_t stack_size, int argsize_md) {
1564 log_develop_trace(continuations)("allocate_chunk allocating new chunk");
1565
1566 InstanceStackChunkKlass* klass = InstanceStackChunkKlass::cast(vmClasses::StackChunk_klass());
1567 size_t size_in_words = klass->instance_size(stack_size);
1568
1569 if (CollectedHeap::stack_chunk_max_size() > 0 && size_in_words >= CollectedHeap::stack_chunk_max_size()) {
1570 if (!_preempt) {
1571 throw_stack_overflow_on_humongous_chunk();
1572 }
1573 return nullptr;
1574 }
1575
1576 JavaThread* current = _preempt ? JavaThread::current() : _thread;
1577 assert(current == JavaThread::current(), "should be current");
1578
1579 // Allocate the chunk.
1580 //
1581 // This might safepoint while allocating, but all safepointing due to
1582 // instrumentation have been deferred. This property is important for
1583 // some GCs, as this ensures that the allocated object is in the young
1584 // generation / newly allocated memory.
1585 StackChunkAllocator allocator(klass, size_in_words, current, stack_size, argsize_md, _cont, _jvmti_event_collector);
1586 stackChunkOop chunk = allocator.allocate();
1587
1588 if (chunk == nullptr) {
1589 return nullptr; // OOME
1590 }
1591
1592 // assert that chunk is properly initialized
1593 assert(chunk->stack_size() == (int)stack_size, "");
1594 assert(chunk->size() >= stack_size, "chunk->size(): %zu size: %zu", chunk->size(), stack_size);
1595 assert(chunk->sp() == chunk->bottom(), "");
1596 assert((intptr_t)chunk->start_address() % 8 == 0, "");
1597 assert(chunk->max_thawing_size() == 0, "");
1598 assert(chunk->pc() == nullptr, "");
1599 assert(chunk->is_empty(), "");
1600 assert(chunk->flags() == 0, "");
1601 assert(chunk->is_gc_mode() == false, "");
1602 assert(chunk->lockstack_size() == 0, "");
1603
1604 // fields are uninitialized
1605 chunk->set_parent_access<IS_DEST_UNINITIALIZED>(_cont.last_nonempty_chunk());
1606 chunk->set_cont_access<IS_DEST_UNINITIALIZED>(_cont.continuation());
1607
1608 #if INCLUDE_ZGC
1609 if (UseZGC) {
1610 ZStackChunkGCData::initialize(chunk);
1611 assert(!chunk->requires_barriers(), "ZGC always allocates in the young generation");
1612 _barriers = false;
1613 } else
1614 #endif
1615 #if INCLUDE_SHENANDOAHGC
1616 if (UseShenandoahGC) {
1617 _barriers = chunk->requires_barriers();
1618 } else
1619 #endif
1620 {
1621 if (!allocator.took_slow_path()) {
1622 // Guaranteed to be in young gen / newly allocated memory
1623 assert(!chunk->requires_barriers(), "Unfamiliar GC requires barriers on TLAB allocation");
1624 _barriers = false;
1625 } else {
1626 // Some GCs could put direct allocations in old gen for slow-path
1627 // allocations; need to explicitly check if that was the case.
1628 _barriers = chunk->requires_barriers();
1629 }
1630 }
1631
1632 if (_barriers) {
1633 log_develop_trace(continuations)("allocation requires barriers");
1634 }
1635
1636 assert(chunk->parent() == nullptr || chunk->parent()->is_stackChunk(), "");
1637
1638 return chunk;
1639 }
1640
1641 void FreezeBase::throw_stack_overflow_on_humongous_chunk() {
1642 ContinuationWrapper::SafepointOp so(_thread, _cont); // could also call _cont.done() instead
1643 Exceptions::_throw_msg(_thread, __FILE__, __LINE__, vmSymbols::java_lang_StackOverflowError(), "Humongous stack chunk");
1644 }
1645
1646 class AnchorMark : public StackObj {
1647 JavaThread* _current;
1648 frame& _top_frame;
1649 intptr_t* _last_sp_from_frame;
1650 bool _is_interpreted;
1651
1652 public:
1653 AnchorMark(JavaThread* current, frame& f) : _current(current), _top_frame(f), _is_interpreted(false) {
1654 intptr_t* sp = anchor_mark_set_pd();
1655 set_anchor(_current, sp);
1656 }
1657 ~AnchorMark() {
1658 clear_anchor(_current);
1659 anchor_mark_clear_pd();
1660 }
1661 inline intptr_t* anchor_mark_set_pd();
1662 inline void anchor_mark_clear_pd();
1663 };
1664
1665 #if INCLUDE_JVMTI
1666 static int num_java_frames(ContinuationWrapper& cont) {
1667 ResourceMark rm; // used for scope traversal in num_java_frames(nmethod*, address)
1668 int count = 0;
1669 for (stackChunkOop chunk = cont.tail(); chunk != nullptr; chunk = chunk->parent()) {
1670 count += chunk->num_java_frames();
1671 }
1672 return count;
1673 }
1674
1675 static void invalidate_jvmti_stack(JavaThread* thread) {
1676 JvmtiThreadState *state = thread->jvmti_thread_state();
1677 if (state != nullptr) {
1678 state->invalidate_cur_stack_depth();
1679 }
1680 }
1681
1682 static void jvmti_yield_cleanup(JavaThread* thread, ContinuationWrapper& cont) {
1683 if (!cont.entry()->is_virtual_thread()) {
1684 if (JvmtiExport::has_frame_pops(thread)) {
1685 int num_frames = num_java_frames(cont);
1686
1687 ContinuationWrapper::SafepointOp so(Thread::current(), cont);
1688 JvmtiExport::continuation_yield_cleanup(thread, num_frames);
1689 }
1690 invalidate_jvmti_stack(thread);
1691 }
1692 }
1693
1694 static void jvmti_mount_end(JavaThread* current, ContinuationWrapper& cont, frame top, Continuation::preempt_kind pk) {
1695 assert(current->vthread() != nullptr, "must be");
1696
1697 HandleMarkCleaner hm(current); // Cleanup all handles (including so._conth) before returning to Java.
1698 Handle vth(current, current->vthread());
1699 ContinuationWrapper::SafepointOp so(current, cont);
1700 AnchorMark am(current, top); // Set anchor so that the stack is walkable.
1701
1702 JRT_BLOCK
1703 MountUnmountDisabler::end_transition(current, vth(), true /*is_mount*/, false /*is_thread_start*/);
1704
1705 if (current->pending_contended_entered_event()) {
1706 // No monitor JVMTI events for ObjectLocker case.
1707 if (pk != Continuation::object_locker) {
1708 JvmtiExport::post_monitor_contended_entered(current, current->contended_entered_monitor());
1709 }
1710 current->set_contended_entered_monitor(nullptr);
1711 }
1712 JRT_BLOCK_END
1713 }
1714 #endif // INCLUDE_JVMTI
1715
1716 #ifdef ASSERT
1717 // There are no interpreted frames if we're not called from the interpreter and we haven't ancountered an i2c
1718 // adapter or called Deoptimization::unpack_frames. As for native frames, upcalls from JNI also go through the
1719 // interpreter (see JavaCalls::call_helper), while the UpcallLinker explicitly sets cont_fastpath.
1720 bool FreezeBase::check_valid_fast_path() {
1721 ContinuationEntry* ce = _thread->last_continuation();
1722 RegisterMap map(_thread,
1723 RegisterMap::UpdateMap::skip,
1724 RegisterMap::ProcessFrames::skip,
1725 RegisterMap::WalkContinuation::skip);
1726 map.set_include_argument_oops(false);
1727 bool is_top_frame = true;
1728 for (frame f = freeze_start_frame(); Continuation::is_frame_in_continuation(ce, f); f = f.sender(&map), is_top_frame = false) {
1729 if (!((f.is_compiled_frame() && !f.is_deoptimized_frame()) || (is_top_frame && (f.is_runtime_frame() || f.is_native_frame())))) {
1730 return false;
1731 }
1732 }
1733 return true;
1734 }
1735
1736 static void verify_frame_kind(frame& top, Continuation::preempt_kind preempt_kind, Method** m_ptr, const char** code_name_ptr, int* bci_ptr, stackChunkOop chunk) {
1737 Method* m;
1738 const char* code_name;
1739 int bci;
1740 ResourceMark rm;
1741
1742 if (preempt_kind == Continuation::monitorenter) {
1743 assert(top.is_interpreted_frame() || top.is_runtime_frame(), "unexpected %sframe",
1744 top.is_compiled_frame() ? "compiled " : top.is_native_frame() ? "native " : "");
1745 bool at_sync_method;
1746 if (top.is_interpreted_frame()) {
1747 m = top.interpreter_frame_method();
1748 assert(!m->is_native() || m->is_synchronized(), "invalid method %s", m->external_name());
1749 address bcp = top.interpreter_frame_bcp();
1750 assert(bcp != nullptr || m->is_native(), "");
1751 at_sync_method = m->is_synchronized() && (bcp == nullptr || bcp == m->code_base());
1752 // bcp is advanced on monitorenter before making the VM call, adjust for that.
1753 bool at_sync_bytecode = bcp > m->code_base() && Bytecode(m, bcp - 1).code() == Bytecodes::Code::_monitorenter;
1754 assert(at_sync_method || at_sync_bytecode, "");
1755 bci = at_sync_method ? -1 : top.interpreter_frame_bci();
1756 } else {
1757 JavaThread* current = JavaThread::current();
1758 CodeBlob* cb = top.cb();
1759 RegisterMap reg_map(current,
1760 RegisterMap::UpdateMap::skip,
1761 RegisterMap::ProcessFrames::skip,
1762 RegisterMap::WalkContinuation::include);
1763 if (top.is_heap_frame()) {
1764 assert(chunk != nullptr, "");
1765 reg_map.set_stack_chunk(chunk);
1766 top = chunk->relativize(top);
1767 top.set_frame_index(0);
1768 }
1769 frame fr = top.sender(®_map);
1770 vframe* vf = vframe::new_vframe(&fr, ®_map, current);
1771 compiledVFrame* cvf = compiledVFrame::cast(vf);
1772 m = cvf->method();
1773 bci = cvf->scope()->bci();
1774 at_sync_method = bci == SynchronizationEntryBCI;
1775 assert(!at_sync_method || m->is_synchronized(), "bci is %d but method %s is not synchronized", bci, m->external_name());
1776 bool is_c1_monitorenter = false, is_c2_monitorenter = false;
1777 COMPILER1_PRESENT(is_c1_monitorenter = cb == Runtime1::blob_for(StubId::c1_monitorenter_id) ||
1778 cb == Runtime1::blob_for(StubId::c1_monitorenter_nofpu_id);)
1779 COMPILER2_PRESENT(is_c2_monitorenter = cb == CodeCache::find_blob(OptoRuntime::complete_monitor_locking_Java());)
1780 assert(is_c1_monitorenter || is_c2_monitorenter, "wrong runtime stub frame");
1781 }
1782 code_name = at_sync_method ? "synchronized method" : "monitorenter";
1783 } else if (preempt_kind == Continuation::object_wait) {
1784 assert(top.is_interpreted_frame() || top.is_native_frame(), "");
1785 m = top.is_interpreted_frame() ? top.interpreter_frame_method() : top.cb()->as_nmethod()->method();
1786 assert(m->is_object_wait0(), "");
1787 bci = 0;
1788 code_name = "";
1789 } else {
1790 assert(preempt_kind == Continuation::object_locker, "invalid preempt kind");
1791 assert(top.is_interpreted_frame(), "");
1792 m = top.interpreter_frame_method();
1793 Bytecode current_bytecode = Bytecode(m, top.interpreter_frame_bcp());
1794 Bytecodes::Code code = current_bytecode.code();
1795 assert(code == Bytecodes::Code::_new || code == Bytecodes::Code::_invokestatic ||
1796 (code == Bytecodes::Code::_getstatic || code == Bytecodes::Code::_putstatic), "invalid bytecode");
1797 bci = top.interpreter_frame_bci();
1798 code_name = Bytecodes::name(current_bytecode.code());
1799 }
1800 assert(bci >= 0 || m->is_synchronized(), "invalid bci:%d at method %s", bci, m->external_name());
1801
1802 if (m_ptr != nullptr) {
1803 *m_ptr = m;
1804 *code_name_ptr = code_name;
1805 *bci_ptr = bci;
1806 }
1807 }
1808
1809 static void log_preempt_after_freeze(const ContinuationWrapper& cont) {
1810 JavaThread* current = cont.thread();
1811 int64_t tid = current->monitor_owner_id();
1812
1813 StackChunkFrameStream<ChunkFrames::Mixed> sfs(cont.tail());
1814 frame top_frame = sfs.to_frame();
1815 bool at_init = current->at_preemptable_init();
1816 bool at_enter = current->current_pending_monitor() != nullptr;
1817 bool at_wait = current->current_waiting_monitor() != nullptr;
1818 assert((at_enter && !at_wait) || (!at_enter && at_wait), "");
1819 Continuation::preempt_kind pk = at_init ? Continuation::object_locker : at_enter ? Continuation::monitorenter : Continuation::object_wait;
1820
1821 Method* m = nullptr;
1822 const char* code_name = nullptr;
1823 int bci = InvalidFrameStateBci;
1824 verify_frame_kind(top_frame, pk, &m, &code_name, &bci, cont.tail());
1825 assert(m != nullptr && code_name != nullptr && bci != InvalidFrameStateBci, "should be set");
1826
1827 ResourceMark rm(current);
1828 if (bci < 0) {
1829 log_trace(continuations, preempt)("Preempted " INT64_FORMAT " while synchronizing on %smethod %s", tid, m->is_native() ? "native " : "", m->external_name());
1830 } else if (m->is_object_wait0()) {
1831 log_trace(continuations, preempt)("Preempted " INT64_FORMAT " at native method %s", tid, m->external_name());
1832 } else {
1833 Klass* k = current->preempt_init_klass();
1834 assert(k != nullptr || !at_init, "");
1835 log_trace(continuations, preempt)("Preempted " INT64_FORMAT " at %s(bci:%d) in method %s %s%s", tid, code_name, bci,
1836 m->external_name(), at_init ? "trying to initialize klass " : "", at_init ? k->external_name() : "");
1837 }
1838 }
1839 #endif // ASSERT
1840
1841 static inline freeze_result freeze_epilog(ContinuationWrapper& cont) {
1842 verify_continuation(cont.continuation());
1843 assert(!cont.is_empty(), "");
1844
1845 log_develop_debug(continuations)("=== End of freeze cont ### #" INTPTR_FORMAT, cont.hash());
1846 return freeze_ok;
1847 }
1848
1849 static freeze_result freeze_epilog(JavaThread* thread, ContinuationWrapper& cont, freeze_result res) {
1850 if (UNLIKELY(res != freeze_ok)) {
1851 JFR_ONLY(thread->set_last_freeze_fail_result(res);)
1852 verify_continuation(cont.continuation());
1853 log_develop_trace(continuations)("=== end of freeze (fail %d)", res);
1854 return res;
1855 }
1856
1857 JVMTI_ONLY(jvmti_yield_cleanup(thread, cont)); // can safepoint
1858 return freeze_epilog(cont);
1859 }
1860
1861 static freeze_result preempt_epilog(ContinuationWrapper& cont, freeze_result res, frame& old_last_frame) {
1862 if (UNLIKELY(res != freeze_ok)) {
1863 verify_continuation(cont.continuation());
1864 log_develop_trace(continuations)("=== end of freeze (fail %d)", res);
1865 return res;
1866 }
1867
1868 // Set up things so that on return to Java we jump to preempt stub.
1869 patch_return_pc_with_preempt_stub(old_last_frame);
1870 cont.tail()->set_preempted(true);
1871 DEBUG_ONLY(log_preempt_after_freeze(cont);)
1872 return freeze_epilog(cont);
1873 }
1874
1875 template<typename ConfigT, bool preempt>
1876 static inline freeze_result freeze_internal(JavaThread* current, intptr_t* const sp) {
1877 assert(!current->has_pending_exception(), "");
1878
1879 #ifdef ASSERT
1880 log_trace(continuations)("~~~~ freeze sp: " INTPTR_FORMAT "JavaThread: " INTPTR_FORMAT, p2i(current->last_continuation()->entry_sp()), p2i(current));
1881 log_frames(current);
1882 #endif
1883
1884 CONT_JFR_ONLY(EventContinuationFreeze event;)
1885
1886 ContinuationEntry* entry = current->last_continuation();
1887
1888 oop oopCont = entry->cont_oop(current);
1889 assert(oopCont == current->last_continuation()->cont_oop(current), "");
1890 assert(ContinuationEntry::assert_entry_frame_laid_out(current), "");
1891
1892 verify_continuation(oopCont);
1893 ContinuationWrapper cont(current, oopCont);
1894 log_develop_debug(continuations)("FREEZE #" INTPTR_FORMAT " " INTPTR_FORMAT, cont.hash(), p2i((oopDesc*)oopCont));
1895
1896 assert(entry->is_virtual_thread() == (entry->scope(current) == java_lang_VirtualThread::vthread_scope()), "");
1897
1898 if (entry->is_pinned()) {
1899 log_develop_debug(continuations)("PINNED due to critical section");
1900 verify_continuation(cont.continuation());
1901 const freeze_result res = freeze_pinned_cs;
1902 if (!preempt) {
1903 JFR_ONLY(current->set_last_freeze_fail_result(res);)
1904 }
1905 log_develop_trace(continuations)("=== end of freeze (fail %d)", res);
1906 // Avoid Thread.yield() loops without safepoint polls.
1907 if (SafepointMechanism::should_process(current) && !preempt) {
1908 cont.done(); // allow safepoint
1909 ThreadInVMfromJava tivmfj(current);
1910 }
1911 return res;
1912 }
1913
1914 Freeze<ConfigT> freeze(current, cont, sp, preempt);
1915
1916 assert(!current->cont_fastpath() || freeze.check_valid_fast_path(), "");
1917 bool fast = UseContinuationFastPath && current->cont_fastpath();
1918 if (fast && freeze.size_if_fast_freeze_available() > 0) {
1919 freeze.freeze_fast_existing_chunk();
1920 CONT_JFR_ONLY(freeze.jfr_info().post_jfr_event(&event, oopCont, current);)
1921 return !preempt ? freeze_epilog(cont) : preempt_epilog(cont, freeze_ok, freeze.last_frame());
1922 }
1923
1924 if (preempt) {
1925 JvmtiSampledObjectAllocEventCollector jsoaec(false);
1926 freeze.set_jvmti_event_collector(&jsoaec);
1927
1928 freeze_result res = fast ? freeze.try_freeze_fast() : freeze.freeze_slow();
1929
1930 CONT_JFR_ONLY(freeze.jfr_info().post_jfr_event(&event, oopCont, current);)
1931 preempt_epilog(cont, res, freeze.last_frame());
1932 return res;
1933 }
1934
1935 log_develop_trace(continuations)("chunk unavailable; transitioning to VM");
1936 assert(current == JavaThread::current(), "must be current thread");
1937 JRT_BLOCK
1938 // delays a possible JvmtiSampledObjectAllocEventCollector in alloc_chunk
1939 JvmtiSampledObjectAllocEventCollector jsoaec(false);
1940 freeze.set_jvmti_event_collector(&jsoaec);
1941
1942 freeze_result res = fast ? freeze.try_freeze_fast() : freeze.freeze_slow();
1943
1944 CONT_JFR_ONLY(freeze.jfr_info().post_jfr_event(&event, oopCont, current);)
1945 freeze_epilog(current, cont, res);
1946 cont.done(); // allow safepoint in the transition back to Java
1947 return res;
1948 JRT_BLOCK_END
1949 }
1950
1951 static freeze_result is_pinned0(JavaThread* thread, oop cont_scope, bool safepoint) {
1952 ContinuationEntry* entry = thread->last_continuation();
1953 if (entry == nullptr) {
1954 return freeze_ok;
1955 }
1956 if (entry->is_pinned()) {
1957 return freeze_pinned_cs;
1958 }
1959
1960 RegisterMap map(thread,
1961 RegisterMap::UpdateMap::include,
1962 RegisterMap::ProcessFrames::skip,
1963 RegisterMap::WalkContinuation::skip);
1964 map.set_include_argument_oops(false);
1965 frame f = thread->last_frame();
1966
1967 if (!safepoint) {
1968 f = f.sender(&map); // this is the yield frame
1969 } else { // safepoint yield
1970 #if (defined(X86) || defined(AARCH64) || defined(RISCV64)) && !defined(ZERO)
1971 f.set_fp(f.real_fp()); // Instead of this, maybe in ContinuationWrapper::set_last_frame always use the real_fp?
1972 #else
1973 Unimplemented();
1974 #endif
1975 if (!Interpreter::contains(f.pc())) {
1976 assert(ContinuationHelper::Frame::is_stub(f.cb()), "must be");
1977 assert(f.oop_map() != nullptr, "must be");
1978 f.oop_map()->update_register_map(&f, &map); // we have callee-save registers in this case
1979 }
1980 }
1981
1982 while (true) {
1983 if ((f.is_interpreted_frame() && f.interpreter_frame_method()->is_native()) || f.is_native_frame()) {
1984 return freeze_pinned_native;
1985 }
1986
1987 f = f.sender(&map);
1988 if (!Continuation::is_frame_in_continuation(entry, f)) {
1989 oop scope = jdk_internal_vm_Continuation::scope(entry->cont_oop(thread));
1990 if (scope == cont_scope) {
1991 break;
1992 }
1993 entry = entry->parent();
1994 if (entry == nullptr) {
1995 break;
1996 }
1997 if (entry->is_pinned()) {
1998 return freeze_pinned_cs;
1999 }
2000 }
2001 }
2002 return freeze_ok;
2003 }
2004
2005 /////////////// THAW ////
2006
2007 static int thaw_size(stackChunkOop chunk) {
2008 int size = chunk->max_thawing_size();
2009 size += frame::metadata_words; // For the top pc+fp in push_return_frame or top = stack_sp - frame::metadata_words in thaw_fast
2010 size += 2*frame::align_wiggle; // in case of alignments at the top and bottom
2011 return size;
2012 }
2013
2014 // make room on the stack for thaw
2015 // returns the size in bytes, or 0 on failure
2016 static inline int prepare_thaw_internal(JavaThread* thread, bool return_barrier) {
2017 log_develop_trace(continuations)("~~~~ prepare_thaw return_barrier: %d", return_barrier);
2018
2019 assert(thread == JavaThread::current(), "");
2020
2021 ContinuationEntry* ce = thread->last_continuation();
2022 assert(ce != nullptr, "");
2023 oop continuation = ce->cont_oop(thread);
2024 assert(continuation == get_continuation(thread), "");
2025 verify_continuation(continuation);
2026
2027 stackChunkOop chunk = jdk_internal_vm_Continuation::tail(continuation);
2028 assert(chunk != nullptr, "");
2029
2030 // The tail can be empty because it might still be available for another freeze.
2031 // However, here we want to thaw, so we get rid of it (it will be GCed).
2032 if (UNLIKELY(chunk->is_empty())) {
2033 chunk = chunk->parent();
2034 assert(chunk != nullptr, "");
2035 assert(!chunk->is_empty(), "");
2036 jdk_internal_vm_Continuation::set_tail(continuation, chunk);
2037 }
2038
2039 // Verification
2040 chunk->verify();
2041 assert(chunk->max_thawing_size() > 0, "chunk invariant violated; expected to not be empty");
2042
2043 // Only make space for the last chunk because we only thaw from the last chunk
2044 int size = thaw_size(chunk) << LogBytesPerWord;
2045
2046 const address bottom = (address)thread->last_continuation()->entry_sp();
2047 // 300 is an estimate for stack size taken for this native code, in addition to StackShadowPages
2048 // for the Java frames in the check below.
2049 if (!stack_overflow_check(thread, size + 300, bottom)) {
2050 return 0;
2051 }
2052
2053 log_develop_trace(continuations)("prepare_thaw bottom: " INTPTR_FORMAT " top: " INTPTR_FORMAT " size: %d",
2054 p2i(bottom), p2i(bottom - size), size);
2055 return size;
2056 }
2057
2058 class ThawBase : public StackObj {
2059 protected:
2060 JavaThread* _thread;
2061 ContinuationWrapper& _cont;
2062 CONT_JFR_ONLY(FreezeThawJfrInfo _jfr_info;)
2063
2064 intptr_t* _fastpath;
2065 bool _barriers;
2066 bool _preempted_case;
2067 bool _should_patch_caller_pc;
2068 bool _process_args_at_top;
2069 intptr_t* _top_unextended_sp_before_thaw;
2070 int _align_size;
2071 DEBUG_ONLY(intptr_t* _top_stack_address;)
2072 DEBUG_ONLY(address _caller_raw_pc;)
2073
2074 // Only used for preemption on ObjectLocker
2075 ObjectMonitor* _init_lock;
2076
2077 StackChunkFrameStream<ChunkFrames::Mixed> _stream;
2078
2079 NOT_PRODUCT(int _frames;)
2080
2081 protected:
2082 ThawBase(JavaThread* thread, ContinuationWrapper& cont) :
2083 _thread(thread), _cont(cont),
2084 _fastpath(nullptr) {
2085 DEBUG_ONLY(_top_unextended_sp_before_thaw = nullptr;)
2086 assert (cont.tail() != nullptr, "no last chunk");
2087 DEBUG_ONLY(_top_stack_address = _cont.entrySP() - thaw_size(cont.tail());)
2088 }
2089
2090 void clear_chunk(stackChunkOop chunk);
2091 template<bool check_stub>
2092 int remove_top_compiled_frame_from_chunk(stackChunkOop chunk, int &argsize);
2093 int remove_scalarized_frames(StackChunkFrameStream<ChunkFrames::CompiledOnly>& scfs, int &argsize);
2094 void check_top_for_deoptimization(stackChunkOop chunk);
2095 void copy_from_chunk(intptr_t* from, intptr_t* to, int size);
2096
2097 void thaw_lockstack(stackChunkOop chunk);
2098
2099 // fast path
2100 inline void prefetch_chunk_pd(void* start, int size_words);
2101 void patch_return(intptr_t* sp, bool is_last);
2102
2103 intptr_t* handle_preempted_continuation(intptr_t* sp, Continuation::preempt_kind preempt_kind, bool fast_case);
2104 inline intptr_t* push_cleanup_continuation();
2105 inline intptr_t* push_preempt_adapter();
2106 intptr_t* redo_vmcall(JavaThread* current, frame& top);
2107 void throw_interrupted_exception(JavaThread* current, frame& top);
2108
2109 void recurse_thaw(const frame& heap_frame, frame& caller, int num_frames, bool top_on_preempt_case);
2110 void finish_thaw(frame& f);
2111
2112 private:
2113 template<typename FKind> bool recurse_thaw_java_frame(frame& caller, int num_frames);
2114 void finalize_thaw(frame& entry, int argsize);
2115
2116 inline bool seen_by_gc();
2117
2118 inline void before_thaw_java_frame(const frame& hf, const frame& caller, bool bottom, int num_frame);
2119 inline void after_thaw_java_frame(const frame& f, bool bottom);
2120 inline void patch(frame& f, const frame& caller, bool bottom);
2121 void clear_bitmap_bits(address start, address end);
2122
2123 NOINLINE void recurse_thaw_interpreted_frame(const frame& hf, frame& caller, int num_frames, bool is_top);
2124 void recurse_thaw_compiled_frame(const frame& hf, frame& caller, int num_frames, bool stub_caller);
2125 void recurse_thaw_stub_frame(const frame& hf, frame& caller, int num_frames);
2126 void recurse_thaw_native_frame(const frame& hf, frame& caller, int num_frames);
2127
2128 void push_return_frame(const frame& f);
2129 inline frame new_entry_frame();
2130 template<typename FKind> frame new_stack_frame(const frame& hf, frame& caller, bool bottom, int size_adjust = 0);
2131 inline void patch_pd(frame& f, const frame& sender);
2132 inline void patch_pd(frame& f, intptr_t* caller_sp);
2133 inline intptr_t* align(const frame& hf, intptr_t* frame_sp, frame& caller, bool bottom);
2134
2135 void maybe_set_fastpath(intptr_t* sp) { if (sp > _fastpath) _fastpath = sp; }
2136
2137 static inline void derelativize_interpreted_frame_metadata(const frame& hf, const frame& f);
2138
2139 public:
2140 CONT_JFR_ONLY(FreezeThawJfrInfo& jfr_info() { return _jfr_info; })
2141 };
2142
2143 template <typename ConfigT>
2144 class Thaw : public ThawBase {
2145 public:
2146 Thaw(JavaThread* thread, ContinuationWrapper& cont) : ThawBase(thread, cont) {}
2147
2148 inline bool can_thaw_fast(stackChunkOop chunk) {
2149 return !_barriers
2150 && _thread->cont_fastpath_thread_state()
2151 && !chunk->has_thaw_slowpath_condition()
2152 && !PreserveFramePointer;
2153 }
2154
2155 inline intptr_t* thaw(Continuation::thaw_kind kind);
2156 template<bool check_stub = false>
2157 NOINLINE intptr_t* thaw_fast(stackChunkOop chunk);
2158 NOINLINE intptr_t* thaw_slow(stackChunkOop chunk, Continuation::thaw_kind kind);
2159 inline void patch_caller_links(intptr_t* sp, intptr_t* bottom);
2160 };
2161
2162 template <typename ConfigT>
2163 inline intptr_t* Thaw<ConfigT>::thaw(Continuation::thaw_kind kind) {
2164 verify_continuation(_cont.continuation());
2165 assert(!jdk_internal_vm_Continuation::done(_cont.continuation()), "");
2166 assert(!_cont.is_empty(), "");
2167
2168 stackChunkOop chunk = _cont.tail();
2169 assert(chunk != nullptr, "guaranteed by prepare_thaw");
2170 assert(!chunk->is_empty(), "guaranteed by prepare_thaw");
2171
2172 _barriers = chunk->requires_barriers();
2173 return (LIKELY(can_thaw_fast(chunk))) ? thaw_fast(chunk)
2174 : thaw_slow(chunk, kind);
2175 }
2176
2177 class ReconstructedStack : public StackObj {
2178 intptr_t* _base; // _cont.entrySP(); // top of the entry frame
2179 int _thaw_size;
2180 int _argsize;
2181 public:
2182 ReconstructedStack(intptr_t* base, int thaw_size, int argsize)
2183 : _base(base), _thaw_size(thaw_size - (argsize == 0 ? frame::metadata_words_at_top : 0)), _argsize(argsize) {
2184 // The only possible source of misalignment is stack-passed arguments b/c compiled frames are 16-byte aligned.
2185 assert(argsize != 0 || (_base - _thaw_size) == ContinuationHelper::frame_align_pointer(_base - _thaw_size), "");
2186 // We're at most one alignment word away from entrySP
2187 assert(_base - 1 <= top() + total_size() + frame::metadata_words_at_bottom, "missed entry frame");
2188 }
2189
2190 int entry_frame_extension() const { return _argsize + (_argsize > 0 ? frame::metadata_words_at_top : 0); }
2191
2192 // top and bottom stack pointers
2193 intptr_t* sp() const { return ContinuationHelper::frame_align_pointer(_base - _thaw_size); }
2194 intptr_t* bottom_sp() const { return ContinuationHelper::frame_align_pointer(_base - entry_frame_extension()); }
2195
2196 // several operations operate on the totality of the stack being reconstructed,
2197 // including the metadata words
2198 intptr_t* top() const { return sp() - frame::metadata_words_at_bottom; }
2199 int total_size() const { return _thaw_size + frame::metadata_words_at_bottom; }
2200 };
2201
2202 inline void ThawBase::clear_chunk(stackChunkOop chunk) {
2203 chunk->set_sp(chunk->bottom());
2204 chunk->set_max_thawing_size(0);
2205 }
2206
2207 void ThawBase::check_top_for_deoptimization(stackChunkOop chunk) {
2208 StackChunkFrameStream<ChunkFrames::CompiledOnly> f(chunk);
2209 if (f.is_stub()) {
2210 f.next(SmallRegisterMap::instance_no_args(), true /* stop */);
2211 assert(!f.is_done(), "");
2212
2213 f.get_cb();
2214 assert(f.is_compiled(), "");
2215 if (f.cb()->as_nmethod()->is_marked_for_deoptimization()) {
2216 // The caller of the runtime stub when the continuation is preempted is not at a
2217 // Java call instruction, and so cannot rely on nmethod patching for deopt.
2218 log_develop_trace(continuations)("Deoptimizing runtime stub caller");
2219 f.to_frame().deoptimize(nullptr); // the null thread simply avoids the assertion in deoptimize which we're not set up for
2220 }
2221 }
2222 }
2223
2224 int ThawBase::remove_scalarized_frames(StackChunkFrameStream<ChunkFrames::CompiledOnly>& f, int &argsize) {
2225 intptr_t* top = f.sp();
2226
2227 while (f.cb()->as_nmethod()->needs_stack_repair()) {
2228 f.next(SmallRegisterMap::instance_no_args(), false /* stop */);
2229 }
2230 assert(!f.is_done(), "");
2231 assert(f.is_compiled(), "");
2232
2233 intptr_t* bottom = f.sp() + f.cb()->frame_size();
2234 argsize = f.stack_argsize();
2235 return bottom - top;
2236 }
2237
2238 template<bool check_stub>
2239 int ThawBase::remove_top_compiled_frame_from_chunk(stackChunkOop chunk, int &argsize) {
2240 bool empty = false;
2241 StackChunkFrameStream<ChunkFrames::CompiledOnly> f(chunk);
2242 DEBUG_ONLY(intptr_t* const chunk_sp = chunk->start_address() + chunk->sp();)
2243 assert(chunk_sp == f.sp(), "");
2244 assert(chunk_sp == f.unextended_sp(), "");
2245
2246 int frame_size = f.cb()->frame_size();
2247 argsize = f.stack_argsize();
2248
2249 assert(!f.is_stub() || check_stub, "");
2250 if (check_stub && f.is_stub()) {
2251 // If we don't thaw the top compiled frame too, after restoring the saved
2252 // registers back in Java, we would hit the return barrier to thaw one more
2253 // frame effectively overwriting the restored registers during that call.
2254 f.next(SmallRegisterMap::instance_no_args(), true /* stop */);
2255 assert(!f.is_done(), "");
2256
2257 f.get_cb();
2258 assert(f.is_compiled(), "");
2259
2260 if (f.cb()->as_nmethod()->is_marked_for_deoptimization()) {
2261 // The caller of the runtime stub when the continuation is preempted is not at a
2262 // Java call instruction, and so cannot rely on nmethod patching for deopt.
2263 log_develop_trace(continuations)("Deoptimizing runtime stub caller");
2264 f.to_frame().deoptimize(nullptr); // the null thread simply avoids the assertion in deoptimize which we're not set up for
2265 }
2266
2267 if (f.cb()->as_nmethod()->needs_stack_repair()) {
2268 frame_size += remove_scalarized_frames(f, argsize);
2269 } else {
2270 frame_size += f.cb()->frame_size();
2271 argsize = f.stack_argsize();
2272 }
2273 } else if (f.cb()->as_nmethod()->needs_stack_repair()) {
2274 frame_size = remove_scalarized_frames(f, argsize);
2275 }
2276
2277 f.next(SmallRegisterMap::instance_no_args(), true /* stop */);
2278 empty = f.is_done();
2279 assert(!empty || argsize == chunk->argsize(), "");
2280
2281 if (empty) {
2282 clear_chunk(chunk);
2283 } else {
2284 chunk->set_sp(chunk->sp() + frame_size);
2285 chunk->set_max_thawing_size(chunk->max_thawing_size() - frame_size);
2286 // We set chunk->pc to the return pc into the next frame
2287 chunk->set_pc(f.pc());
2288 #ifdef ASSERT
2289 {
2290 intptr_t* retaddr_slot = (chunk_sp
2291 + frame_size
2292 - frame::sender_sp_ret_address_offset());
2293 assert(f.pc() == ContinuationHelper::return_address_at(retaddr_slot),
2294 "unexpected pc");
2295 }
2296 #endif
2297 }
2298 assert(empty == chunk->is_empty(), "");
2299 // returns the size required to store the frame on stack, and because it is a
2300 // compiled frame, it must include a copy of the arguments passed by the caller
2301 return frame_size + argsize + frame::metadata_words_at_top;
2302 }
2303
2304 void ThawBase::thaw_lockstack(stackChunkOop chunk) {
2305 int lockStackSize = chunk->lockstack_size();
2306 assert(lockStackSize > 0 && lockStackSize <= LockStack::CAPACITY, "");
2307
2308 oop tmp_lockstack[LockStack::CAPACITY];
2309 chunk->transfer_lockstack(tmp_lockstack, _barriers);
2310 _thread->lock_stack().move_from_address(tmp_lockstack, lockStackSize);
2311
2312 chunk->set_lockstack_size(0);
2313 chunk->set_has_lockstack(false);
2314 }
2315
2316 void ThawBase::copy_from_chunk(intptr_t* from, intptr_t* to, int size) {
2317 assert(to >= _top_stack_address, "overwrote past thawing space"
2318 " to: " INTPTR_FORMAT " top_address: " INTPTR_FORMAT, p2i(to), p2i(_top_stack_address));
2319 assert(to + size <= _cont.entrySP(), "overwrote past thawing space");
2320 _cont.tail()->copy_from_chunk_to_stack(from, to, size);
2321 CONT_JFR_ONLY(_jfr_info.record_size_copied(size);)
2322 }
2323
2324 void ThawBase::patch_return(intptr_t* sp, bool is_last) {
2325 log_develop_trace(continuations)("thaw_fast patching -- sp: " INTPTR_FORMAT, p2i(sp));
2326
2327 address pc = !is_last ? StubRoutines::cont_returnBarrier() : _cont.entryPC();
2328 ContinuationHelper::patch_return_address_at(
2329 sp - frame::sender_sp_ret_address_offset(),
2330 pc);
2331 }
2332
2333 template <typename ConfigT>
2334 template<bool check_stub>
2335 NOINLINE intptr_t* Thaw<ConfigT>::thaw_fast(stackChunkOop chunk) {
2336 assert(chunk == _cont.tail(), "");
2337 assert(!chunk->has_mixed_frames(), "");
2338 assert(!chunk->requires_barriers(), "");
2339 assert(!chunk->has_bitmap(), "");
2340 assert(!_thread->is_interp_only_mode(), "");
2341
2342 LogTarget(Trace, continuations) lt;
2343 if (lt.develop_is_enabled()) {
2344 LogStream ls(lt);
2345 ls.print_cr("thaw_fast");
2346 chunk->print_on(true, &ls);
2347 }
2348
2349 // Below this heuristic, we thaw the whole chunk, above it we thaw just one frame.
2350 static const int threshold = 500; // words
2351
2352 const int full_chunk_size = chunk->stack_size() - chunk->sp(); // this initial size could be reduced if it's a partial thaw
2353 int argsize, thaw_size;
2354
2355 intptr_t* const chunk_sp = chunk->start_address() + chunk->sp();
2356
2357 bool partial, empty;
2358 if (LIKELY(!ForceSingleFrameThaw && (full_chunk_size < threshold))) {
2359 prefetch_chunk_pd(chunk->start_address(), full_chunk_size); // prefetch anticipating memcpy starting at highest address
2360
2361 if (check_stub) {
2362 check_top_for_deoptimization(chunk);
2363 }
2364 partial = false;
2365 argsize = chunk->argsize(); // must be called *before* clearing the chunk
2366 clear_chunk(chunk);
2367 thaw_size = full_chunk_size;
2368 empty = true;
2369 } else { // thaw a single frame
2370 partial = true;
2371 thaw_size = remove_top_compiled_frame_from_chunk<check_stub>(chunk, argsize);
2372 empty = chunk->is_empty();
2373 }
2374
2375 // Are we thawing the last frame(s) in the continuation
2376 const bool is_last = empty && chunk->parent() == nullptr;
2377 assert(!is_last || argsize == 0, "");
2378
2379 log_develop_trace(continuations)("thaw_fast partial: %d is_last: %d empty: %d size: %d argsize: %d entrySP: " PTR_FORMAT,
2380 partial, is_last, empty, thaw_size, argsize, p2i(_cont.entrySP()));
2381
2382 ReconstructedStack rs(_cont.entrySP(), thaw_size, argsize);
2383
2384 // also copy metadata words at frame bottom
2385 copy_from_chunk(chunk_sp - frame::metadata_words_at_bottom, rs.top(), rs.total_size());
2386
2387 // update the ContinuationEntry
2388 _cont.set_argsize(argsize);
2389 log_develop_trace(continuations)("setting entry argsize: %d", _cont.argsize());
2390 assert(rs.bottom_sp() == _cont.entry()->bottom_sender_sp(), "");
2391
2392 // install the return barrier if not last frame, or the entry's pc if last
2393 patch_return(rs.bottom_sp(), is_last);
2394
2395 // insert the back links from callee to caller frames
2396 patch_caller_links(rs.top(), rs.top() + rs.total_size());
2397
2398 assert(is_last == _cont.is_empty(), "");
2399 assert(_cont.chunk_invariant(), "");
2400
2401 #if CONT_JFR
2402 EventContinuationThawFast e;
2403 if (e.should_commit()) {
2404 e.set_id(cast_from_oop<u8>(chunk));
2405 e.set_size(thaw_size << LogBytesPerWord);
2406 e.set_full(!partial);
2407 e.commit();
2408 }
2409 #endif
2410
2411 #ifdef ASSERT
2412 if (LoomDeoptAfterThaw) {
2413 frame top(rs.sp());
2414 AnchorMark am(_thread, top);
2415 log_frames(_thread);
2416 do_deopt_after_thaw(_thread);
2417 }
2418 #endif
2419
2420 return rs.sp();
2421 }
2422
2423 inline bool ThawBase::seen_by_gc() {
2424 return _barriers || _cont.tail()->is_gc_mode();
2425 }
2426
2427 static inline void relativize_chunk_concurrently(stackChunkOop chunk) {
2428 #if INCLUDE_ZGC || INCLUDE_SHENANDOAHGC
2429 if (UseZGC || UseShenandoahGC) {
2430 chunk->relativize_derived_pointers_concurrently();
2431 }
2432 #endif
2433 }
2434
2435 template <typename ConfigT>
2436 NOINLINE intptr_t* Thaw<ConfigT>::thaw_slow(stackChunkOop chunk, Continuation::thaw_kind kind) {
2437 Continuation::preempt_kind preempt_kind;
2438 bool retry_fast_path = false;
2439
2440 _process_args_at_top = false;
2441 _preempted_case = chunk->preempted();
2442 if (_preempted_case) {
2443 ObjectMonitor* mon = nullptr;
2444 ObjectWaiter* waiter = java_lang_VirtualThread::objectWaiter(_thread->vthread());
2445 if (waiter != nullptr) {
2446 // Mounted again after preemption. Resume the pending monitor operation,
2447 // which will be either a monitorenter or Object.wait() call.
2448 mon = waiter->monitor();
2449 preempt_kind = waiter->is_wait() ? Continuation::object_wait : Continuation::monitorenter;
2450
2451 bool mon_acquired = mon->resume_operation(_thread, waiter, _cont);
2452 assert(!mon_acquired || mon->has_owner(_thread), "invariant");
2453 if (!mon_acquired) {
2454 // Failed to acquire monitor. Return to enterSpecial to unmount again.
2455 log_develop_trace(continuations, preempt)("Failed to acquire monitor, unmounting again");
2456 return push_cleanup_continuation();
2457 }
2458 chunk = _cont.tail(); // reload oop in case of safepoint in resume_operation (if posting JVMTI events).
2459 JVMTI_ONLY(assert(_thread->contended_entered_monitor() == nullptr || _thread->contended_entered_monitor() == mon, ""));
2460 } else {
2461 // Preemption cancelled on moniterenter or ObjectLocker case. We
2462 // actually acquired the monitor after freezing all frames so no
2463 // need to call resume_operation. If this is the ObjectLocker case
2464 // we released the monitor already at ~ObjectLocker, so _init_lock
2465 // will be set to nullptr below since there is no monitor to release.
2466 preempt_kind = Continuation::monitorenter;
2467 }
2468
2469 // Call this first to avoid racing with GC threads later when modifying the chunk flags.
2470 relativize_chunk_concurrently(chunk);
2471
2472 if (chunk->at_klass_init()) {
2473 preempt_kind = Continuation::object_locker;
2474 chunk->set_at_klass_init(false);
2475 _process_args_at_top = chunk->has_args_at_top();
2476 if (_process_args_at_top) {
2477 // Only needed for the top frame which will be thawed.
2478 chunk->set_has_args_at_top(false);
2479 }
2480 assert(waiter == nullptr || mon != nullptr, "should have a monitor");
2481 _init_lock = mon; // remember monitor since we will need it on handle_preempted_continuation()
2482 }
2483 chunk->set_preempted(false);
2484 retry_fast_path = true;
2485 } else {
2486 relativize_chunk_concurrently(chunk);
2487 }
2488
2489 // On first thaw after freeze restore oops to the lockstack if any.
2490 assert(chunk->lockstack_size() == 0 || kind == Continuation::thaw_top, "");
2491 if (kind == Continuation::thaw_top && chunk->lockstack_size() > 0) {
2492 thaw_lockstack(chunk);
2493 retry_fast_path = true;
2494 }
2495
2496 // Retry the fast path now that we possibly cleared the FLAG_HAS_LOCKSTACK
2497 // and FLAG_PREEMPTED flags from the stackChunk.
2498 if (retry_fast_path && can_thaw_fast(chunk)) {
2499 intptr_t* sp = thaw_fast<true>(chunk);
2500 if (_preempted_case) {
2501 return handle_preempted_continuation(sp, preempt_kind, true /* fast_case */);
2502 }
2503 return sp;
2504 }
2505
2506 LogTarget(Trace, continuations) lt;
2507 if (lt.develop_is_enabled()) {
2508 LogStream ls(lt);
2509 ls.print_cr("thaw slow return_barrier: %d " INTPTR_FORMAT, kind, p2i(chunk));
2510 chunk->print_on(true, &ls);
2511 }
2512
2513 #if CONT_JFR
2514 EventContinuationThawSlow e;
2515 if (e.should_commit()) {
2516 e.set_id(cast_from_oop<u8>(_cont.continuation()));
2517 e.commit();
2518 }
2519 #endif
2520
2521 DEBUG_ONLY(_frames = 0;)
2522 _align_size = 0;
2523 int num_frames = kind == Continuation::thaw_top ? 2 : 1;
2524
2525 _stream = StackChunkFrameStream<ChunkFrames::Mixed>(chunk);
2526 _top_unextended_sp_before_thaw = _stream.unextended_sp();
2527
2528 frame heap_frame = _stream.to_frame();
2529 if (lt.develop_is_enabled()) {
2530 LogStream ls(lt);
2531 ls.print_cr("top hframe before (thaw):");
2532 assert(heap_frame.is_heap_frame(), "should have created a relative frame");
2533 heap_frame.print_value_on(&ls);
2534 }
2535
2536 frame caller; // the thawed caller on the stack
2537 _should_patch_caller_pc = false;
2538 recurse_thaw(heap_frame, caller, num_frames, _preempted_case);
2539 finish_thaw(caller); // caller is now the topmost thawed frame
2540 _cont.write();
2541
2542 assert(_cont.chunk_invariant(), "");
2543
2544 JVMTI_ONLY(if (!_cont.entry()->is_virtual_thread()) invalidate_jvmti_stack(_thread));
2545
2546 _thread->set_cont_fastpath(_fastpath);
2547
2548 intptr_t* sp = caller.sp();
2549
2550 if (_preempted_case) {
2551 return handle_preempted_continuation(sp, preempt_kind, false /* fast_case */);
2552 }
2553 return sp;
2554 }
2555
2556 void ThawBase::recurse_thaw(const frame& heap_frame, frame& caller, int num_frames, bool top_on_preempt_case) {
2557 log_develop_debug(continuations)("thaw num_frames: %d", num_frames);
2558 assert(!_cont.is_empty(), "no more frames");
2559 assert(num_frames > 0, "");
2560 assert(!heap_frame.is_empty(), "");
2561
2562 if (top_on_preempt_case && (heap_frame.is_native_frame() || heap_frame.is_runtime_frame())) {
2563 heap_frame.is_native_frame() ? recurse_thaw_native_frame(heap_frame, caller, 2) : recurse_thaw_stub_frame(heap_frame, caller, 2);
2564 } else if (!heap_frame.is_interpreted_frame()) {
2565 recurse_thaw_compiled_frame(heap_frame, caller, num_frames, false);
2566 } else {
2567 recurse_thaw_interpreted_frame(heap_frame, caller, num_frames, top_on_preempt_case);
2568 }
2569 }
2570
2571 template<typename FKind>
2572 bool ThawBase::recurse_thaw_java_frame(frame& caller, int num_frames) {
2573 assert(num_frames > 0, "");
2574
2575 DEBUG_ONLY(_frames++;)
2576
2577 int argsize = _stream.stack_argsize();
2578 CodeBlob* cb = _stream.cb();
2579
2580 _stream.next(SmallRegisterMap::instance_no_args());
2581 assert(_stream.to_frame().is_empty() == _stream.is_done(), "");
2582
2583 // We never leave a compiled caller of an interpreted frame as the top frame in the chunk
2584 // as it makes detecting that situation and adjusting unextended_sp tricky. We also always
2585 // thaw the caller of a frame that needs_stack_repair, as it would otherwise complicate things:
2586 // - Regardless of whether the frame was extended or not, we would need to copy the right arg
2587 // size if its greater than the one given by the normal method signature (non-scalarized).
2588 // - If the frame was indeed extended, leaving its caller as the top frame would complicate walking
2589 // the chunk (we need unextended_sp, but we only have sp).
2590 if (num_frames == 1 && !_stream.is_done() && ((FKind::interpreted && _stream.is_compiled()) || (FKind::compiled && cb->as_nmethod_or_null()->needs_stack_repair()))) {
2591 log_develop_trace(continuations)("thawing extra compiled frame to not leave a compiled interpreted-caller at top");
2592 num_frames++;
2593 }
2594
2595 if (num_frames == 1 || _stream.is_done()) { // end recursion
2596 finalize_thaw(caller, FKind::interpreted ? 0 : argsize);
2597 return true; // bottom
2598 } else { // recurse
2599 recurse_thaw(_stream.to_frame(), caller, num_frames - 1, false /* top_on_preempt_case */);
2600 return false;
2601 }
2602 }
2603
2604 void ThawBase::finalize_thaw(frame& entry, int argsize) {
2605 stackChunkOop chunk = _cont.tail();
2606
2607 if (!_stream.is_done()) {
2608 assert(_stream.sp() >= chunk->sp_address(), "");
2609 chunk->set_sp(chunk->to_offset(_stream.sp()));
2610 chunk->set_pc(_stream.pc());
2611 } else {
2612 chunk->set_sp(chunk->bottom());
2613 chunk->set_pc(nullptr);
2614 }
2615 assert(_stream.is_done() == chunk->is_empty(), "");
2616
2617 int total_thawed = pointer_delta_as_int(_stream.unextended_sp(), _top_unextended_sp_before_thaw);
2618 chunk->set_max_thawing_size(chunk->max_thawing_size() - total_thawed);
2619
2620 _cont.set_argsize(argsize);
2621 entry = new_entry_frame();
2622
2623 assert(entry.sp() == _cont.entrySP(), "");
2624 assert(Continuation::is_continuation_enterSpecial(entry), "");
2625 assert(_cont.is_entry_frame(entry), "");
2626 assert(entry.pc() == entry.raw_pc(), "");
2627 DEBUG_ONLY(_caller_raw_pc = entry.pc();)
2628 }
2629
2630 inline void ThawBase::before_thaw_java_frame(const frame& hf, const frame& caller, bool bottom, int num_frame) {
2631 LogTarget(Trace, continuations) lt;
2632 if (lt.develop_is_enabled()) {
2633 LogStream ls(lt);
2634 ls.print_cr("======== THAWING FRAME: %d", num_frame);
2635 assert(hf.is_heap_frame(), "should be");
2636 hf.print_value_on(&ls);
2637 }
2638 assert(bottom == _cont.is_entry_frame(caller), "bottom: %d is_entry_frame: %d", bottom, _cont.is_entry_frame(hf));
2639 }
2640
2641 inline void ThawBase::after_thaw_java_frame(const frame& f, bool bottom) {
2642 #ifdef ASSERT
2643 LogTarget(Trace, continuations) lt;
2644 if (lt.develop_is_enabled()) {
2645 LogStream ls(lt);
2646 ls.print_cr("thawed frame:");
2647 print_frame_layout(f, false, &ls); // f.print_on(&ls);
2648 }
2649 #endif
2650 }
2651
2652 inline void ThawBase::patch(frame& f, const frame& caller, bool bottom) {
2653 assert(!bottom || caller.fp() == _cont.entryFP(), "");
2654 if (bottom) {
2655 ContinuationHelper::Frame::patch_pc(caller, _cont.is_empty() ? caller.pc()
2656 : StubRoutines::cont_returnBarrier());
2657 } else if (_should_patch_caller_pc) {
2658 // Caller was deoptimized during thaw but we've overwritten the return address when copying f from the heap.
2659 // Also, on some platforms, if the caller is interpreted but the callee not we also need to patch.
2660
2661 #if defined(PPC64) || defined(S390)
2662 assert(caller.is_deoptimized_frame() || caller.is_interpreted_frame(), "");
2663 #else
2664 assert(caller.is_deoptimized_frame(), "");
2665 #endif
2666
2667 ContinuationHelper::Frame::patch_pc(caller, caller.raw_pc());
2668 _should_patch_caller_pc = false;
2669 }
2670
2671 patch_pd(f, caller);
2672
2673 if (f.is_interpreted_frame()) {
2674 ContinuationHelper::InterpretedFrame::patch_sender_sp(f, caller);
2675 }
2676
2677 assert(!bottom || !_cont.is_empty() || Continuation::is_continuation_entry_frame(f, nullptr), "");
2678 assert(!bottom || (_cont.is_empty() != Continuation::is_cont_barrier_frame(f)), "");
2679 assert(!caller.is_compiled_frame() || verify_deopt_state(caller), "");
2680 }
2681
2682 void ThawBase::clear_bitmap_bits(address start, address end) {
2683 assert(is_aligned(start, wordSize), "should be aligned: " PTR_FORMAT, p2i(start));
2684 assert(is_aligned(end, VMRegImpl::stack_slot_size), "should be aligned: " PTR_FORMAT, p2i(end));
2685
2686 // we need to clear the bits that correspond to arguments as they reside in the caller frame
2687 // or they will keep objects that are otherwise unreachable alive.
2688
2689 // Align `end` if UseCompressedOops is not set to avoid UB when calculating the bit index, since
2690 // `end` could be at an odd number of stack slots from `start`, i.e might not be oop aligned.
2691 // If that's the case the bit range corresponding to the last stack slot should not have bits set
2692 // anyways and we assert that before returning.
2693 address effective_end = UseCompressedOops ? end : align_down(end, wordSize);
2694 log_develop_trace(continuations)("clearing bitmap for " INTPTR_FORMAT " - " INTPTR_FORMAT, p2i(start), p2i(effective_end));
2695 stackChunkOop chunk = _cont.tail();
2696 chunk->bitmap().clear_range(chunk->bit_index_for(start), chunk->bit_index_for(effective_end));
2697 assert(effective_end == end || !chunk->bitmap().at(chunk->bit_index_for(effective_end)), "bit should not be set");
2698 }
2699
2700 intptr_t* ThawBase::handle_preempted_continuation(intptr_t* sp, Continuation::preempt_kind preempt_kind, bool fast_case) {
2701 frame top(sp);
2702 assert(top.pc() == ContinuationHelper::return_address_at(sp - frame::sender_sp_ret_address_offset()), "");
2703 DEBUG_ONLY(verify_frame_kind(top, preempt_kind);)
2704 NOT_PRODUCT(int64_t tid = _thread->monitor_owner_id();)
2705
2706 // Finish the VTMS transition.
2707 assert(_thread->is_in_vthread_transition(), "must be");
2708 bool is_vthread = Continuation::continuation_scope(_cont.continuation()) == java_lang_VirtualThread::vthread_scope();
2709 if (is_vthread) {
2710 #if INCLUDE_JVMTI
2711 if (MountUnmountDisabler::notify_jvmti_events()) {
2712 jvmti_mount_end(_thread, _cont, top, preempt_kind);
2713 } else
2714 #endif
2715 { // Faster version of MountUnmountDisabler::end_transition() to avoid
2716 // unnecessary extra instructions from jvmti_mount_end().
2717 java_lang_Thread::set_is_in_vthread_transition(_thread->vthread(), false);
2718 _thread->set_is_in_vthread_transition(false);
2719 }
2720 }
2721
2722 if (fast_case) {
2723 // If we thawed in the slow path the runtime stub/native wrapper frame already
2724 // has the correct fp (see ThawBase::new_stack_frame). On the fast path though,
2725 // we copied the fp patched during freeze, which will now have to be fixed.
2726 assert(top.is_runtime_frame() || top.is_native_frame(), "");
2727 int fsize = top.cb()->frame_size();
2728 patch_pd(top, sp + fsize);
2729 }
2730
2731 if (preempt_kind == Continuation::object_wait) {
2732 // Check now if we need to throw IE exception.
2733 bool throw_ie = _thread->pending_interrupted_exception();
2734 if (throw_ie) {
2735 throw_interrupted_exception(_thread, top);
2736 _thread->set_pending_interrupted_exception(false);
2737 }
2738 log_develop_trace(continuations, preempt)("Resuming " INT64_FORMAT" after preemption on Object.wait%s", tid, throw_ie ? "(throwing IE)" : "");
2739 } else if (preempt_kind == Continuation::monitorenter) {
2740 if (top.is_runtime_frame()) {
2741 // The continuation might now run on a different platform thread than the previous time so
2742 // we need to adjust the current thread saved in the stub frame before restoring registers.
2743 JavaThread** thread_addr = frame::saved_thread_address(top);
2744 if (thread_addr != nullptr) *thread_addr = _thread;
2745 }
2746 log_develop_trace(continuations, preempt)("Resuming " INT64_FORMAT " after preemption on monitorenter", tid);
2747 } else {
2748 // We need to redo the original call into the VM. First though, we need
2749 // to exit the monitor we just acquired (except on preemption cancelled
2750 // case where it was already released).
2751 assert(preempt_kind == Continuation::object_locker, "");
2752 if (_init_lock != nullptr) _init_lock->exit(_thread);
2753 sp = redo_vmcall(_thread, top);
2754 }
2755 return sp;
2756 }
2757
2758 intptr_t* ThawBase::redo_vmcall(JavaThread* current, frame& top) {
2759 assert(!current->preempting(), "");
2760 NOT_PRODUCT(int64_t tid = current->monitor_owner_id();)
2761 intptr_t* sp = top.sp();
2762
2763 {
2764 HandleMarkCleaner hmc(current); // Cleanup all handles (including so._conth) before returning to Java.
2765 ContinuationWrapper::SafepointOp so(current, _cont);
2766 AnchorMark am(current, top); // Set the anchor so that the stack is walkable.
2767
2768 Method* m = top.interpreter_frame_method();
2769 Bytecode current_bytecode = Bytecode(m, top.interpreter_frame_bcp());
2770 Bytecodes::Code code = current_bytecode.code();
2771 log_develop_trace(continuations, preempt)("Redoing InterpreterRuntime::%s for " INT64_FORMAT, code == Bytecodes::Code::_new ? "_new" : "resolve_from_cache", tid);
2772
2773 // These InterpreterRuntime entry points use JRT_ENTRY which uses a HandleMarkCleaner.
2774 // Create a HandeMark to avoid destroying so._conth.
2775 HandleMark hm(current);
2776 DEBUG_ONLY(JavaThread::AtRedoVMCall apvmc(current);)
2777 if (code == Bytecodes::Code::_new) {
2778 InterpreterRuntime::_new(current, m->constants(), current_bytecode.get_index_u2(code));
2779 } else {
2780 InterpreterRuntime::resolve_from_cache(current, code);
2781 }
2782 }
2783
2784 if (current->preempting()) {
2785 // Preempted again so we just arrange to return to preempt stub to unmount.
2786 sp = push_preempt_adapter();
2787 current->set_preempt_alternate_return(nullptr);
2788 bool cancelled = current->preemption_cancelled();
2789 if (cancelled) {
2790 // Since preemption was cancelled, the thread will call thaw again from the preempt
2791 // stub. These retries could happen several times due to contention on the init_lock,
2792 // so just let the vthread umount to give a chance for other vthreads to run.
2793 current->set_preemption_cancelled(false);
2794 oop vthread = current->vthread();
2795 assert(java_lang_VirtualThread::state(vthread) == java_lang_VirtualThread::RUNNING, "wrong state for vthread");
2796 java_lang_VirtualThread::set_state(vthread, java_lang_VirtualThread::YIELDING);
2797 #if INCLUDE_JVMTI
2798 if (current->contended_entered_monitor() != nullptr) {
2799 current->set_contended_entered_monitor(nullptr);
2800 }
2801 #endif
2802 }
2803 log_develop_trace(continuations, preempt)("Preempted " INT64_FORMAT " again%s", tid, cancelled ? "(preemption cancelled, setting state to YIELDING)" : "");
2804 } else {
2805 log_develop_trace(continuations, preempt)("Call succesful, resuming " INT64_FORMAT, tid);
2806 }
2807 return sp;
2808 }
2809
2810 void ThawBase::throw_interrupted_exception(JavaThread* current, frame& top) {
2811 HandleMarkCleaner hm(current); // Cleanup all handles (including so._conth) before returning to Java.
2812 ContinuationWrapper::SafepointOp so(current, _cont);
2813 AnchorMark am(current, top); // Set the anchor so that the stack is walkable.
2814 JRT_BLOCK
2815 THROW(vmSymbols::java_lang_InterruptedException());
2816 JRT_BLOCK_END
2817 }
2818
2819 NOINLINE void ThawBase::recurse_thaw_interpreted_frame(const frame& hf, frame& caller, int num_frames, bool is_top) {
2820 assert(hf.is_interpreted_frame(), "");
2821
2822 if (UNLIKELY(seen_by_gc())) {
2823 if (is_top && _process_args_at_top) {
2824 _cont.tail()->do_barriers<stackChunkOopDesc::BarrierType::Store>(_stream, SmallRegisterMap::instance_with_args());
2825 } else {
2826 _cont.tail()->do_barriers<stackChunkOopDesc::BarrierType::Store>(_stream, SmallRegisterMap::instance_no_args());
2827 }
2828 }
2829
2830 const bool is_bottom_frame = recurse_thaw_java_frame<ContinuationHelper::InterpretedFrame>(caller, num_frames);
2831
2832 DEBUG_ONLY(before_thaw_java_frame(hf, caller, is_bottom_frame, num_frames);)
2833
2834 _align_size += frame::align_wiggle; // possible added alignment for internal interpreted frame alignment om AArch64
2835
2836 frame f = new_stack_frame<ContinuationHelper::InterpretedFrame>(hf, caller, is_bottom_frame);
2837
2838 intptr_t* const stack_frame_top = f.sp() + frame::metadata_words_at_top;
2839 intptr_t* const stack_frame_bottom = ContinuationHelper::InterpretedFrame::frame_bottom(f);
2840 intptr_t* const heap_frame_top = hf.unextended_sp() + frame::metadata_words_at_top;
2841 intptr_t* const heap_frame_bottom = ContinuationHelper::InterpretedFrame::frame_bottom(hf);
2842
2843 assert(hf.is_heap_frame(), "should be");
2844 assert(!f.is_heap_frame(), "should not be");
2845
2846 const int fsize = pointer_delta_as_int(heap_frame_bottom, heap_frame_top);
2847 assert((stack_frame_bottom == stack_frame_top + fsize), "");
2848
2849 // Some architectures (like AArch64/PPC64/RISC-V) add padding between the locals and the fixed_frame to keep the fp 16-byte-aligned.
2850 // On those architectures we freeze the padding in order to keep the same fp-relative offsets in the fixed_frame.
2851 copy_from_chunk(heap_frame_top, stack_frame_top, fsize);
2852
2853 // Make sure the relativized locals is already set.
2854 assert(f.interpreter_frame_local_at(0) == stack_frame_bottom - 1, "invalid frame bottom");
2855
2856 derelativize_interpreted_frame_metadata(hf, f);
2857 patch(f, caller, is_bottom_frame);
2858
2859 assert(f.is_interpreted_frame_valid(_cont.thread()), "invalid thawed frame");
2860 assert(stack_frame_bottom <= ContinuationHelper::Frame::frame_top(caller), "");
2861
2862 CONT_JFR_ONLY(_jfr_info.record_interpreted_frame();)
2863
2864 maybe_set_fastpath(f.sp());
2865
2866 Method* m = hf.interpreter_frame_method();
2867 assert(!m->is_native() || !is_bottom_frame, "should be top frame of thaw_top case; missing caller frame");
2868 const int locals = m->max_locals();
2869
2870 if (!is_bottom_frame) {
2871 // can only fix caller once this frame is thawed (due to callee saved regs)
2872 _cont.tail()->fix_thawed_frame(caller, SmallRegisterMap::instance_no_args());
2873 } else if (_cont.tail()->has_bitmap() && locals > 0) {
2874 assert(hf.is_heap_frame(), "should be");
2875 address start = (address)(heap_frame_bottom - locals);
2876 address end = (address)heap_frame_bottom;
2877 clear_bitmap_bits(start, end);
2878 }
2879
2880 DEBUG_ONLY(after_thaw_java_frame(f, is_bottom_frame);)
2881 DEBUG_ONLY(address return_pc = ContinuationHelper::InterpretedFrame::return_pc(f);)
2882 assert(return_pc == _caller_raw_pc || (is_bottom_frame && return_pc == StubRoutines::cont_returnBarrier()), "wrong return pc");
2883 assert(f.pc() == f.raw_pc(), "");
2884 DEBUG_ONLY(_caller_raw_pc = f.pc();)
2885 caller = f;
2886 }
2887
2888 void ThawBase::recurse_thaw_compiled_frame(const frame& hf, frame& caller, int num_frames, bool stub_caller) {
2889 assert(hf.is_compiled_frame(), "");
2890 assert(_preempted_case || !stub_caller, "stub caller not at preemption");
2891
2892 if (!stub_caller && UNLIKELY(seen_by_gc())) { // recurse_thaw_stub_frame already invoked our barriers with a full regmap
2893 _cont.tail()->do_barriers<stackChunkOopDesc::BarrierType::Store>(_stream, SmallRegisterMap::instance_no_args());
2894 }
2895
2896 const bool is_bottom_frame = recurse_thaw_java_frame<ContinuationHelper::CompiledFrame>(caller, num_frames);
2897
2898 DEBUG_ONLY(before_thaw_java_frame(hf, caller, is_bottom_frame, num_frames);)
2899
2900 assert(caller.sp() == caller.unextended_sp(), "");
2901
2902 if ((!is_bottom_frame && caller.is_interpreted_frame()) || (is_bottom_frame && Interpreter::contains(_cont.tail()->pc()))) {
2903 _align_size += frame::align_wiggle; // we add one whether or not we've aligned because we add it in recurse_freeze_compiled_frame
2904 }
2905
2906 int fsize = 0;
2907 int added_argsize = 0;
2908 bool augmented = hf.was_augmented_on_entry(fsize);
2909 if (!augmented) {
2910 added_argsize = (is_bottom_frame || caller.is_interpreted_frame()) ? hf.compiled_frame_stack_argsize() : 0;
2911 fsize += added_argsize;
2912 }
2913 assert(!is_bottom_frame || !augmented, "");
2914
2915 // new_stack_frame must construct the resulting frame using hf.pc() rather than hf.raw_pc() because the frame is not
2916 // yet laid out in the stack, and so the original_pc is not stored in it.
2917 // As a result, f.is_deoptimized_frame() is always false and we must test hf to know if the frame is deoptimized.
2918 frame f = new_stack_frame<ContinuationHelper::CompiledFrame>(hf, caller, is_bottom_frame, augmented ? fsize - hf.cb()->frame_size() : 0);
2919 assert((int)(caller.sp() - f.sp()) == (augmented ? fsize : f.cb()->frame_size()), "");
2920
2921 intptr_t* const stack_frame_top = f.sp();
2922 intptr_t* const heap_frame_top = hf.unextended_sp();
2923 intptr_t* from = heap_frame_top - frame::metadata_words_at_bottom;
2924 intptr_t* to = stack_frame_top - frame::metadata_words_at_bottom;
2925 // copy metadata, except the metadata at the top of the (unextended) entry frame
2926 int sz = fsize + frame::metadata_words_at_bottom + (is_bottom_frame && added_argsize == 0 ? 0 : frame::metadata_words_at_top);
2927
2928 // If we're the bottom-most thawed frame, we're writing to within one word from entrySP
2929 // (we might have one padding word for alignment)
2930 assert(!is_bottom_frame || (_cont.entrySP() - 1 <= to + sz && to + sz <= _cont.entrySP()), "");
2931 assert(!is_bottom_frame || hf.compiled_frame_stack_argsize() != 0 || (to + sz && to + sz == _cont.entrySP()), "");
2932
2933 copy_from_chunk(from, to, sz); // copying good oops because we invoked barriers above
2934
2935 patch(f, caller, is_bottom_frame);
2936
2937 // f.is_deoptimized_frame() is always false and we must test hf.is_deoptimized_frame() (see comment above)
2938 assert(!f.is_deoptimized_frame(), "");
2939 if (hf.is_deoptimized_frame()) {
2940 maybe_set_fastpath(f.sp());
2941 f.set_deoptimized();
2942 } else if (_thread->is_interp_only_mode()
2943 || (stub_caller && f.cb()->as_nmethod()->is_marked_for_deoptimization())) {
2944 // The caller of the safepoint stub when the continuation is preempted is not at a call instruction, and so
2945 // cannot rely on nmethod patching for deopt.
2946 assert(_thread->is_interp_only_mode() || stub_caller, "expected a stub-caller");
2947
2948 log_develop_trace(continuations)("Deoptimizing thawed frame");
2949 DEBUG_ONLY(ContinuationHelper::Frame::patch_pc(f, nullptr));
2950
2951 f.deoptimize(nullptr); // the null thread simply avoids the assertion in deoptimize which we're not set up for
2952 assert(f.is_deoptimized_frame(), "");
2953 assert(ContinuationHelper::Frame::is_deopt_return(f.raw_pc(), f), "");
2954 maybe_set_fastpath(f.sp());
2955 assert(!_should_patch_caller_pc, "");
2956 _should_patch_caller_pc = true;
2957 }
2958
2959 if (!is_bottom_frame) {
2960 // can only fix caller once this frame is thawed (due to callee saved regs); this happens on the stack
2961 _cont.tail()->fix_thawed_frame(caller, SmallRegisterMap::instance_no_args());
2962 } else if (_cont.tail()->has_bitmap() && added_argsize > 0) {
2963 address start = (address)(heap_frame_top + ContinuationHelper::CompiledFrame::size(hf) + frame::metadata_words_at_top);
2964 int stack_args_slots = f.cb()->as_nmethod()->num_stack_arg_slots(false /* rounded */);
2965 int argsize_in_bytes = stack_args_slots * VMRegImpl::stack_slot_size;
2966 clear_bitmap_bits(start, start + argsize_in_bytes);
2967 }
2968
2969 DEBUG_ONLY(after_thaw_java_frame(f, is_bottom_frame);)
2970 DEBUG_ONLY(address return_pc = ContinuationHelper::CompiledFrame::return_pc(f);)
2971 assert(return_pc == _caller_raw_pc || (is_bottom_frame && return_pc == StubRoutines::cont_returnBarrier()), "wrong return pc");
2972 DEBUG_ONLY(_caller_raw_pc = f.raw_pc();)
2973 caller = f;
2974 }
2975
2976 void ThawBase::recurse_thaw_stub_frame(const frame& hf, frame& caller, int num_frames) {
2977 DEBUG_ONLY(_frames++;)
2978
2979 if (UNLIKELY(seen_by_gc())) {
2980 // Process the stub's caller here since we might need the full map.
2981 RegisterMap map(nullptr,
2982 RegisterMap::UpdateMap::include,
2983 RegisterMap::ProcessFrames::skip,
2984 RegisterMap::WalkContinuation::skip);
2985 map.set_include_argument_oops(false);
2986 _stream.next(&map);
2987 assert(!_stream.is_done(), "");
2988 _cont.tail()->do_barriers<stackChunkOopDesc::BarrierType::Store>(_stream, &map);
2989 } else {
2990 _stream.next(SmallRegisterMap::instance_no_args());
2991 assert(!_stream.is_done(), "");
2992 }
2993
2994 recurse_thaw_compiled_frame(_stream.to_frame(), caller, num_frames, true);
2995
2996 assert(caller.is_compiled_frame(), "");
2997 assert(caller.sp() == caller.unextended_sp(), "");
2998
2999 DEBUG_ONLY(before_thaw_java_frame(hf, caller, false /*is_bottom_frame*/, num_frames);)
3000
3001 frame f = new_stack_frame<ContinuationHelper::StubFrame>(hf, caller, false);
3002 intptr_t* stack_frame_top = f.sp();
3003 intptr_t* heap_frame_top = hf.sp();
3004 int fsize = ContinuationHelper::StubFrame::size(hf);
3005
3006 copy_from_chunk(heap_frame_top - frame::metadata_words, stack_frame_top - frame::metadata_words,
3007 fsize + frame::metadata_words);
3008
3009 patch(f, caller, false /*is_bottom_frame*/);
3010
3011 // can only fix caller once this frame is thawed (due to callee saved regs)
3012 RegisterMap map(nullptr,
3013 RegisterMap::UpdateMap::include,
3014 RegisterMap::ProcessFrames::skip,
3015 RegisterMap::WalkContinuation::skip);
3016 map.set_include_argument_oops(false);
3017 f.oop_map()->update_register_map(&f, &map);
3018 ContinuationHelper::update_register_map_with_callee(caller, &map);
3019 _cont.tail()->fix_thawed_frame(caller, &map);
3020
3021 DEBUG_ONLY(after_thaw_java_frame(f, false /*is_bottom_frame*/);)
3022 assert(ContinuationHelper::StubFrame::return_pc(f) == _caller_raw_pc, "wrong return pc");
3023 caller = f;
3024 }
3025
3026 void ThawBase::recurse_thaw_native_frame(const frame& hf, frame& caller, int num_frames) {
3027 assert(hf.is_native_frame(), "");
3028 assert(_preempted_case && hf.cb()->as_nmethod()->method()->is_object_wait0(), "");
3029
3030 if (UNLIKELY(seen_by_gc())) { // recurse_thaw_stub_frame already invoked our barriers with a full regmap
3031 _cont.tail()->do_barriers<stackChunkOopDesc::BarrierType::Store>(_stream, SmallRegisterMap::instance_no_args());
3032 }
3033
3034 const bool is_bottom_frame = recurse_thaw_java_frame<ContinuationHelper::NativeFrame>(caller, num_frames);
3035 assert(!is_bottom_frame, "");
3036
3037 DEBUG_ONLY(before_thaw_java_frame(hf, caller, is_bottom_frame, num_frames);)
3038
3039 assert(caller.sp() == caller.unextended_sp(), "");
3040
3041 if (caller.is_interpreted_frame()) {
3042 _align_size += frame::align_wiggle; // we add one whether or not we've aligned because we add it in recurse_freeze_native_frame
3043 }
3044
3045 // new_stack_frame must construct the resulting frame using hf.pc() rather than hf.raw_pc() because the frame is not
3046 // yet laid out in the stack, and so the original_pc is not stored in it.
3047 // As a result, f.is_deoptimized_frame() is always false and we must test hf to know if the frame is deoptimized.
3048 frame f = new_stack_frame<ContinuationHelper::NativeFrame>(hf, caller, false /* bottom */);
3049 intptr_t* const stack_frame_top = f.sp();
3050 intptr_t* const heap_frame_top = hf.unextended_sp();
3051
3052 int fsize = ContinuationHelper::NativeFrame::size(hf);
3053 assert(fsize <= (int)(caller.unextended_sp() - f.unextended_sp()), "");
3054
3055 intptr_t* from = heap_frame_top - frame::metadata_words_at_bottom;
3056 intptr_t* to = stack_frame_top - frame::metadata_words_at_bottom;
3057 int sz = fsize + frame::metadata_words_at_bottom;
3058
3059 copy_from_chunk(from, to, sz); // copying good oops because we invoked barriers above
3060
3061 patch(f, caller, false /* bottom */);
3062
3063 // f.is_deoptimized_frame() is always false and we must test hf.is_deoptimized_frame() (see comment above)
3064 assert(!f.is_deoptimized_frame(), "");
3065 assert(!hf.is_deoptimized_frame(), "");
3066 assert(!f.cb()->as_nmethod()->is_marked_for_deoptimization(), "");
3067
3068 // can only fix caller once this frame is thawed (due to callee saved regs); this happens on the stack
3069 _cont.tail()->fix_thawed_frame(caller, SmallRegisterMap::instance_no_args());
3070
3071 DEBUG_ONLY(after_thaw_java_frame(f, false /* bottom */);)
3072 assert(ContinuationHelper::NativeFrame::return_pc(f) == _caller_raw_pc, "wrong return pc");
3073 caller = f;
3074 }
3075
3076 void ThawBase::finish_thaw(frame& f) {
3077 stackChunkOop chunk = _cont.tail();
3078
3079 if (chunk->is_empty()) {
3080 // Only remove chunk from list if it can't be reused for another freeze
3081 if (seen_by_gc()) {
3082 _cont.set_tail(chunk->parent());
3083 } else {
3084 chunk->set_has_mixed_frames(false);
3085 }
3086 chunk->set_max_thawing_size(0);
3087 } else {
3088 chunk->set_max_thawing_size(chunk->max_thawing_size() - _align_size);
3089 }
3090 assert(chunk->is_empty() == (chunk->max_thawing_size() == 0), "");
3091
3092 if (!is_aligned(f.sp(), frame::frame_alignment)) {
3093 assert(f.is_interpreted_frame(), "");
3094 f.set_sp(align_down(f.sp(), frame::frame_alignment));
3095 }
3096 push_return_frame(f);
3097 // can only fix caller after push_return_frame (due to callee saved regs)
3098 if (_process_args_at_top) {
3099 chunk->fix_thawed_frame(f, SmallRegisterMap::instance_with_args());
3100 } else {
3101 chunk->fix_thawed_frame(f, SmallRegisterMap::instance_no_args());
3102 }
3103
3104 assert(_cont.is_empty() == _cont.last_frame().is_empty(), "");
3105
3106 log_develop_trace(continuations)("thawed %d frames", _frames);
3107
3108 LogTarget(Trace, continuations) lt;
3109 if (lt.develop_is_enabled()) {
3110 LogStream ls(lt);
3111 ls.print_cr("top hframe after (thaw):");
3112 _cont.last_frame().print_value_on(&ls);
3113 }
3114 }
3115
3116 void ThawBase::push_return_frame(const frame& f) { // see generate_cont_thaw
3117 assert(!f.is_compiled_frame() || verify_deopt_state(f), "");
3118
3119 LogTarget(Trace, continuations) lt;
3120 if (lt.develop_is_enabled()) {
3121 LogStream ls(lt);
3122 ls.print_cr("push_return_frame");
3123 f.print_value_on(&ls);
3124 }
3125
3126 assert(f.sp() - frame::metadata_words_at_bottom >= _top_stack_address, "overwrote past thawing space"
3127 " to: " INTPTR_FORMAT " top_address: " INTPTR_FORMAT, p2i(f.sp() - frame::metadata_words), p2i(_top_stack_address));
3128 ContinuationHelper::Frame::patch_pc(f, f.raw_pc()); // in case we want to deopt the frame in a full transition, this is checked.
3129 ContinuationHelper::push_pd(f);
3130
3131 assert(ContinuationHelper::Frame::assert_frame_laid_out(f), "");
3132 }
3133
3134 // returns new top sp
3135 // called after preparations (stack overflow check and making room)
3136 template<typename ConfigT>
3137 static inline intptr_t* thaw_internal(JavaThread* thread, const Continuation::thaw_kind kind) {
3138 assert(thread == JavaThread::current(), "Must be current thread");
3139
3140 CONT_JFR_ONLY(EventContinuationThaw event;)
3141
3142 log_develop_trace(continuations)("~~~~ thaw kind: %d sp: " INTPTR_FORMAT, kind, p2i(thread->last_continuation()->entry_sp()));
3143
3144 ContinuationEntry* entry = thread->last_continuation();
3145 assert(entry != nullptr, "");
3146 oop oopCont = entry->cont_oop(thread);
3147
3148 assert(!jdk_internal_vm_Continuation::done(oopCont), "");
3149 assert(oopCont == get_continuation(thread), "");
3150 verify_continuation(oopCont);
3151
3152 assert(entry->is_virtual_thread() == (entry->scope(thread) == java_lang_VirtualThread::vthread_scope()), "");
3153
3154 ContinuationWrapper cont(thread, oopCont);
3155 log_develop_debug(continuations)("THAW #" INTPTR_FORMAT " " INTPTR_FORMAT, cont.hash(), p2i((oopDesc*)oopCont));
3156
3157 #ifdef ASSERT
3158 set_anchor_to_entry(thread, cont.entry());
3159 log_frames(thread);
3160 clear_anchor(thread);
3161 #endif
3162
3163 Thaw<ConfigT> thw(thread, cont);
3164 intptr_t* const sp = thw.thaw(kind);
3165 assert(is_aligned(sp, frame::frame_alignment), "");
3166 DEBUG_ONLY(log_frames_after_thaw(thread, cont, sp);)
3167
3168 CONT_JFR_ONLY(thw.jfr_info().post_jfr_event(&event, cont.continuation(), thread);)
3169
3170 verify_continuation(cont.continuation());
3171 log_develop_debug(continuations)("=== End of thaw #" INTPTR_FORMAT, cont.hash());
3172
3173 return sp;
3174 }
3175
3176 #ifdef ASSERT
3177 static void do_deopt_after_thaw(JavaThread* thread) {
3178 int i = 0;
3179 StackFrameStream fst(thread, true, false);
3180 fst.register_map()->set_include_argument_oops(false);
3181 ContinuationHelper::update_register_map_with_callee(*fst.current(), fst.register_map());
3182 for (; !fst.is_done(); fst.next()) {
3183 if (fst.current()->cb()->is_nmethod()) {
3184 nmethod* nm = fst.current()->cb()->as_nmethod();
3185 if (!nm->method()->is_continuation_native_intrinsic()) {
3186 nm->make_deoptimized();
3187 }
3188 }
3189 }
3190 }
3191
3192 class ThawVerifyOopsClosure: public OopClosure {
3193 intptr_t* _p;
3194 outputStream* _st;
3195 bool is_good_oop(oop o) {
3196 return dbg_is_safe(o, -1) && dbg_is_safe(o->klass(), -1) && oopDesc::is_oop(o) && o->klass()->is_klass();
3197 }
3198 public:
3199 ThawVerifyOopsClosure(outputStream* st) : _p(nullptr), _st(st) {}
3200 intptr_t* p() { return _p; }
3201 void reset() { _p = nullptr; }
3202
3203 virtual void do_oop(oop* p) {
3204 oop o = *p;
3205 if (o == nullptr || is_good_oop(o)) {
3206 return;
3207 }
3208 _p = (intptr_t*)p;
3209 _st->print_cr("*** non-oop " PTR_FORMAT " found at " PTR_FORMAT, p2i(*p), p2i(p));
3210 }
3211 virtual void do_oop(narrowOop* p) {
3212 oop o = RawAccess<>::oop_load(p);
3213 if (o == nullptr || is_good_oop(o)) {
3214 return;
3215 }
3216 _p = (intptr_t*)p;
3217 _st->print_cr("*** (narrow) non-oop %x found at " PTR_FORMAT, (int)(*p), p2i(p));
3218 }
3219 };
3220
3221 static bool do_verify_after_thaw(JavaThread* thread, stackChunkOop chunk, outputStream* st) {
3222 assert(thread->has_last_Java_frame(), "");
3223
3224 ResourceMark rm;
3225 ThawVerifyOopsClosure cl(st);
3226 NMethodToOopClosure cf(&cl, false);
3227
3228 StackFrameStream fst(thread, true, false);
3229 fst.register_map()->set_include_argument_oops(false);
3230 ContinuationHelper::update_register_map_with_callee(*fst.current(), fst.register_map());
3231 for (; !fst.is_done() && !Continuation::is_continuation_enterSpecial(*fst.current()); fst.next()) {
3232 if (fst.current()->cb()->is_nmethod() && fst.current()->cb()->as_nmethod()->is_marked_for_deoptimization()) {
3233 st->print_cr(">>> do_verify_after_thaw deopt");
3234 fst.current()->deoptimize(nullptr);
3235 fst.current()->print_on(st);
3236 }
3237
3238 fst.current()->oops_do(&cl, &cf, fst.register_map());
3239 if (cl.p() != nullptr) {
3240 frame fr = *fst.current();
3241 st->print_cr("Failed for frame barriers: %d",chunk->requires_barriers());
3242 fr.print_on(st);
3243 if (!fr.is_interpreted_frame()) {
3244 st->print_cr("size: %d argsize: %d",
3245 ContinuationHelper::NonInterpretedUnknownFrame::size(fr),
3246 ContinuationHelper::NonInterpretedUnknownFrame::stack_argsize(fr));
3247 }
3248 VMReg reg = fst.register_map()->find_register_spilled_here(cl.p(), fst.current()->sp());
3249 if (reg != nullptr) {
3250 st->print_cr("Reg %s %d", reg->name(), reg->is_stack() ? (int)reg->reg2stack() : -99);
3251 }
3252 cl.reset();
3253 DEBUG_ONLY(thread->print_frame_layout();)
3254 if (chunk != nullptr) {
3255 chunk->print_on(true, st);
3256 }
3257 return false;
3258 }
3259 }
3260 return true;
3261 }
3262
3263 static bool verify_deopt_state(const frame& f) {
3264 nmethod* nm = f.cb()->as_nmethod();
3265 assert(f.is_deoptimized_frame() == nm->is_deopt_pc(f.raw_pc()), "");
3266 assert(f.is_deoptimized_frame() == (f.pc() != f.raw_pc()), "");
3267 assert(f.is_deoptimized_frame() == nm->is_deopt_pc(ContinuationHelper::Frame::real_pc(f)), "");
3268 return true;
3269 }
3270
3271 static void log_frames(JavaThread* thread) {
3272 const static int show_entry_callers = 3;
3273 LogTarget(Trace, continuations) lt;
3274 if (!lt.develop_is_enabled()) {
3275 return;
3276 }
3277 LogStream ls(lt);
3278
3279 ls.print_cr("------- frames --------- for thread " INTPTR_FORMAT, p2i(thread));
3280 if (!thread->has_last_Java_frame()) {
3281 ls.print_cr("NO ANCHOR!");
3282 }
3283
3284 RegisterMap map(thread,
3285 RegisterMap::UpdateMap::include,
3286 RegisterMap::ProcessFrames::include,
3287 RegisterMap::WalkContinuation::skip);
3288 map.set_include_argument_oops(false);
3289
3290 if (false) {
3291 for (frame f = thread->last_frame(); !f.is_entry_frame(); f = f.sender(&map)) {
3292 f.print_on(&ls);
3293 }
3294 } else {
3295 map.set_skip_missing(true);
3296 ResetNoHandleMark rnhm;
3297 ResourceMark rm;
3298 HandleMark hm(Thread::current());
3299 FrameValues values;
3300
3301 int i = 0;
3302 int post_entry = -1;
3303 for (frame f = thread->last_frame(); !f.is_first_frame(); f = f.sender(&map), i++) {
3304 f.describe(values, i, &map, i == 0);
3305 if (post_entry >= 0 || Continuation::is_continuation_enterSpecial(f))
3306 post_entry++;
3307 if (post_entry >= show_entry_callers)
3308 break;
3309 }
3310 values.print_on(thread, &ls);
3311 }
3312
3313 ls.print_cr("======= end frames =========");
3314 }
3315
3316 static void log_frames_after_thaw(JavaThread* thread, ContinuationWrapper& cont, intptr_t* sp) {
3317 intptr_t* sp0 = sp;
3318 bool preempted = false;
3319 stackChunkOop tail = cont.tail();
3320 if (tail != nullptr && tail->preempted()) {
3321 // Still preempted (monitor not acquired) so no frames were thawed.
3322 set_anchor(thread, cont.entrySP(), cont.entryPC());
3323 preempted = true;
3324 } else {
3325 set_anchor(thread, sp0);
3326 }
3327
3328 log_frames(thread);
3329 if (LoomVerifyAfterThaw) {
3330 assert(do_verify_after_thaw(thread, cont.tail(), tty), "");
3331 }
3332 assert(preempted || ContinuationEntry::assert_entry_frame_laid_out(thread), "");
3333 clear_anchor(thread);
3334
3335 LogTarget(Trace, continuations) lt;
3336 if (lt.develop_is_enabled()) {
3337 LogStream ls(lt);
3338 ls.print_cr("Jumping to frame (thaw):");
3339 frame(sp).print_value_on(&ls);
3340 }
3341 }
3342 #endif // ASSERT
3343
3344 #include CPU_HEADER_INLINE(continuationFreezeThaw)
3345
3346 #ifdef ASSERT
3347 static void print_frame_layout(const frame& f, bool callee_complete, outputStream* st) {
3348 ResourceMark rm;
3349 FrameValues values;
3350 assert(f.get_cb() != nullptr, "");
3351 RegisterMap map(f.is_heap_frame() ?
3352 nullptr :
3353 JavaThread::current(),
3354 RegisterMap::UpdateMap::include,
3355 RegisterMap::ProcessFrames::skip,
3356 RegisterMap::WalkContinuation::skip);
3357 map.set_include_argument_oops(false);
3358 map.set_skip_missing(true);
3359 if (callee_complete) {
3360 frame::update_map_with_saved_link(&map, ContinuationHelper::Frame::callee_link_address(f));
3361 }
3362 const_cast<frame&>(f).describe(values, 0, &map, true);
3363 values.print_on(static_cast<JavaThread*>(nullptr), st);
3364 }
3365 #endif
3366
3367 static address thaw_entry = nullptr;
3368 static address freeze_entry = nullptr;
3369 static address freeze_preempt_entry = nullptr;
3370
3371 address Continuation::thaw_entry() {
3372 return ::thaw_entry;
3373 }
3374
3375 address Continuation::freeze_entry() {
3376 return ::freeze_entry;
3377 }
3378
3379 address Continuation::freeze_preempt_entry() {
3380 return ::freeze_preempt_entry;
3381 }
3382
3383 class ConfigResolve {
3384 public:
3385 static void resolve() { resolve_compressed(); }
3386
3387 static void resolve_compressed() {
3388 UseCompressedOops ? resolve_gc<true>()
3389 : resolve_gc<false>();
3390 }
3391
3392 private:
3393 template <bool use_compressed>
3394 static void resolve_gc() {
3395 BarrierSet* bs = BarrierSet::barrier_set();
3396 assert(bs != nullptr, "freeze/thaw invoked before BarrierSet is set");
3397 switch (bs->kind()) {
3398 #define BARRIER_SET_RESOLVE_BARRIER_CLOSURE(bs_name) \
3399 case BarrierSet::bs_name: { \
3400 resolve<use_compressed, typename BarrierSet::GetType<BarrierSet::bs_name>::type>(); \
3401 } \
3402 break;
3403 FOR_EACH_BARRIER_SET_DO(BARRIER_SET_RESOLVE_BARRIER_CLOSURE)
3404 #undef BARRIER_SET_RESOLVE_BARRIER_CLOSURE
3405
3406 default:
3407 fatal("BarrierSet resolving not implemented");
3408 };
3409 }
3410
3411 template <bool use_compressed, typename BarrierSetT>
3412 static void resolve() {
3413 typedef Config<use_compressed ? oop_kind::NARROW : oop_kind::WIDE, BarrierSetT> SelectedConfigT;
3414
3415 freeze_entry = (address)freeze<SelectedConfigT>;
3416 freeze_preempt_entry = (address)SelectedConfigT::freeze_preempt;
3417
3418 // If we wanted, we could templatize by kind and have three different thaw entries
3419 thaw_entry = (address)thaw<SelectedConfigT>;
3420 }
3421 };
3422
3423 void Continuation::init() {
3424 ConfigResolve::resolve();
3425 }