1 /*
   2  * Copyright (c) 2002, 2018, 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 "gc/parallel/gcTaskManager.hpp"
  27 #include "gc/parallel/mutableSpace.hpp"
  28 #include "gc/parallel/parallelScavengeHeap.hpp"
  29 #include "gc/parallel/psOldGen.hpp"
  30 #include "gc/parallel/psPromotionManager.inline.hpp"
  31 #include "gc/parallel/psScavenge.inline.hpp"
  32 #include "gc/shared/gcTrace.hpp"
  33 #include "gc/shared/preservedMarks.inline.hpp"
  34 #include "gc/shared/taskqueue.inline.hpp"
  35 #include "logging/log.hpp"
  36 #include "logging/logStream.hpp"
  37 #include "memory/allocation.inline.hpp"
  38 #include "memory/memRegion.hpp"
  39 #include "memory/padded.inline.hpp"
  40 #include "memory/resourceArea.hpp"
  41 #include "oops/access.inline.hpp"
  42 #include "oops/arrayOop.inline.hpp"
  43 #include "oops/compressedOops.inline.hpp"
  44 #include "oops/instanceKlass.inline.hpp"
  45 #include "oops/instanceMirrorKlass.inline.hpp"
  46 #include "oops/objArrayKlass.inline.hpp"
  47 #include "oops/objArrayOop.inline.hpp"
  48 #include "oops/oop.inline.hpp"
  49 
  50 PaddedEnd<PSPromotionManager>* PSPromotionManager::_manager_array = NULL;
  51 OopStarTaskQueueSet*           PSPromotionManager::_stack_array_depth = NULL;
  52 PreservedMarksSet*             PSPromotionManager::_preserved_marks_set = NULL;
  53 PSOldGen*                      PSPromotionManager::_old_gen = NULL;
  54 MutableSpace*                  PSPromotionManager::_young_space = NULL;
  55 
  56 void PSPromotionManager::initialize() {
  57   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
  58 
  59   _old_gen = heap->old_gen();
  60   _young_space = heap->young_gen()->to_space();
  61 
  62   const uint promotion_manager_num = ParallelGCThreads + 1;
  63 
  64   // To prevent false sharing, we pad the PSPromotionManagers
  65   // and make sure that the first instance starts at a cache line.
  66   assert(_manager_array == NULL, "Attempt to initialize twice");
  67   _manager_array = PaddedArray<PSPromotionManager, mtGC>::create_unfreeable(promotion_manager_num);
  68   guarantee(_manager_array != NULL, "Could not initialize promotion manager");
  69 
  70   _stack_array_depth = new OopStarTaskQueueSet(ParallelGCThreads);
  71   guarantee(_stack_array_depth != NULL, "Could not initialize promotion manager");
  72 
  73   // Create and register the PSPromotionManager(s) for the worker threads.
  74   for(uint i=0; i<ParallelGCThreads; i++) {
  75     stack_array_depth()->register_queue(i, _manager_array[i].claimed_stack_depth());
  76   }
  77   // The VMThread gets its own PSPromotionManager, which is not available
  78   // for work stealing.
  79 
  80   assert(_preserved_marks_set == NULL, "Attempt to initialize twice");
  81   _preserved_marks_set = new PreservedMarksSet(true /* in_c_heap */);
  82   guarantee(_preserved_marks_set != NULL, "Could not initialize preserved marks set");
  83   _preserved_marks_set->init(promotion_manager_num);
  84   for (uint i = 0; i < promotion_manager_num; i += 1) {
  85     _manager_array[i].register_preserved_marks(_preserved_marks_set->get(i));
  86   }
  87 }
  88 
  89 // Helper functions to get around the circular dependency between
  90 // psScavenge.inline.hpp and psPromotionManager.inline.hpp.
  91 bool PSPromotionManager::should_scavenge(oop* p, bool check_to_space) {
  92   return PSScavenge::should_scavenge(p, check_to_space);
  93 }
  94 bool PSPromotionManager::should_scavenge(narrowOop* p, bool check_to_space) {
  95   return PSScavenge::should_scavenge(p, check_to_space);
  96 }
  97 
  98 PSPromotionManager* PSPromotionManager::gc_thread_promotion_manager(uint index) {
  99   assert(index < ParallelGCThreads, "index out of range");
 100   assert(_manager_array != NULL, "Sanity");
 101   return &_manager_array[index];
 102 }
 103 
 104 PSPromotionManager* PSPromotionManager::vm_thread_promotion_manager() {
 105   assert(_manager_array != NULL, "Sanity");
 106   return &_manager_array[ParallelGCThreads];
 107 }
 108 
 109 void PSPromotionManager::pre_scavenge() {
 110   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 111 
 112   _preserved_marks_set->assert_empty();
 113   _young_space = heap->young_gen()->to_space();
 114 
 115   for(uint i=0; i<ParallelGCThreads+1; i++) {
 116     manager_array(i)->reset();
 117   }
 118 }
 119 
 120 bool PSPromotionManager::post_scavenge(YoungGCTracer& gc_tracer) {
 121   bool promotion_failure_occurred = false;
 122 
 123   TASKQUEUE_STATS_ONLY(print_taskqueue_stats());
 124   for (uint i = 0; i < ParallelGCThreads + 1; i++) {
 125     PSPromotionManager* manager = manager_array(i);
 126     assert(manager->claimed_stack_depth()->is_empty(), "should be empty");
 127     if (manager->_promotion_failed_info.has_failed()) {
 128       gc_tracer.report_promotion_failed(manager->_promotion_failed_info);
 129       promotion_failure_occurred = true;
 130     }
 131     manager->flush_labs();
 132   }
 133   if (!promotion_failure_occurred) {
 134     // If there was no promotion failure, the preserved mark stacks
 135     // should be empty.
 136     _preserved_marks_set->assert_empty();
 137   }
 138   return promotion_failure_occurred;
 139 }
 140 
 141 #if TASKQUEUE_STATS
 142 void
 143 PSPromotionManager::print_local_stats(outputStream* const out, uint i) const {
 144   #define FMT " " SIZE_FORMAT_W(10)
 145   out->print_cr("%3u" FMT FMT FMT FMT, i, _masked_pushes, _masked_steals,
 146                 _arrays_chunked, _array_chunks_processed);
 147   #undef FMT
 148 }
 149 
 150 static const char* const pm_stats_hdr[] = {
 151   "    --------masked-------     arrays      array",
 152   "thr       push      steal    chunked     chunks",
 153   "--- ---------- ---------- ---------- ----------"
 154 };
 155 
 156 void
 157 PSPromotionManager::print_taskqueue_stats() {
 158   if (!log_develop_is_enabled(Trace, gc, task, stats)) {
 159     return;
 160   }
 161   Log(gc, task, stats) log;
 162   ResourceMark rm;
 163   LogStream ls(log.trace());
 164   outputStream* out = &ls;
 165   out->print_cr("== GC Tasks Stats, GC %3d",
 166                 ParallelScavengeHeap::heap()->total_collections());
 167 
 168   TaskQueueStats totals;
 169   out->print("thr "); TaskQueueStats::print_header(1, out); out->cr();
 170   out->print("--- "); TaskQueueStats::print_header(2, out); out->cr();
 171   for (uint i = 0; i < ParallelGCThreads + 1; ++i) {
 172     TaskQueueStats& next = manager_array(i)->_claimed_stack_depth.stats;
 173     out->print("%3d ", i); next.print(out); out->cr();
 174     totals += next;
 175   }
 176   out->print("tot "); totals.print(out); out->cr();
 177 
 178   const uint hlines = sizeof(pm_stats_hdr) / sizeof(pm_stats_hdr[0]);
 179   for (uint i = 0; i < hlines; ++i) out->print_cr("%s", pm_stats_hdr[i]);
 180   for (uint i = 0; i < ParallelGCThreads + 1; ++i) {
 181     manager_array(i)->print_local_stats(out, i);
 182   }
 183 }
 184 
 185 void
 186 PSPromotionManager::reset_stats() {
 187   claimed_stack_depth()->stats.reset();
 188   _masked_pushes = _masked_steals = 0;
 189   _arrays_chunked = _array_chunks_processed = 0;
 190 }
 191 #endif // TASKQUEUE_STATS
 192 
 193 PSPromotionManager::PSPromotionManager() {
 194   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 195 
 196   // We set the old lab's start array.
 197   _old_lab.set_start_array(old_gen()->start_array());
 198 
 199   uint queue_size;
 200   claimed_stack_depth()->initialize();
 201   queue_size = claimed_stack_depth()->max_elems();
 202 
 203   _totally_drain = (ParallelGCThreads == 1) || (GCDrainStackTargetSize == 0);
 204   if (_totally_drain) {
 205     _target_stack_size = 0;
 206   } else {
 207     // don't let the target stack size to be more than 1/4 of the entries
 208     _target_stack_size = (uint) MIN2((uint) GCDrainStackTargetSize,
 209                                      (uint) (queue_size / 4));
 210   }
 211 
 212   _array_chunk_size = ParGCArrayScanChunk;
 213   // let's choose 1.5x the chunk size
 214   _min_array_size_for_chunking = 3 * _array_chunk_size / 2;
 215 
 216   _preserved_marks = NULL;
 217 
 218   reset();
 219 }
 220 
 221 void PSPromotionManager::reset() {
 222   assert(stacks_empty(), "reset of non-empty stack");
 223 
 224   // We need to get an assert in here to make sure the labs are always flushed.
 225 
 226   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 227 
 228   // Do not prefill the LAB's, save heap wastage!
 229   HeapWord* lab_base = young_space()->top();
 230   _young_lab.initialize(MemRegion(lab_base, (size_t)0));
 231   _young_gen_is_full = false;
 232 
 233   lab_base = old_gen()->object_space()->top();
 234   _old_lab.initialize(MemRegion(lab_base, (size_t)0));
 235   _old_gen_is_full = false;
 236 
 237   _promotion_failed_info.reset();
 238 
 239   TASKQUEUE_STATS_ONLY(reset_stats());
 240 }
 241 
 242 void PSPromotionManager::register_preserved_marks(PreservedMarks* preserved_marks) {
 243   assert(_preserved_marks == NULL, "do not set it twice");
 244   _preserved_marks = preserved_marks;
 245 }
 246 
 247 class ParRestoreGCTask : public GCTask {
 248 private:
 249   const uint _id;
 250   PreservedMarksSet* const _preserved_marks_set;
 251   volatile size_t* const _total_size_addr;
 252 
 253 public:
 254   virtual char* name() {
 255     return (char*) "preserved mark restoration task";
 256   }
 257 
 258   virtual void do_it(GCTaskManager* manager, uint which){
 259     _preserved_marks_set->get(_id)->restore_and_increment(_total_size_addr);
 260   }
 261 
 262   ParRestoreGCTask(uint id,
 263                    PreservedMarksSet* preserved_marks_set,
 264                    volatile size_t* total_size_addr)
 265     : _id(id),
 266       _preserved_marks_set(preserved_marks_set),
 267       _total_size_addr(total_size_addr) { }
 268 };
 269 
 270 class PSRestorePreservedMarksTaskExecutor : public RestorePreservedMarksTaskExecutor {
 271 private:
 272   GCTaskManager* _gc_task_manager;
 273 
 274 public:
 275   PSRestorePreservedMarksTaskExecutor(GCTaskManager* gc_task_manager)
 276       : _gc_task_manager(gc_task_manager) { }
 277 
 278   void restore(PreservedMarksSet* preserved_marks_set,
 279                volatile size_t* total_size_addr) {
 280     // GCTask / GCTaskQueue are ResourceObjs
 281     ResourceMark rm;
 282 
 283     GCTaskQueue* q = GCTaskQueue::create();
 284     for (uint i = 0; i < preserved_marks_set->num(); i += 1) {
 285       q->enqueue(new ParRestoreGCTask(i, preserved_marks_set, total_size_addr));
 286     }
 287     _gc_task_manager->execute_and_wait(q);
 288   }
 289 };
 290 
 291 void PSPromotionManager::restore_preserved_marks() {
 292   PSRestorePreservedMarksTaskExecutor task_executor(PSScavenge::gc_task_manager());
 293   _preserved_marks_set->restore(&task_executor);
 294 }
 295 
 296 void PSPromotionManager::drain_stacks_depth(bool totally_drain) {
 297   totally_drain = totally_drain || _totally_drain;
 298 
 299 #ifdef ASSERT
 300   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 301   MutableSpace* to_space = heap->young_gen()->to_space();
 302   MutableSpace* old_space = heap->old_gen()->object_space();
 303 #endif /* ASSERT */
 304 
 305   OopStarTaskQueue* const tq = claimed_stack_depth();
 306   do {
 307     StarTask p;
 308 
 309     // Drain overflow stack first, so other threads can steal from
 310     // claimed stack while we work.
 311     while (tq->pop_overflow(p)) {
 312       process_popped_location_depth(p);
 313     }
 314 
 315     if (totally_drain) {
 316       while (tq->pop_local(p)) {
 317         process_popped_location_depth(p);
 318       }
 319     } else {
 320       while (tq->size() > _target_stack_size && tq->pop_local(p)) {
 321         process_popped_location_depth(p);
 322       }
 323     }
 324   } while ((totally_drain && !tq->taskqueue_empty()) || !tq->overflow_empty());
 325 
 326   assert(!totally_drain || tq->taskqueue_empty(), "Sanity");
 327   assert(totally_drain || tq->size() <= _target_stack_size, "Sanity");
 328   assert(tq->overflow_empty(), "Sanity");
 329 }
 330 
 331 void PSPromotionManager::flush_labs() {
 332   assert(stacks_empty(), "Attempt to flush lab with live stack");
 333 
 334   // If either promotion lab fills up, we can flush the
 335   // lab but not refill it, so check first.
 336   assert(!_young_lab.is_flushed() || _young_gen_is_full, "Sanity");
 337   if (!_young_lab.is_flushed())
 338     _young_lab.flush();
 339 
 340   assert(!_old_lab.is_flushed() || _old_gen_is_full, "Sanity");
 341   if (!_old_lab.is_flushed())
 342     _old_lab.flush();
 343 
 344   // Let PSScavenge know if we overflowed
 345   if (_young_gen_is_full) {
 346     PSScavenge::set_survivor_overflow(true);
 347   }
 348 }
 349 
 350 template <class T> void PSPromotionManager::process_array_chunk_work(
 351                                                  oop obj,
 352                                                  int start, int end) {
 353   assert(start <= end, "invariant");
 354   T* const base      = (T*)objArrayOop(obj)->base();
 355   T* p               = base + start;
 356   T* const chunk_end = base + end;
 357   while (p < chunk_end) {
 358     if (PSScavenge::should_scavenge(p)) {
 359       claim_or_forward_depth(p);
 360     }
 361     ++p;
 362   }
 363 }
 364 
 365 void PSPromotionManager::process_array_chunk(oop old) {
 366   assert(PSChunkLargeArrays, "invariant");
 367   assert(old->is_objArray(), "invariant");
 368   assert(old->is_forwarded(), "invariant");
 369 
 370   TASKQUEUE_STATS_ONLY(++_array_chunks_processed);
 371 
 372   oop const obj = old->forwardee();
 373 
 374   int start;
 375   int const end = arrayOop(old)->length();
 376   if (end > (int) _min_array_size_for_chunking) {
 377     // we'll chunk more
 378     start = end - _array_chunk_size;
 379     assert(start > 0, "invariant");
 380     arrayOop(old)->set_length(start);
 381     push_depth(mask_chunked_array_oop(old));
 382     TASKQUEUE_STATS_ONLY(++_masked_pushes);
 383   } else {
 384     // this is the final chunk for this array
 385     start = 0;
 386     int const actual_length = arrayOop(obj)->length();
 387     arrayOop(old)->set_length(actual_length);
 388   }
 389 
 390   if (UseCompressedOops) {
 391     process_array_chunk_work<narrowOop>(obj, start, end);
 392   } else {
 393     process_array_chunk_work<oop>(obj, start, end);
 394   }
 395 }
 396 
 397 class PushContentsClosure : public ExtendedOopClosure {
 398   PSPromotionManager* _pm;
 399  public:
 400   PushContentsClosure(PSPromotionManager* pm) : _pm(pm) {}
 401 
 402   template <typename T> void do_oop_nv(T* p) {
 403     if (PSScavenge::should_scavenge(p)) {
 404       _pm->claim_or_forward_depth(p);
 405     }
 406   }
 407 
 408   virtual void do_oop(oop* p)       { do_oop_nv(p); }
 409   virtual void do_oop(narrowOop* p) { do_oop_nv(p); }
 410 
 411   // Don't use the oop verification code in the oop_oop_iterate framework.
 412   debug_only(virtual bool should_verify_oops() { return false; })
 413 };
 414 
 415 void InstanceKlass::oop_ps_push_contents(oop obj, PSPromotionManager* pm) {
 416   PushContentsClosure cl(pm);
 417   oop_oop_iterate_oop_maps_reverse<true>(obj, &cl);
 418 }
 419 
 420 void InstanceMirrorKlass::oop_ps_push_contents(oop obj, PSPromotionManager* pm) {
 421     // Note that we don't have to follow the mirror -> klass pointer, since all
 422     // klasses that are dirty will be scavenged when we iterate over the
 423     // ClassLoaderData objects.
 424 
 425   InstanceKlass::oop_ps_push_contents(obj, pm);
 426 
 427   PushContentsClosure cl(pm);
 428   oop_oop_iterate_statics<true>(obj, &cl);
 429 }
 430 
 431 void InstanceClassLoaderKlass::oop_ps_push_contents(oop obj, PSPromotionManager* pm) {
 432   InstanceKlass::oop_ps_push_contents(obj, pm);
 433 
 434   // This is called by the young collector. It will already have taken care of
 435   // all class loader data. So, we don't have to follow the class loader ->
 436   // class loader data link.
 437 }
 438 
 439 template <class T>
 440 static void oop_ps_push_contents_specialized(oop obj, InstanceRefKlass *klass, PSPromotionManager* pm) {
 441   T* referent_addr = (T*)java_lang_ref_Reference::referent_addr_raw(obj);
 442   if (PSScavenge::should_scavenge(referent_addr)) {
 443     ReferenceProcessor* rp = PSScavenge::reference_processor();
 444     if (rp->discover_reference(obj, klass->reference_type())) {
 445       // reference already enqueued, referent and next will be traversed later
 446       klass->InstanceKlass::oop_ps_push_contents(obj, pm);
 447       return;
 448     } else {
 449       // treat referent as normal oop
 450       pm->claim_or_forward_depth(referent_addr);
 451     }
 452   }
 453   // Treat discovered as normal oop, if ref is not "active",
 454   // i.e. if next is non-NULL.
 455   T* next_addr = (T*)java_lang_ref_Reference::next_addr_raw(obj);
 456   T  next_oop = RawAccess<>::oop_load(next_addr);
 457   if (!CompressedOops::is_null(next_oop)) { // i.e. ref is not "active"
 458     T* discovered_addr = (T*)java_lang_ref_Reference::discovered_addr_raw(obj);
 459     log_develop_trace(gc, ref)("   Process discovered as normal " PTR_FORMAT, p2i(discovered_addr));
 460     if (PSScavenge::should_scavenge(discovered_addr)) {
 461       pm->claim_or_forward_depth(discovered_addr);
 462     }
 463   }
 464   // Treat next as normal oop;  next is a link in the reference queue.
 465   if (PSScavenge::should_scavenge(next_addr)) {
 466     pm->claim_or_forward_depth(next_addr);
 467   }
 468   klass->InstanceKlass::oop_ps_push_contents(obj, pm);
 469 }
 470 
 471 void InstanceRefKlass::oop_ps_push_contents(oop obj, PSPromotionManager* pm) {
 472   if (UseCompressedOops) {
 473     oop_ps_push_contents_specialized<narrowOop>(obj, this, pm);
 474   } else {
 475     oop_ps_push_contents_specialized<oop>(obj, this, pm);
 476   }
 477 }
 478 
 479 void ObjArrayKlass::oop_ps_push_contents(oop obj, PSPromotionManager* pm) {
 480   assert(obj->is_objArray(), "obj must be obj array");
 481   PushContentsClosure cl(pm);
 482   oop_oop_iterate_elements<true>(objArrayOop(obj), &cl);
 483 }
 484 
 485 void TypeArrayKlass::oop_ps_push_contents(oop obj, PSPromotionManager* pm) {
 486   assert(obj->is_typeArray(),"must be a type array");
 487   ShouldNotReachHere();
 488 }
 489 
 490 oop PSPromotionManager::oop_promotion_failed(oop obj, markOop obj_mark) {
 491   assert(_old_gen_is_full || PromotionFailureALot, "Sanity");
 492 
 493   // Attempt to CAS in the header.
 494   // This tests if the header is still the same as when
 495   // this started.  If it is the same (i.e., no forwarding
 496   // pointer has been installed), then this thread owns
 497   // it.
 498   if (obj->cas_forward_to(obj, obj_mark)) {
 499     // We won any races, we "own" this object.
 500     assert(obj == obj->forwardee(), "Sanity");
 501 
 502     _promotion_failed_info.register_copy_failure(obj->size());
 503 
 504     push_contents(obj);
 505 
 506     _preserved_marks->push_if_necessary(obj, obj_mark);
 507   }  else {
 508     // We lost, someone else "owns" this object
 509     guarantee(obj->is_forwarded(), "Object must be forwarded if the cas failed.");
 510 
 511     // No unallocation to worry about.
 512     obj = obj->forwardee();
 513   }
 514 
 515   log_develop_trace(gc, scavenge)("{promotion-failure %s " PTR_FORMAT " (%d)}", obj->klass()->internal_name(), p2i(obj), obj->size());
 516 
 517   return obj;
 518 }