1 /*
   2  * Copyright (c) 2010, 2014, 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_implementation/concurrentMarkSweep/compactibleFreeListSpace.hpp"
  27 #include "gc_implementation/concurrentMarkSweep/promotionInfo.hpp"
  28 #include "oops/markOop.inline.hpp"
  29 #include "oops/oop.inline.hpp"
  30 
  31 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
  32 
  33 /////////////////////////////////////////////////////////////////////////
  34 //// PromotionInfo
  35 /////////////////////////////////////////////////////////////////////////
  36 
  37 
  38 //////////////////////////////////////////////////////////////////////////////
  39 // We go over the list of promoted objects, removing each from the list,
  40 // and applying the closure (this may, in turn, add more elements to
  41 // the tail of the promoted list, and these newly added objects will
  42 // also be processed) until the list is empty.
  43 // To aid verification and debugging, in the non-product builds
  44 // we actually forward _promoHead each time we process a promoted oop.
  45 // Note that this is not necessary in general (i.e. when we don't need to
  46 // call PromotionInfo::verify()) because oop_iterate can only add to the
  47 // end of _promoTail, and never needs to look at _promoHead.
  48 
  49 #define PROMOTED_OOPS_ITERATE_DEFN(OopClosureType, nv_suffix)               \
  50                                                                             \
  51 void PromotionInfo::promoted_oops_iterate##nv_suffix(OopClosureType* cl) {  \
  52   NOT_PRODUCT(verify());                                                    \
  53   PromotedObject *curObj, *nextObj;                                         \
  54   for (curObj = _promoHead; curObj != NULL; curObj = nextObj) {             \
  55     if ((nextObj = curObj->next()) == NULL) {                               \
  56       /* protect ourselves against additions due to closure application     \
  57          below by resetting the list.  */                                   \
  58       assert(_promoTail == curObj, "Should have been the tail");            \
  59       _promoHead = _promoTail = NULL;                                       \
  60     }                                                                       \
  61     if (curObj->hasDisplacedMark()) {                                       \
  62       /* restore displaced header */                                        \
  63       oop(curObj)->set_mark(nextDisplacedHeader());                         \
  64     } else {                                                                \
  65       /* restore prototypical header */                                     \
  66       oop(curObj)->init_mark();                                             \
  67     }                                                                       \
  68     /* The "promoted_mark" should now not be set */                         \
  69     assert(!curObj->hasPromotedMark(),                                      \
  70            "Should have been cleared by restoring displaced mark-word");    \
  71     NOT_PRODUCT(_promoHead = nextObj);                                      \
  72     if (cl != NULL) oop(curObj)->oop_iterate(cl);                           \
  73     if (nextObj == NULL) { /* start at head of list reset above */          \
  74       nextObj = _promoHead;                                                 \
  75     }                                                                       \
  76   }                                                                         \
  77   assert(noPromotions(), "post-condition violation");                       \
  78   assert(_promoHead == NULL && _promoTail == NULL, "emptied promoted list");\
  79   assert(_spoolHead == _spoolTail, "emptied spooling buffers");             \
  80   assert(_firstIndex == _nextIndex, "empty buffer");                        \
  81 }
  82 
  83 // This should have been ALL_SINCE_...() just like the others,
  84 // but, because the body of the method above is somehwat longer,
  85 // the MSVC compiler cannot cope; as a workaround, we split the
  86 // macro into its 3 constituent parts below (see original macro
  87 // definition in specializedOopClosures.hpp).
  88 SPECIALIZED_SINCE_SAVE_MARKS_CLOSURES_YOUNG(PROMOTED_OOPS_ITERATE_DEFN)
  89 PROMOTED_OOPS_ITERATE_DEFN(OopsInGenClosure,_v)
  90 
  91 
  92 // Return the next displaced header, incrementing the pointer and
  93 // recycling spool area as necessary.
  94 markOop PromotionInfo::nextDisplacedHeader() {
  95   assert(_spoolHead != NULL, "promotionInfo inconsistency");
  96   assert(_spoolHead != _spoolTail || _firstIndex < _nextIndex,
  97          "Empty spool space: no displaced header can be fetched");
  98   assert(_spoolHead->bufferSize > _firstIndex, "Off by one error at head?");
  99   markOop hdr = _spoolHead->displacedHdr[_firstIndex];
 100   // Spool forward
 101   if (++_firstIndex == _spoolHead->bufferSize) { // last location in this block
 102     // forward to next block, recycling this block into spare spool buffer
 103     SpoolBlock* tmp = _spoolHead->nextSpoolBlock;
 104     assert(_spoolHead != _spoolTail, "Spooling storage mix-up");
 105     _spoolHead->nextSpoolBlock = _spareSpool;
 106     _spareSpool = _spoolHead;
 107     _spoolHead = tmp;
 108     _firstIndex = 1;
 109     NOT_PRODUCT(
 110       if (_spoolHead == NULL) {  // all buffers fully consumed
 111         assert(_spoolTail == NULL && _nextIndex == 1,
 112                "spool buffers processing inconsistency");
 113       }
 114     )
 115   }
 116   return hdr;
 117 }
 118 
 119 void PromotionInfo::track(PromotedObject* trackOop) {
 120   track(trackOop, oop(trackOop)->klass());
 121 }
 122 
 123 void PromotionInfo::track(PromotedObject* trackOop, Klass* klassOfOop) {
 124   // make a copy of header as it may need to be spooled
 125   markOop mark = oop(trackOop)->mark();
 126   trackOop->clear_next();
 127   if (mark->must_be_preserved_for_cms_scavenge(klassOfOop)) {
 128     // save non-prototypical header, and mark oop
 129     saveDisplacedHeader(mark);
 130     trackOop->setDisplacedMark();
 131   } else {
 132     // we'd like to assert something like the following:
 133     // assert(mark == markOopDesc::prototype(), "consistency check");
 134     // ... but the above won't work because the age bits have not (yet) been
 135     // cleared. The remainder of the check would be identical to the
 136     // condition checked in must_be_preserved() above, so we don't really
 137     // have anything useful to check here!
 138   }
 139   if (_promoTail != NULL) {
 140     assert(_promoHead != NULL, "List consistency");
 141     _promoTail->setNext(trackOop);
 142     _promoTail = trackOop;
 143   } else {
 144     assert(_promoHead == NULL, "List consistency");
 145     _promoHead = _promoTail = trackOop;
 146   }
 147   // Mask as newly promoted, so we can skip over such objects
 148   // when scanning dirty cards
 149   assert(!trackOop->hasPromotedMark(), "Should not have been marked");
 150   trackOop->setPromotedMark();
 151 }
 152 
 153 // Save the given displaced header, incrementing the pointer and
 154 // obtaining more spool area as necessary.
 155 void PromotionInfo::saveDisplacedHeader(markOop hdr) {
 156   assert(_spoolHead != NULL && _spoolTail != NULL,
 157          "promotionInfo inconsistency");
 158   assert(_spoolTail->bufferSize > _nextIndex, "Off by one error at tail?");
 159   _spoolTail->displacedHdr[_nextIndex] = hdr;
 160   // Spool forward
 161   if (++_nextIndex == _spoolTail->bufferSize) { // last location in this block
 162     // get a new spooling block
 163     assert(_spoolTail->nextSpoolBlock == NULL, "tail should terminate spool list");
 164     _splice_point = _spoolTail;                   // save for splicing
 165     _spoolTail->nextSpoolBlock = getSpoolBlock(); // might fail
 166     _spoolTail = _spoolTail->nextSpoolBlock;      // might become NULL ...
 167     // ... but will attempt filling before next promotion attempt
 168     _nextIndex = 1;
 169   }
 170 }
 171 
 172 // Ensure that spooling space exists. Return false if spooling space
 173 // could not be obtained.
 174 bool PromotionInfo::ensure_spooling_space_work() {
 175   assert(!has_spooling_space(), "Only call when there is no spooling space");
 176   // Try and obtain more spooling space
 177   SpoolBlock* newSpool = getSpoolBlock();
 178   assert(newSpool == NULL ||
 179          (newSpool->bufferSize != 0 && newSpool->nextSpoolBlock == NULL),
 180         "getSpoolBlock() sanity check");
 181   if (newSpool == NULL) {
 182     return false;
 183   }
 184   _nextIndex = 1;
 185   if (_spoolTail == NULL) {
 186     _spoolTail = newSpool;
 187     if (_spoolHead == NULL) {
 188       _spoolHead = newSpool;
 189       _firstIndex = 1;
 190     } else {
 191       assert(_splice_point != NULL && _splice_point->nextSpoolBlock == NULL,
 192              "Splice point invariant");
 193       // Extra check that _splice_point is connected to list
 194       #ifdef ASSERT
 195       {
 196         SpoolBlock* blk = _spoolHead;
 197         for (; blk->nextSpoolBlock != NULL;
 198              blk = blk->nextSpoolBlock);
 199         assert(blk != NULL && blk == _splice_point,
 200                "Splice point incorrect");
 201       }
 202       #endif // ASSERT
 203       _splice_point->nextSpoolBlock = newSpool;
 204     }
 205   } else {
 206     assert(_spoolHead != NULL, "spool list consistency");
 207     _spoolTail->nextSpoolBlock = newSpool;
 208     _spoolTail = newSpool;
 209   }
 210   return true;
 211 }
 212 
 213 // Get a free spool buffer from the free pool, getting a new block
 214 // from the heap if necessary.
 215 SpoolBlock* PromotionInfo::getSpoolBlock() {
 216   SpoolBlock* res;
 217   if ((res = _spareSpool) != NULL) {
 218     _spareSpool = _spareSpool->nextSpoolBlock;
 219     res->nextSpoolBlock = NULL;
 220   } else {  // spare spool exhausted, get some from heap
 221     res = (SpoolBlock*)(space()->allocateScratch(refillSize()));
 222     if (res != NULL) {
 223       res->init();
 224     }
 225   }
 226   assert(res == NULL || res->nextSpoolBlock == NULL, "postcondition");
 227   return res;
 228 }
 229 
 230 void PromotionInfo::startTrackingPromotions() {
 231   assert(_spoolHead == _spoolTail && _firstIndex == _nextIndex,
 232          "spooling inconsistency?");
 233   _firstIndex = _nextIndex = 1;
 234   _tracking = true;
 235 }
 236 
 237 #define CMSPrintPromoBlockInfo 1
 238 
 239 void PromotionInfo::stopTrackingPromotions(uint worker_id) {
 240   assert(_spoolHead == _spoolTail && _firstIndex == _nextIndex,
 241          "spooling inconsistency?");
 242   _firstIndex = _nextIndex = 1;
 243   _tracking = false;
 244   if (CMSPrintPromoBlockInfo > 1) {
 245     print_statistics(worker_id);
 246   }
 247 }
 248 
 249 void PromotionInfo::print_statistics(uint worker_id) const {
 250   assert(_spoolHead == _spoolTail && _firstIndex == _nextIndex,
 251          "Else will undercount");
 252   assert(CMSPrintPromoBlockInfo > 0, "Else unnecessary call");
 253   // Count the number of blocks and slots in the free pool
 254   size_t slots  = 0;
 255   size_t blocks = 0;
 256   for (SpoolBlock* cur_spool = _spareSpool;
 257        cur_spool != NULL;
 258        cur_spool = cur_spool->nextSpoolBlock) {
 259     // the first entry is just a self-pointer; indices 1 through
 260     // bufferSize - 1 are occupied (thus, bufferSize - 1 slots).
 261     assert((void*)cur_spool->displacedHdr == (void*)&cur_spool->displacedHdr,
 262            "first entry of displacedHdr should be self-referential");
 263     slots += cur_spool->bufferSize - 1;
 264     blocks++;
 265   }
 266   if (_spoolHead != NULL) {
 267     slots += _spoolHead->bufferSize - 1;
 268     blocks++;
 269   }
 270   gclog_or_tty->print_cr(" [worker %d] promo_blocks = " SIZE_FORMAT ", promo_slots = " SIZE_FORMAT,
 271                          worker_id, blocks, slots);
 272 }
 273 
 274 // When _spoolTail is not NULL, then the slot <_spoolTail, _nextIndex>
 275 // points to the next slot available for filling.
 276 // The set of slots holding displaced headers are then all those in the
 277 // right-open interval denoted by:
 278 //
 279 //    [ <_spoolHead, _firstIndex>, <_spoolTail, _nextIndex> )
 280 //
 281 // When _spoolTail is NULL, then the set of slots with displaced headers
 282 // is all those starting at the slot <_spoolHead, _firstIndex> and
 283 // going up to the last slot of last block in the linked list.
 284 // In this latter case, _splice_point points to the tail block of
 285 // this linked list of blocks holding displaced headers.
 286 void PromotionInfo::verify() const {
 287   // Verify the following:
 288   // 1. the number of displaced headers matches the number of promoted
 289   //    objects that have displaced headers
 290   // 2. each promoted object lies in this space
 291   debug_only(
 292     PromotedObject* junk = NULL;
 293     assert(junk->next_addr() == (void*)(oop(junk)->mark_addr()),
 294            "Offset of PromotedObject::_next is expected to align with "
 295            "  the OopDesc::_mark within OopDesc");
 296   )
 297   // FIXME: guarantee????
 298   guarantee(_spoolHead == NULL || _spoolTail != NULL ||
 299             _splice_point != NULL, "list consistency");
 300   guarantee(_promoHead == NULL || _promoTail != NULL, "list consistency");
 301   // count the number of objects with displaced headers
 302   size_t numObjsWithDisplacedHdrs = 0;
 303   for (PromotedObject* curObj = _promoHead; curObj != NULL; curObj = curObj->next()) {
 304     guarantee(space()->is_in_reserved((HeapWord*)curObj), "Containment");
 305     // the last promoted object may fail the mark() != NULL test of is_oop().
 306     guarantee(curObj->next() == NULL || oop(curObj)->is_oop(), "must be an oop");
 307     if (curObj->hasDisplacedMark()) {
 308       numObjsWithDisplacedHdrs++;
 309     }
 310   }
 311   // Count the number of displaced headers
 312   size_t numDisplacedHdrs = 0;
 313   for (SpoolBlock* curSpool = _spoolHead;
 314        curSpool != _spoolTail && curSpool != NULL;
 315        curSpool = curSpool->nextSpoolBlock) {
 316     // the first entry is just a self-pointer; indices 1 through
 317     // bufferSize - 1 are occupied (thus, bufferSize - 1 slots).
 318     guarantee((void*)curSpool->displacedHdr == (void*)&curSpool->displacedHdr,
 319               "first entry of displacedHdr should be self-referential");
 320     numDisplacedHdrs += curSpool->bufferSize - 1;
 321   }
 322   guarantee((_spoolHead == _spoolTail) == (numDisplacedHdrs == 0),
 323             "internal consistency");
 324   guarantee(_spoolTail != NULL || _nextIndex == 1,
 325             "Inconsistency between _spoolTail and _nextIndex");
 326   // We overcounted (_firstIndex-1) worth of slots in block
 327   // _spoolHead and we undercounted (_nextIndex-1) worth of
 328   // slots in block _spoolTail. We make an appropriate
 329   // adjustment by subtracting the first and adding the
 330   // second:  - (_firstIndex - 1) + (_nextIndex - 1)
 331   numDisplacedHdrs += (_nextIndex - _firstIndex);
 332   guarantee(numDisplacedHdrs == numObjsWithDisplacedHdrs, "Displaced hdr count");
 333 }
 334 
 335 void PromotionInfo::print_on(outputStream* st) const {
 336   SpoolBlock* curSpool = NULL;
 337   size_t i = 0;
 338   st->print_cr(" start & end indices: [" SIZE_FORMAT ", " SIZE_FORMAT ")",
 339                _firstIndex, _nextIndex);
 340   for (curSpool = _spoolHead; curSpool != _spoolTail && curSpool != NULL;
 341        curSpool = curSpool->nextSpoolBlock) {
 342     curSpool->print_on(st);
 343     st->print_cr(" active ");
 344     i++;
 345   }
 346   for (curSpool = _spoolTail; curSpool != NULL;
 347        curSpool = curSpool->nextSpoolBlock) {
 348     curSpool->print_on(st);
 349     st->print_cr(" inactive ");
 350     i++;
 351   }
 352   for (curSpool = _spareSpool; curSpool != NULL;
 353        curSpool = curSpool->nextSpoolBlock) {
 354     curSpool->print_on(st);
 355     st->print_cr(" free ");
 356     i++;
 357   }
 358   st->print_cr("  " SIZE_FORMAT " header spooling blocks", i);
 359 }
 360 
 361 void SpoolBlock::print_on(outputStream* st) const {
 362   st->print("[" PTR_FORMAT "," PTR_FORMAT "), " SIZE_FORMAT " HeapWords -> " PTR_FORMAT,
 363             this, (HeapWord*)displacedHdr + bufferSize,
 364             bufferSize, nextSpoolBlock);
 365 }