1 /*
   2  * Copyright (c) 2017, 2020, 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 "precompiled.hpp"
  26 #include "logging/log.hpp"
  27 #include "logging/logStream.hpp"
  28 #include "memory/resourceArea.hpp"
  29 #include "runtime/atomic.hpp"
  30 #include "runtime/handshake.hpp"
  31 #include "runtime/interfaceSupport.inline.hpp"
  32 #include "runtime/osThread.hpp"
  33 #include "runtime/semaphore.inline.hpp"
  34 #include "runtime/task.hpp"
  35 #include "runtime/thread.hpp"
  36 #include "runtime/vmThread.hpp"
  37 #include "utilities/formatBuffer.hpp"
  38 #include "utilities/preserveException.hpp"
  39 




  40 
  41 class HandshakeOperation: public StackObj {

  42   HandshakeClosure* _handshake_cl;
  43   int32_t _pending_threads;
  44   bool _executed;
  45   bool _is_direct;
  46 public:
  47   HandshakeOperation(HandshakeClosure* cl, bool is_direct = false) :
  48     _handshake_cl(cl),
  49     _pending_threads(1),
  50     _executed(false),
  51     _is_direct(is_direct) {}
  52 
  53   void do_handshake(JavaThread* thread);
  54   bool is_completed() {
  55     int32_t val = Atomic::load(&_pending_threads);
  56     assert(val >= 0, "_pending_threads=%d cannot be negative", val);
  57     return val == 0;
  58   }
  59   void add_target_count(int count) { Atomic::add(&_pending_threads, count, memory_order_relaxed); }
  60   bool executed() const { return _executed; }
  61   const char* name() { return _handshake_cl->name(); }
  62 
  63   bool is_direct() { return _is_direct; }




  64 };
  65 


  66 class VM_Handshake: public VM_Operation {
  67   const jlong _handshake_timeout;
  68  public:
  69   bool evaluate_at_safepoint() const { return false; }
  70 
  71  protected:
  72   HandshakeOperation* const _op;
  73 
  74   VM_Handshake(HandshakeOperation* op) :
  75       _handshake_timeout(TimeHelper::millis_to_counter(HandshakeTimeout)), _op(op) {}
  76 









  77   bool handshake_has_timed_out(jlong start_time);
  78   static void handle_timeout();
  79 };
  80 
  81 bool VM_Handshake::handshake_has_timed_out(jlong start_time) {
  82   // Check if handshake operation has timed out
  83   if (_handshake_timeout > 0) {
  84     return os::elapsed_counter() >= (start_time + _handshake_timeout);
  85   }
  86   return false;
  87 }
  88 
  89 void VM_Handshake::handle_timeout() {
  90   LogStreamHandle(Warning, handshake) log_stream;
  91   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *thr = jtiwh.next(); ) {
  92     if (thr->has_handshake()) {
  93       log_stream.print("Thread " PTR_FORMAT " has not cleared its handshake op", p2i(thr));
  94       thr->print_thread_state_on(&log_stream);
  95     }
  96   }
  97   log_stream.flush();
  98   fatal("Handshake operation timed out");
  99 }
 100 
 101 static void log_handshake_info(jlong start_time_ns, const char* name, int targets, int vmt_executed, const char* extra = NULL) {
 102   if (start_time_ns != 0) {
 103     jlong completion_time = os::javaTimeNanos() - start_time_ns;
 104     log_info(handshake)("Handshake \"%s\", Targeted threads: %d, Executed by targeted threads: %d, Total completion time: " JLONG_FORMAT " ns%s%s",
 105                         name, targets,
 106                         targets - vmt_executed,
 107                         completion_time,
 108                         extra != NULL ? ", " : "",
 109                         extra != NULL ? extra : "");
 110   }
 111 }
 112 
 113 class VM_HandshakeOneThread: public VM_Handshake {
 114   JavaThread* _target;
 115  public:
 116   VM_HandshakeOneThread(HandshakeOperation* op, JavaThread* target) :
 117     VM_Handshake(op), _target(target) {}
 118 
 119   void doit() {


 120     jlong start_time_ns = 0;
 121     if (log_is_enabled(Info, handshake)) {
 122       start_time_ns = os::javaTimeNanos();
 123     }
 124 
 125     ThreadsListHandle tlh;
 126     if (tlh.includes(_target)) {
 127       _target->set_handshake_operation(_op);
 128     } else {
 129       log_handshake_info(start_time_ns, _op->name(), 0, 0, "(thread dead)");
 130       return;
 131     }
 132 
 133     log_trace(handshake)("JavaThread " INTPTR_FORMAT " signaled, begin attempt to process by VMThtread", p2i(_target));
 134     jlong timeout_start_time = os::elapsed_counter();
 135     bool by_vm_thread = false;
 136     do {
 137       if (handshake_has_timed_out(timeout_start_time)) {
 138         handle_timeout();
 139       }
 140       by_vm_thread = _target->handshake_try_process(_op);
 141     } while (!_op->is_completed());
 142 
 143     // This pairs up with the release store in do_handshake(). It prevents future
 144     // loads from floating above the load of _pending_threads in is_completed()
 145     // and thus prevents reading stale data modified in the handshake closure
 146     // by the Handshakee.
 147     OrderAccess::acquire();
 148 
 149     log_handshake_info(start_time_ns, _op->name(), 1, by_vm_thread ? 1 : 0);
 150   }
 151 
 152   VMOp_Type type() const { return VMOp_HandshakeOneThread; }
 153 
 154   bool executed() const { return _op->executed(); }
 155 };
 156 
 157 class VM_HandshakeAllThreads: public VM_Handshake {
 158  public:
 159   VM_HandshakeAllThreads(HandshakeOperation* op) : VM_Handshake(op) {}
 160 
 161   void doit() {


 162     jlong start_time_ns = 0;
 163     if (log_is_enabled(Info, handshake)) {
 164       start_time_ns = os::javaTimeNanos();
 165     }
 166     int handshake_executed_by_vm_thread = 0;
 167 
 168     JavaThreadIteratorWithHandle jtiwh;
 169     int number_of_threads_issued = 0;
 170     for (JavaThread *thr = jtiwh.next(); thr != NULL; thr = jtiwh.next()) {
 171       thr->set_handshake_operation(_op);
 172       number_of_threads_issued++;
 173     }
 174 
 175     if (number_of_threads_issued < 1) {
 176       log_handshake_info(start_time_ns, _op->name(), 0, 0);
 177       return;
 178     }
 179     // _op was created with a count == 1 so don't double count.
 180     _op->add_target_count(number_of_threads_issued - 1);
 181 
 182     log_trace(handshake)("Threads signaled, begin processing blocked threads by VMThread");
 183     const jlong start_time = os::elapsed_counter();

 184     do {
 185       // Check if handshake operation has timed out
 186       if (handshake_has_timed_out(start_time)) {
 187         handle_timeout();
 188       }
 189 
 190       // Have VM thread perform the handshake operation for blocked threads.
 191       // Observing a blocked state may of course be transient but the processing is guarded
 192       // by semaphores and we optimistically begin by working on the blocked threads
 193       jtiwh.rewind();
 194       for (JavaThread *thr = jtiwh.next(); thr != NULL; thr = jtiwh.next()) {
 195         // A new thread on the ThreadsList will not have an operation,
 196         // hence it is skipped in handshake_try_process.
 197         if (thr->handshake_try_process(_op)) {
 198           handshake_executed_by_vm_thread++;
 199         }
 200       }
 201     } while (!_op->is_completed());



 202 
 203     // This pairs up with the release store in do_handshake(). It prevents future
 204     // loads from floating above the load of _pending_threads in is_completed()
 205     // and thus prevents reading stale data modified in the handshake closure
 206     // by the Handshakee.
 207     OrderAccess::acquire();
 208 
 209     log_handshake_info(start_time_ns, _op->name(), number_of_threads_issued, handshake_executed_by_vm_thread);
 210   }
 211 
 212   VMOp_Type type() const { return VMOp_HandshakeAllThreads; }
 213 };
 214 
 215 void HandshakeOperation::do_handshake(JavaThread* thread) {
 216   jlong start_time_ns = 0;
 217   if (log_is_enabled(Debug, handshake, task)) {
 218     start_time_ns = os::javaTimeNanos();
 219   }
 220 
 221   // Only actually execute the operation for non terminated threads.
 222   if (!thread->is_terminated()) {
 223     _handshake_cl->do_thread(thread);
 224     _executed = true;
 225   }
 226 
 227   if (start_time_ns != 0) {
 228     jlong completion_time = os::javaTimeNanos() - start_time_ns;
 229     log_debug(handshake, task)("Operation: %s for thread " PTR_FORMAT ", is_vm_thread: %s, completed in " JLONG_FORMAT " ns",
 230                                name(), p2i(thread), BOOL_TO_STR(Thread::current()->is_VM_thread()), completion_time);
 231   }
 232 
 233   // Inform VMThread/Handshaker that we have completed the operation.
 234   // When this is executed by the Handshakee we need a release store
 235   // here to make sure memory operations executed in the handshake
 236   // closure are visible to the VMThread/Handshaker after it reads
 237   // that the operation has completed.
 238   Atomic::dec(&_pending_threads, memory_order_release);
 239 
 240   // It is no longer safe to refer to 'this' as the VMThread/Handshaker may have destroyed this operation
 241 }
 242 
 243 void Handshake::execute(HandshakeClosure* thread_cl) {
 244   HandshakeOperation cto(thread_cl);
 245   VM_HandshakeAllThreads handshake(&cto);
 246   VMThread::execute(&handshake);
 247 }
 248 
 249 bool Handshake::execute(HandshakeClosure* thread_cl, JavaThread* target) {
 250   HandshakeOperation cto(thread_cl);
 251   VM_HandshakeOneThread handshake(&cto, target);
 252   VMThread::execute(&handshake);
 253   return handshake.executed();
 254 }
 255 
 256 bool Handshake::execute_direct(HandshakeClosure* thread_cl, JavaThread* target) {
 257   JavaThread* self = JavaThread::current();
 258   HandshakeOperation op(thread_cl, /*is_direct*/ true);
 259 
 260   jlong start_time_ns = 0;
 261   if (log_is_enabled(Info, handshake)) {
 262     start_time_ns = os::javaTimeNanos();
 263   }
 264 
 265   ThreadsListHandle tlh;
 266   if (tlh.includes(target)) {
 267     target->set_handshake_operation(&op);
 268   } else {
 269     log_handshake_info(start_time_ns, op.name(), 0, 0, "(thread dead)");
 270     return false;
 271   }
 272 
 273   bool by_handshaker = false;
 274   while (!op.is_completed()) {
 275     by_handshaker = target->handshake_try_process(&op);
 276     // Check for pending handshakes to avoid possible deadlocks where our
 277     // target is trying to handshake us.
 278     if (SafepointMechanism::should_block(self)) {
 279       ThreadBlockInVM tbivm(self);
 280     }
 281   }
 282 
 283   // This pairs up with the release store in do_handshake(). It prevents future
 284   // loads from floating above the load of _pending_threads in is_completed()
 285   // and thus prevents reading stale data modified in the handshake closure
 286   // by the Handshakee.
 287   OrderAccess::acquire();
 288 
 289   log_handshake_info(start_time_ns, op.name(), 1, by_handshaker ? 1 : 0);
 290 
 291   return op.executed();
 292 }
 293 
 294 HandshakeState::HandshakeState() :
 295   _operation(NULL),
 296   _operation_direct(NULL),
 297   _handshake_turn_sem(1),
 298   _processing_sem(1),
 299   _thread_in_process_handshake(false)
 300 {
 301   DEBUG_ONLY(_active_handshaker = NULL;)
 302 }
 303 
 304 void HandshakeState::set_operation(HandshakeOperation* op) {
 305   if (!op->is_direct()) {
 306     assert(Thread::current()->is_VM_thread(), "should be the VMThread");
 307     _operation = op;
 308   } else {
 309     assert(Thread::current()->is_Java_thread(), "should be a JavaThread");
 310     // Serialize direct handshakes so that only one proceeds at a time for a given target
 311     _handshake_turn_sem.wait_with_safepoint_check(JavaThread::current());
 312     _operation_direct = op;
 313   }
 314   SafepointMechanism::arm_local_poll_release(_handshakee);
 315 }
 316 
 317 void HandshakeState::clear_handshake(bool is_direct) {
 318   if (!is_direct) {
 319     _operation = NULL;
 320   } else {
 321     _operation_direct = NULL;
 322     _handshake_turn_sem.signal();
 323   }
 324 }
 325 
 326 void HandshakeState::process_self_inner() {
 327   assert(Thread::current() == _handshakee, "should call from _handshakee");
 328   assert(!_handshakee->is_terminated(), "should not be a terminated thread");
 329   assert(_handshakee->thread_state() != _thread_blocked, "should not be in a blocked state");
 330   assert(_handshakee->thread_state() != _thread_in_native, "should not be in native");
 331   JavaThread* self = _handshakee;
 332 
 333   do {
 334     ThreadInVMForHandshake tivm(self);
 335     if (!_processing_sem.trywait()) {
 336       _processing_sem.wait_with_safepoint_check(self);
 337     }
 338     if (has_operation()) {
 339       HandleMark hm(self);
 340       CautiouslyPreserveExceptionMark pem(self);
 341       HandshakeOperation * op = _operation;
 342       if (op != NULL) {
 343         // Disarm before executing the operation
 344         clear_handshake(/*is_direct*/ false);
 345         op->do_handshake(self);
 346       }
 347       op = _operation_direct;
 348       if (op != NULL) {
 349         // Disarm before executing the operation
 350         clear_handshake(/*is_direct*/ true);
 351         op->do_handshake(self);


 352       }
 353     }
 354     _processing_sem.signal();
 355   } while (has_operation());
 356 }
 357 
 358 bool HandshakeState::can_process_handshake() {
 359   // handshake_safe may only be called with polls armed.
 360   // Handshaker controls this by first claiming the handshake via claim_handshake().
 361   return SafepointSynchronize::handshake_safe(_handshakee);
 362 }
 363 
 364 bool HandshakeState::possibly_can_process_handshake() {
 365   // Note that this method is allowed to produce false positives.
 366   if (_handshakee->is_ext_suspended()) {
 367     return true;
 368   }
 369   if (_handshakee->is_terminated()) {
 370     return true;
 371   }
 372   switch (_handshakee->thread_state()) {
 373   case _thread_in_native:
 374     // native threads are safe if they have no java stack or have walkable stack
 375     return !_handshakee->has_last_Java_frame() || _handshakee->frame_anchor()->walkable();
 376 
 377   case _thread_blocked:
 378     return true;
 379 
 380   default:
 381     return false;
 382   }
 383 }
 384 
 385 bool HandshakeState::claim_handshake(bool is_direct) {
 386   if (!_processing_sem.trywait()) {
 387     return false;
 388   }
 389   if (has_specific_operation(is_direct)){
 390     return true;
 391   }
 392   _processing_sem.signal();
 393   return false;
 394 }
 395 
 396 bool HandshakeState::try_process(HandshakeOperation* op) {
 397   bool is_direct = op->is_direct();
 398 
 399   if (!has_specific_operation(is_direct)){
 400     // JT has already cleared its handshake
 401     return false;
 402   }
 403 
 404   if (!possibly_can_process_handshake()) {
 405     // JT is observed in an unsafe state, it must notice the handshake itself
 406     return false;
 407   }
 408 
 409   // Claim the semaphore if there still an operation to be executed.
 410   if (!claim_handshake(is_direct)) {
 411     return false;
 412   }
 413 
 414   // Check if the handshake operation is the same as the one we meant to execute. The
 415   // handshake could have been already processed by the handshakee and a new handshake
 416   // by another JavaThread might be in progress.
 417   if (is_direct && op != _operation_direct) {
 418     _processing_sem.signal();
 419     return false;
 420   }
 421 
 422   // If we own the semaphore at this point and while owning the semaphore
 423   // can observe a safe state the thread cannot possibly continue without
 424   // getting caught by the semaphore.
 425   bool executed = false;
 426   if (can_process_handshake()) {
 427     guarantee(!_processing_sem.trywait(), "we should already own the semaphore");
 428     log_trace(handshake)("Processing handshake by %s", Thread::current()->is_VM_thread() ? "VMThread" : "Handshaker");
 429     DEBUG_ONLY(_active_handshaker = Thread::current();)
 430     op->do_handshake(_handshakee);
 431     DEBUG_ONLY(_active_handshaker = NULL;)
 432     // Disarm after we have executed the operation.
 433     clear_handshake(is_direct);
 434     executed = true;
 435   }
 436 
 437   // Release the thread
 438   _processing_sem.signal();
 439 
 440   return executed;
 441 }
--- EOF ---