src/share/vm/gc_implementation/g1/g1RemSet.cpp

Mon, 27 Apr 2009 16:52:18 -0700

author
iveresov
date
Mon, 27 Apr 2009 16:52:18 -0700
changeset 1182
b803b1b9e206
parent 1112
96b229c54d1e
child 1186
20c6f43950b5
permissions
-rw-r--r--

6819098: G1: reduce RSet scanning times
Summary: Added a feedback-driven exponential skipping for parallel RSet scanning.
Reviewed-by: tonyp, apetrusenko

     1 /*
     2  * Copyright 2001-2009 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    20  * CA 95054 USA or visit www.sun.com if you need additional information or
    21  * have any questions.
    22  *
    23  */
    25 #include "incls/_precompiled.incl"
    26 #include "incls/_g1RemSet.cpp.incl"
    28 #define CARD_REPEAT_HISTO 0
    30 #if CARD_REPEAT_HISTO
    31 static size_t ct_freq_sz;
    32 static jbyte* ct_freq = NULL;
    34 void init_ct_freq_table(size_t heap_sz_bytes) {
    35   if (ct_freq == NULL) {
    36     ct_freq_sz = heap_sz_bytes/CardTableModRefBS::card_size;
    37     ct_freq = new jbyte[ct_freq_sz];
    38     for (size_t j = 0; j < ct_freq_sz; j++) ct_freq[j] = 0;
    39   }
    40 }
    42 void ct_freq_note_card(size_t index) {
    43   assert(0 <= index && index < ct_freq_sz, "Bounds error.");
    44   if (ct_freq[index] < 100) { ct_freq[index]++; }
    45 }
    47 static IntHistogram card_repeat_count(10, 10);
    49 void ct_freq_update_histo_and_reset() {
    50   for (size_t j = 0; j < ct_freq_sz; j++) {
    51     card_repeat_count.add_entry(ct_freq[j]);
    52     ct_freq[j] = 0;
    53   }
    55 }
    56 #endif
    59 class IntoCSOopClosure: public OopsInHeapRegionClosure {
    60   OopsInHeapRegionClosure* _blk;
    61   G1CollectedHeap* _g1;
    62 public:
    63   IntoCSOopClosure(G1CollectedHeap* g1, OopsInHeapRegionClosure* blk) :
    64     _g1(g1), _blk(blk) {}
    65   void set_region(HeapRegion* from) {
    66     _blk->set_region(from);
    67   }
    68   virtual void do_oop(narrowOop* p) {
    69     guarantee(false, "NYI");
    70   }
    71   virtual void do_oop(oop* p) {
    72     oop obj = *p;
    73     if (_g1->obj_in_cs(obj)) _blk->do_oop(p);
    74   }
    75   bool apply_to_weak_ref_discovered_field() { return true; }
    76   bool idempotent() { return true; }
    77 };
    79 class IntoCSRegionClosure: public HeapRegionClosure {
    80   IntoCSOopClosure _blk;
    81   G1CollectedHeap* _g1;
    82 public:
    83   IntoCSRegionClosure(G1CollectedHeap* g1, OopsInHeapRegionClosure* blk) :
    84     _g1(g1), _blk(g1, blk) {}
    85   bool doHeapRegion(HeapRegion* r) {
    86     if (!r->in_collection_set()) {
    87       _blk.set_region(r);
    88       if (r->isHumongous()) {
    89         if (r->startsHumongous()) {
    90           oop obj = oop(r->bottom());
    91           obj->oop_iterate(&_blk);
    92         }
    93       } else {
    94         r->oop_before_save_marks_iterate(&_blk);
    95       }
    96     }
    97     return false;
    98   }
    99 };
   101 void
   102 StupidG1RemSet::oops_into_collection_set_do(OopsInHeapRegionClosure* oc,
   103                                             int worker_i) {
   104   IntoCSRegionClosure rc(_g1, oc);
   105   _g1->heap_region_iterate(&rc);
   106 }
   108 class UpdateRSOutOfRegionClosure: public HeapRegionClosure {
   109   G1CollectedHeap*    _g1h;
   110   ModRefBarrierSet*   _mr_bs;
   111   UpdateRSOopClosure  _cl;
   112   int _worker_i;
   113 public:
   114   UpdateRSOutOfRegionClosure(G1CollectedHeap* g1, int worker_i = 0) :
   115     _cl(g1->g1_rem_set()->as_HRInto_G1RemSet(), worker_i),
   116     _mr_bs(g1->mr_bs()),
   117     _worker_i(worker_i),
   118     _g1h(g1)
   119     {}
   120   bool doHeapRegion(HeapRegion* r) {
   121     if (!r->in_collection_set() && !r->continuesHumongous()) {
   122       _cl.set_from(r);
   123       r->set_next_filter_kind(HeapRegionDCTOC::OutOfRegionFilterKind);
   124       _mr_bs->mod_oop_in_space_iterate(r, &_cl, true, true);
   125     }
   126     return false;
   127   }
   128 };
   130 class VerifyRSCleanCardOopClosure: public OopClosure {
   131   G1CollectedHeap* _g1;
   132 public:
   133   VerifyRSCleanCardOopClosure(G1CollectedHeap* g1) : _g1(g1) {}
   135   virtual void do_oop(narrowOop* p) {
   136     guarantee(false, "NYI");
   137   }
   138   virtual void do_oop(oop* p) {
   139     oop obj = *p;
   140     HeapRegion* to = _g1->heap_region_containing(obj);
   141     guarantee(to == NULL || !to->in_collection_set(),
   142               "Missed a rem set member.");
   143   }
   144 };
   146 HRInto_G1RemSet::HRInto_G1RemSet(G1CollectedHeap* g1, CardTableModRefBS* ct_bs)
   147   : G1RemSet(g1), _ct_bs(ct_bs), _g1p(_g1->g1_policy()),
   148     _cg1r(g1->concurrent_g1_refine()),
   149     _par_traversal_in_progress(false), _new_refs(NULL),
   150     _cards_scanned(NULL), _total_cards_scanned(0)
   151 {
   152   _seq_task = new SubTasksDone(NumSeqTasks);
   153   guarantee(n_workers() > 0, "There should be some workers");
   154   _new_refs = NEW_C_HEAP_ARRAY(GrowableArray<oop*>*, n_workers());
   155   for (uint i = 0; i < n_workers(); i++) {
   156     _new_refs[i] = new (ResourceObj::C_HEAP) GrowableArray<oop*>(8192,true);
   157   }
   158 }
   160 HRInto_G1RemSet::~HRInto_G1RemSet() {
   161   delete _seq_task;
   162   for (uint i = 0; i < n_workers(); i++) {
   163     delete _new_refs[i];
   164   }
   165   FREE_C_HEAP_ARRAY(GrowableArray<oop*>*, _new_refs);
   166 }
   168 void CountNonCleanMemRegionClosure::do_MemRegion(MemRegion mr) {
   169   if (_g1->is_in_g1_reserved(mr.start())) {
   170     _n += (int) ((mr.byte_size() / CardTableModRefBS::card_size));
   171     if (_start_first == NULL) _start_first = mr.start();
   172   }
   173 }
   175 class ScanRSClosure : public HeapRegionClosure {
   176   size_t _cards_done, _cards;
   177   G1CollectedHeap* _g1h;
   178   OopsInHeapRegionClosure* _oc;
   179   G1BlockOffsetSharedArray* _bot_shared;
   180   CardTableModRefBS *_ct_bs;
   181   int _worker_i;
   182   bool _try_claimed;
   183   size_t _min_skip_distance, _max_skip_distance;
   184 public:
   185   ScanRSClosure(OopsInHeapRegionClosure* oc, int worker_i) :
   186     _oc(oc),
   187     _cards(0),
   188     _cards_done(0),
   189     _worker_i(worker_i),
   190     _try_claimed(false)
   191   {
   192     _g1h = G1CollectedHeap::heap();
   193     _bot_shared = _g1h->bot_shared();
   194     _ct_bs = (CardTableModRefBS*) (_g1h->barrier_set());
   195     _min_skip_distance = 16;
   196     _max_skip_distance = 2 * _g1h->n_par_threads() * _min_skip_distance;
   197   }
   199   void set_try_claimed() { _try_claimed = true; }
   201   void scanCard(size_t index, HeapRegion *r) {
   202     _cards_done++;
   203     DirtyCardToOopClosure* cl =
   204       r->new_dcto_closure(_oc,
   205                          CardTableModRefBS::Precise,
   206                          HeapRegionDCTOC::IntoCSFilterKind);
   208     // Set the "from" region in the closure.
   209     _oc->set_region(r);
   210     HeapWord* card_start = _bot_shared->address_for_index(index);
   211     HeapWord* card_end = card_start + G1BlockOffsetSharedArray::N_words;
   212     Space *sp = SharedHeap::heap()->space_containing(card_start);
   213     MemRegion sm_region;
   214     if (ParallelGCThreads > 0) {
   215       // first find the used area
   216       sm_region = sp->used_region_at_save_marks();
   217     } else {
   218       // The closure is not idempotent.  We shouldn't look at objects
   219       // allocated during the GC.
   220       sm_region = sp->used_region_at_save_marks();
   221     }
   222     MemRegion mr = sm_region.intersection(MemRegion(card_start,card_end));
   223     if (!mr.is_empty()) {
   224       cl->do_MemRegion(mr);
   225     }
   226   }
   228   void printCard(HeapRegion* card_region, size_t card_index,
   229                  HeapWord* card_start) {
   230     gclog_or_tty->print_cr("T %d Region [" PTR_FORMAT ", " PTR_FORMAT ") "
   231                            "RS names card %p: "
   232                            "[" PTR_FORMAT ", " PTR_FORMAT ")",
   233                            _worker_i,
   234                            card_region->bottom(), card_region->end(),
   235                            card_index,
   236                            card_start, card_start + G1BlockOffsetSharedArray::N_words);
   237   }
   239   bool doHeapRegion(HeapRegion* r) {
   240     assert(r->in_collection_set(), "should only be called on elements of CS.");
   241     HeapRegionRemSet* hrrs = r->rem_set();
   242     if (hrrs->iter_is_complete()) return false; // All done.
   243     if (!_try_claimed && !hrrs->claim_iter()) return false;
   244     // If we didn't return above, then
   245     //   _try_claimed || r->claim_iter()
   246     // is true: either we're supposed to work on claimed-but-not-complete
   247     // regions, or we successfully claimed the region.
   248     HeapRegionRemSetIterator* iter = _g1h->rem_set_iterator(_worker_i);
   249     hrrs->init_iterator(iter);
   250     size_t card_index;
   251     size_t skip_distance = 0, current_card = 0, jump_to_card = 0;
   252     while (iter->has_next(card_index)) {
   253       if (current_card < jump_to_card) {
   254         ++current_card;
   255         continue;
   256       }
   257       HeapWord* card_start = _g1h->bot_shared()->address_for_index(card_index);
   258 #if 0
   259       gclog_or_tty->print("Rem set iteration yielded card [" PTR_FORMAT ", " PTR_FORMAT ").\n",
   260                           card_start, card_start + CardTableModRefBS::card_size_in_words);
   261 #endif
   263       HeapRegion* card_region = _g1h->heap_region_containing(card_start);
   264       assert(card_region != NULL, "Yielding cards not in the heap?");
   265       _cards++;
   267        // If the card is dirty, then we will scan it during updateRS.
   268       if (!card_region->in_collection_set() && !_ct_bs->is_card_dirty(card_index)) {
   269           if (!_ct_bs->is_card_claimed(card_index) && _ct_bs->claim_card(card_index)) {
   270             scanCard(card_index, card_region);
   271           } else if (_try_claimed) {
   272             if (jump_to_card == 0 || jump_to_card != current_card) {
   273               // We did some useful work in the previous iteration.
   274               // Decrease the distance.
   275               skip_distance = MAX2(skip_distance >> 1, _min_skip_distance);
   276             } else {
   277               // Previous iteration resulted in a claim failure.
   278               // Increase the distance.
   279               skip_distance = MIN2(skip_distance << 1, _max_skip_distance);
   280             }
   281             jump_to_card = current_card + skip_distance;
   282           }
   283       }
   284       ++current_card;
   285     }
   286     if (!_try_claimed) {
   287       hrrs->set_iter_complete();
   288     }
   289     return false;
   290   }
   291   // Set all cards back to clean.
   292   void cleanup() {_g1h->cleanUpCardTable();}
   293   size_t cards_done() { return _cards_done;}
   294   size_t cards_looked_up() { return _cards;}
   295 };
   297 // We want the parallel threads to start their scanning at
   298 // different collection set regions to avoid contention.
   299 // If we have:
   300 //          n collection set regions
   301 //          p threads
   302 // Then thread t will start at region t * floor (n/p)
   304 HeapRegion* HRInto_G1RemSet::calculateStartRegion(int worker_i) {
   305   HeapRegion* result = _g1p->collection_set();
   306   if (ParallelGCThreads > 0) {
   307     size_t cs_size = _g1p->collection_set_size();
   308     int n_workers = _g1->workers()->total_workers();
   309     size_t cs_spans = cs_size / n_workers;
   310     size_t ind      = cs_spans * worker_i;
   311     for (size_t i = 0; i < ind; i++)
   312       result = result->next_in_collection_set();
   313   }
   314   return result;
   315 }
   317 void HRInto_G1RemSet::scanRS(OopsInHeapRegionClosure* oc, int worker_i) {
   318   double rs_time_start = os::elapsedTime();
   319   HeapRegion *startRegion = calculateStartRegion(worker_i);
   321   BufferingOopsInHeapRegionClosure boc(oc);
   322   ScanRSClosure scanRScl(&boc, worker_i);
   323   _g1->collection_set_iterate_from(startRegion, &scanRScl);
   324   scanRScl.set_try_claimed();
   325   _g1->collection_set_iterate_from(startRegion, &scanRScl);
   327   boc.done();
   328   double closure_app_time_sec = boc.closure_app_seconds();
   329   double scan_rs_time_sec = (os::elapsedTime() - rs_time_start) -
   330     closure_app_time_sec;
   331   double closure_app_time_ms = closure_app_time_sec * 1000.0;
   333   assert( _cards_scanned != NULL, "invariant" );
   334   _cards_scanned[worker_i] = scanRScl.cards_done();
   336   _g1p->record_scan_rs_start_time(worker_i, rs_time_start * 1000.0);
   337   _g1p->record_scan_rs_time(worker_i, scan_rs_time_sec * 1000.0);
   339   double scan_new_refs_time_ms = _g1p->get_scan_new_refs_time(worker_i);
   340   if (scan_new_refs_time_ms > 0.0) {
   341     closure_app_time_ms += scan_new_refs_time_ms;
   342   }
   344   _g1p->record_obj_copy_time(worker_i, closure_app_time_ms);
   345 }
   347 void HRInto_G1RemSet::updateRS(int worker_i) {
   348   ConcurrentG1Refine* cg1r = _g1->concurrent_g1_refine();
   350   double start = os::elapsedTime();
   351   _g1p->record_update_rs_start_time(worker_i, start * 1000.0);
   353   if (G1RSBarrierUseQueue && !cg1r->do_traversal()) {
   354     // Apply the appropriate closure to all remaining log entries.
   355     _g1->iterate_dirty_card_closure(false, worker_i);
   356     // Now there should be no dirty cards.
   357     if (G1RSLogCheckCardTable) {
   358       CountNonCleanMemRegionClosure cl(_g1);
   359       _ct_bs->mod_card_iterate(&cl);
   360       // XXX This isn't true any more: keeping cards of young regions
   361       // marked dirty broke it.  Need some reasonable fix.
   362       guarantee(cl.n() == 0, "Card table should be clean.");
   363     }
   364   } else {
   365     UpdateRSOutOfRegionClosure update_rs(_g1, worker_i);
   366     _g1->heap_region_iterate(&update_rs);
   367     // We did a traversal; no further one is necessary.
   368     if (G1RSBarrierUseQueue) {
   369       assert(cg1r->do_traversal(), "Or we shouldn't have gotten here.");
   370       cg1r->set_pya_cancel();
   371     }
   372     if (_cg1r->use_cache()) {
   373       _cg1r->clear_and_record_card_counts();
   374       _cg1r->clear_hot_cache();
   375     }
   376   }
   377   _g1p->record_update_rs_time(worker_i, (os::elapsedTime() - start) * 1000.0);
   378 }
   380 #ifndef PRODUCT
   381 class PrintRSClosure : public HeapRegionClosure {
   382   int _count;
   383 public:
   384   PrintRSClosure() : _count(0) {}
   385   bool doHeapRegion(HeapRegion* r) {
   386     HeapRegionRemSet* hrrs = r->rem_set();
   387     _count += (int) hrrs->occupied();
   388     if (hrrs->occupied() == 0) {
   389       gclog_or_tty->print("Heap Region [" PTR_FORMAT ", " PTR_FORMAT ") "
   390                           "has no remset entries\n",
   391                           r->bottom(), r->end());
   392     } else {
   393       gclog_or_tty->print("Printing rem set for heap region [" PTR_FORMAT ", " PTR_FORMAT ")\n",
   394                           r->bottom(), r->end());
   395       r->print();
   396       hrrs->print();
   397       gclog_or_tty->print("\nDone printing rem set\n");
   398     }
   399     return false;
   400   }
   401   int occupied() {return _count;}
   402 };
   403 #endif
   405 class CountRSSizeClosure: public HeapRegionClosure {
   406   size_t _n;
   407   size_t _tot;
   408   size_t _max;
   409   HeapRegion* _max_r;
   410   enum {
   411     N = 20,
   412     MIN = 6
   413   };
   414   int _histo[N];
   415 public:
   416   CountRSSizeClosure() : _n(0), _tot(0), _max(0), _max_r(NULL) {
   417     for (int i = 0; i < N; i++) _histo[i] = 0;
   418   }
   419   bool doHeapRegion(HeapRegion* r) {
   420     if (!r->continuesHumongous()) {
   421       size_t occ = r->rem_set()->occupied();
   422       _n++;
   423       _tot += occ;
   424       if (occ > _max) {
   425         _max = occ;
   426         _max_r = r;
   427       }
   428       // Fit it into a histo bin.
   429       int s = 1 << MIN;
   430       int i = 0;
   431       while (occ > (size_t) s && i < (N-1)) {
   432         s = s << 1;
   433         i++;
   434       }
   435       _histo[i]++;
   436     }
   437     return false;
   438   }
   439   size_t n() { return _n; }
   440   size_t tot() { return _tot; }
   441   size_t mx() { return _max; }
   442   HeapRegion* mxr() { return _max_r; }
   443   void print_histo() {
   444     int mx = N;
   445     while (mx >= 0) {
   446       if (_histo[mx-1] > 0) break;
   447       mx--;
   448     }
   449     gclog_or_tty->print_cr("Number of regions with given RS sizes:");
   450     gclog_or_tty->print_cr("           <= %8d   %8d", 1 << MIN, _histo[0]);
   451     for (int i = 1; i < mx-1; i++) {
   452       gclog_or_tty->print_cr("  %8d  - %8d   %8d",
   453                     (1 << (MIN + i - 1)) + 1,
   454                     1 << (MIN + i),
   455                     _histo[i]);
   456     }
   457     gclog_or_tty->print_cr("            > %8d   %8d", (1 << (MIN+mx-2))+1, _histo[mx-1]);
   458   }
   459 };
   461 void
   462 HRInto_G1RemSet::scanNewRefsRS(OopsInHeapRegionClosure* oc,
   463                                              int worker_i) {
   464   double scan_new_refs_start_sec = os::elapsedTime();
   465   G1CollectedHeap* g1h = G1CollectedHeap::heap();
   466   CardTableModRefBS* ct_bs = (CardTableModRefBS*) (g1h->barrier_set());
   467   for (int i = 0; i < _new_refs[worker_i]->length(); i++) {
   468     oop* p = _new_refs[worker_i]->at(i);
   469     oop obj = *p;
   470     // *p was in the collection set when p was pushed on "_new_refs", but
   471     // another thread may have processed this location from an RS, so it
   472     // might not point into the CS any longer.  If so, it's obviously been
   473     // processed, and we don't need to do anything further.
   474     if (g1h->obj_in_cs(obj)) {
   475       HeapRegion* r = g1h->heap_region_containing(p);
   477       DEBUG_ONLY(HeapRegion* to = g1h->heap_region_containing(obj));
   478       oc->set_region(r);
   479       // If "p" has already been processed concurrently, this is
   480       // idempotent.
   481       oc->do_oop(p);
   482     }
   483   }
   484   _g1p->record_scan_new_refs_time(worker_i,
   485                                   (os::elapsedTime() - scan_new_refs_start_sec)
   486                                   * 1000.0);
   487 }
   489 void HRInto_G1RemSet::set_par_traversal(bool b) {
   490   _par_traversal_in_progress = b;
   491   HeapRegionRemSet::set_par_traversal(b);
   492 }
   494 void HRInto_G1RemSet::cleanupHRRS() {
   495   HeapRegionRemSet::cleanup();
   496 }
   498 void
   499 HRInto_G1RemSet::oops_into_collection_set_do(OopsInHeapRegionClosure* oc,
   500                                              int worker_i) {
   501 #if CARD_REPEAT_HISTO
   502   ct_freq_update_histo_and_reset();
   503 #endif
   504   if (worker_i == 0) {
   505     _cg1r->clear_and_record_card_counts();
   506   }
   508   // Make this into a command-line flag...
   509   if (G1RSCountHisto && (ParallelGCThreads == 0 || worker_i == 0)) {
   510     CountRSSizeClosure count_cl;
   511     _g1->heap_region_iterate(&count_cl);
   512     gclog_or_tty->print_cr("Avg of %d RS counts is %f, max is %d, "
   513                   "max region is " PTR_FORMAT,
   514                   count_cl.n(), (float)count_cl.tot()/(float)count_cl.n(),
   515                   count_cl.mx(), count_cl.mxr());
   516     count_cl.print_histo();
   517   }
   519   if (ParallelGCThreads > 0) {
   520     // The two flags below were introduced temporarily to serialize
   521     // the updating and scanning of remembered sets. There are some
   522     // race conditions when these two operations are done in parallel
   523     // and they are causing failures. When we resolve said race
   524     // conditions, we'll revert back to parallel remembered set
   525     // updating and scanning. See CRs 6677707 and 6677708.
   526     if (G1EnableParallelRSetUpdating || (worker_i == 0)) {
   527       updateRS(worker_i);
   528       scanNewRefsRS(oc, worker_i);
   529     } else {
   530       _g1p->record_update_rs_start_time(worker_i, os::elapsedTime());
   531       _g1p->record_update_rs_processed_buffers(worker_i, 0.0);
   532       _g1p->record_update_rs_time(worker_i, 0.0);
   533       _g1p->record_scan_new_refs_time(worker_i, 0.0);
   534     }
   535     if (G1EnableParallelRSetScanning || (worker_i == 0)) {
   536       scanRS(oc, worker_i);
   537     } else {
   538       _g1p->record_scan_rs_start_time(worker_i, os::elapsedTime());
   539       _g1p->record_scan_rs_time(worker_i, 0.0);
   540     }
   541   } else {
   542     assert(worker_i == 0, "invariant");
   543     updateRS(0);
   544     scanNewRefsRS(oc, 0);
   545     scanRS(oc, 0);
   546   }
   547 }
   549 void HRInto_G1RemSet::
   550 prepare_for_oops_into_collection_set_do() {
   551 #if G1_REM_SET_LOGGING
   552   PrintRSClosure cl;
   553   _g1->collection_set_iterate(&cl);
   554 #endif
   555   cleanupHRRS();
   556   ConcurrentG1Refine* cg1r = _g1->concurrent_g1_refine();
   557   _g1->set_refine_cte_cl_concurrency(false);
   558   DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
   559   dcqs.concatenate_logs();
   561   assert(!_par_traversal_in_progress, "Invariant between iterations.");
   562   if (ParallelGCThreads > 0) {
   563     set_par_traversal(true);
   564     _seq_task->set_par_threads((int)n_workers());
   565     if (cg1r->do_traversal()) {
   566       updateRS(0);
   567       // Have to do this again after updaters
   568       cleanupHRRS();
   569     }
   570   }
   571   guarantee( _cards_scanned == NULL, "invariant" );
   572   _cards_scanned = NEW_C_HEAP_ARRAY(size_t, n_workers());
   573   for (uint i = 0; i < n_workers(); ++i) {
   574     _cards_scanned[i] = 0;
   575   }
   576   _total_cards_scanned = 0;
   577 }
   580 class cleanUpIteratorsClosure : public HeapRegionClosure {
   581   bool doHeapRegion(HeapRegion *r) {
   582     HeapRegionRemSet* hrrs = r->rem_set();
   583     hrrs->init_for_par_iteration();
   584     return false;
   585   }
   586 };
   588 class UpdateRSetOopsIntoCSImmediate : public OopClosure {
   589   G1CollectedHeap* _g1;
   590 public:
   591   UpdateRSetOopsIntoCSImmediate(G1CollectedHeap* g1) : _g1(g1) { }
   592   virtual void do_oop(narrowOop* p) {
   593     guarantee(false, "NYI");
   594   }
   595   virtual void do_oop(oop* p) {
   596     HeapRegion* to = _g1->heap_region_containing(*p);
   597     if (to->in_collection_set()) {
   598       to->rem_set()->add_reference(p, 0);
   599     }
   600   }
   601 };
   603 class UpdateRSetOopsIntoCSDeferred : public OopClosure {
   604   G1CollectedHeap* _g1;
   605   CardTableModRefBS* _ct_bs;
   606   DirtyCardQueue* _dcq;
   607 public:
   608   UpdateRSetOopsIntoCSDeferred(G1CollectedHeap* g1, DirtyCardQueue* dcq) :
   609     _g1(g1), _ct_bs((CardTableModRefBS*)_g1->barrier_set()), _dcq(dcq) { }
   610   virtual void do_oop(narrowOop* p) {
   611     guarantee(false, "NYI");
   612   }
   613   virtual void do_oop(oop* p) {
   614     oop obj = *p;
   615     if (_g1->obj_in_cs(obj)) {
   616       size_t card_index = _ct_bs->index_for(p);
   617       if (_ct_bs->mark_card_deferred(card_index)) {
   618         _dcq->enqueue((jbyte*)_ct_bs->byte_for_index(card_index));
   619       }
   620     }
   621   }
   622 };
   624 void HRInto_G1RemSet::new_refs_iterate(OopClosure* cl) {
   625   for (size_t i = 0; i < n_workers(); i++) {
   626     for (int j = 0; j < _new_refs[i]->length(); j++) {
   627       oop* p = _new_refs[i]->at(j);
   628       cl->do_oop(p);
   629     }
   630   }
   631 }
   633 void HRInto_G1RemSet::cleanup_after_oops_into_collection_set_do() {
   634   guarantee( _cards_scanned != NULL, "invariant" );
   635   _total_cards_scanned = 0;
   636   for (uint i = 0; i < n_workers(); ++i)
   637     _total_cards_scanned += _cards_scanned[i];
   638   FREE_C_HEAP_ARRAY(size_t, _cards_scanned);
   639   _cards_scanned = NULL;
   640   // Cleanup after copy
   641 #if G1_REM_SET_LOGGING
   642   PrintRSClosure cl;
   643   _g1->heap_region_iterate(&cl);
   644 #endif
   645   _g1->set_refine_cte_cl_concurrency(true);
   646   cleanUpIteratorsClosure iterClosure;
   647   _g1->collection_set_iterate(&iterClosure);
   648   // Set all cards back to clean.
   649   _g1->cleanUpCardTable();
   650   if (ParallelGCThreads > 0) {
   651     ConcurrentG1Refine* cg1r = _g1->concurrent_g1_refine();
   652     if (cg1r->do_traversal()) {
   653       cg1r->cg1rThread()->set_do_traversal(false);
   654     }
   655     set_par_traversal(false);
   656   }
   658   if (_g1->evacuation_failed()) {
   659     // Restore remembered sets for the regions pointing into
   660     // the collection set.
   661     if (G1DeferredRSUpdate) {
   662       DirtyCardQueue dcq(&_g1->dirty_card_queue_set());
   663       UpdateRSetOopsIntoCSDeferred deferred_update(_g1, &dcq);
   664       new_refs_iterate(&deferred_update);
   665     } else {
   666       UpdateRSetOopsIntoCSImmediate immediate_update(_g1);
   667       new_refs_iterate(&immediate_update);
   668     }
   669   }
   670   for (uint i = 0; i < n_workers(); i++) {
   671     _new_refs[i]->clear();
   672   }
   674   assert(!_par_traversal_in_progress, "Invariant between iterations.");
   675 }
   677 class UpdateRSObjectClosure: public ObjectClosure {
   678   UpdateRSOopClosure* _update_rs_oop_cl;
   679 public:
   680   UpdateRSObjectClosure(UpdateRSOopClosure* update_rs_oop_cl) :
   681     _update_rs_oop_cl(update_rs_oop_cl) {}
   682   void do_object(oop obj) {
   683     obj->oop_iterate(_update_rs_oop_cl);
   684   }
   686 };
   688 class ScrubRSClosure: public HeapRegionClosure {
   689   G1CollectedHeap* _g1h;
   690   BitMap* _region_bm;
   691   BitMap* _card_bm;
   692   CardTableModRefBS* _ctbs;
   693 public:
   694   ScrubRSClosure(BitMap* region_bm, BitMap* card_bm) :
   695     _g1h(G1CollectedHeap::heap()),
   696     _region_bm(region_bm), _card_bm(card_bm),
   697     _ctbs(NULL)
   698   {
   699     ModRefBarrierSet* bs = _g1h->mr_bs();
   700     guarantee(bs->is_a(BarrierSet::CardTableModRef), "Precondition");
   701     _ctbs = (CardTableModRefBS*)bs;
   702   }
   704   bool doHeapRegion(HeapRegion* r) {
   705     if (!r->continuesHumongous()) {
   706       r->rem_set()->scrub(_ctbs, _region_bm, _card_bm);
   707     }
   708     return false;
   709   }
   710 };
   712 void HRInto_G1RemSet::scrub(BitMap* region_bm, BitMap* card_bm) {
   713   ScrubRSClosure scrub_cl(region_bm, card_bm);
   714   _g1->heap_region_iterate(&scrub_cl);
   715 }
   717 void HRInto_G1RemSet::scrub_par(BitMap* region_bm, BitMap* card_bm,
   718                                 int worker_num, int claim_val) {
   719   ScrubRSClosure scrub_cl(region_bm, card_bm);
   720   _g1->heap_region_par_iterate_chunked(&scrub_cl, worker_num, claim_val);
   721 }
   724 class ConcRefineRegionClosure: public HeapRegionClosure {
   725   G1CollectedHeap* _g1h;
   726   CardTableModRefBS* _ctbs;
   727   ConcurrentGCThread* _cgc_thrd;
   728   ConcurrentG1Refine* _cg1r;
   729   unsigned _cards_processed;
   730   UpdateRSOopClosure _update_rs_oop_cl;
   731 public:
   732   ConcRefineRegionClosure(CardTableModRefBS* ctbs,
   733                           ConcurrentG1Refine* cg1r,
   734                           HRInto_G1RemSet* g1rs) :
   735     _ctbs(ctbs), _cg1r(cg1r), _cgc_thrd(cg1r->cg1rThread()),
   736     _update_rs_oop_cl(g1rs), _cards_processed(0),
   737     _g1h(G1CollectedHeap::heap())
   738   {}
   740   bool doHeapRegion(HeapRegion* r) {
   741     if (!r->in_collection_set() &&
   742         !r->continuesHumongous() &&
   743         !r->is_young()) {
   744       _update_rs_oop_cl.set_from(r);
   745       UpdateRSObjectClosure update_rs_obj_cl(&_update_rs_oop_cl);
   747       // For each run of dirty card in the region:
   748       //   1) Clear the cards.
   749       //   2) Process the range corresponding to the run, adding any
   750       //      necessary RS entries.
   751       // 1 must precede 2, so that a concurrent modification redirties the
   752       // card.  If a processing attempt does not succeed, because it runs
   753       // into an unparseable region, we will do binary search to find the
   754       // beginning of the next parseable region.
   755       HeapWord* startAddr = r->bottom();
   756       HeapWord* endAddr = r->used_region().end();
   757       HeapWord* lastAddr;
   758       HeapWord* nextAddr;
   760       for (nextAddr = lastAddr = startAddr;
   761            nextAddr < endAddr;
   762            nextAddr = lastAddr) {
   763         MemRegion dirtyRegion;
   765         // Get and clear dirty region from card table
   766         MemRegion next_mr(nextAddr, endAddr);
   767         dirtyRegion =
   768           _ctbs->dirty_card_range_after_reset(
   769                            next_mr,
   770                            true, CardTableModRefBS::clean_card_val());
   771         assert(dirtyRegion.start() >= nextAddr,
   772                "returned region inconsistent?");
   774         if (!dirtyRegion.is_empty()) {
   775           HeapWord* stop_point =
   776             r->object_iterate_mem_careful(dirtyRegion,
   777                                           &update_rs_obj_cl);
   778           if (stop_point == NULL) {
   779             lastAddr = dirtyRegion.end();
   780             _cards_processed +=
   781               (int) (dirtyRegion.word_size() / CardTableModRefBS::card_size_in_words);
   782           } else {
   783             // We're going to skip one or more cards that we can't parse.
   784             HeapWord* next_parseable_card =
   785               r->next_block_start_careful(stop_point);
   786             // Round this up to a card boundary.
   787             next_parseable_card =
   788               _ctbs->addr_for(_ctbs->byte_after_const(next_parseable_card));
   789             // Now we invalidate the intervening cards so we'll see them
   790             // again.
   791             MemRegion remaining_dirty =
   792               MemRegion(stop_point, dirtyRegion.end());
   793             MemRegion skipped =
   794               MemRegion(stop_point, next_parseable_card);
   795             _ctbs->invalidate(skipped.intersection(remaining_dirty));
   797             // Now start up again where we can parse.
   798             lastAddr = next_parseable_card;
   800             // Count how many we did completely.
   801             _cards_processed +=
   802               (stop_point - dirtyRegion.start()) /
   803               CardTableModRefBS::card_size_in_words;
   804           }
   805           // Allow interruption at regular intervals.
   806           // (Might need to make them more regular, if we get big
   807           // dirty regions.)
   808           if (_cgc_thrd != NULL) {
   809             if (_cgc_thrd->should_yield()) {
   810               _cgc_thrd->yield();
   811               switch (_cg1r->get_pya()) {
   812               case PYA_continue:
   813                 // This may have changed: re-read.
   814                 endAddr = r->used_region().end();
   815                 continue;
   816               case PYA_restart: case PYA_cancel:
   817                 return true;
   818               }
   819             }
   820           }
   821         } else {
   822           break;
   823         }
   824       }
   825     }
   826     // A good yield opportunity.
   827     if (_cgc_thrd != NULL) {
   828       if (_cgc_thrd->should_yield()) {
   829         _cgc_thrd->yield();
   830         switch (_cg1r->get_pya()) {
   831         case PYA_restart: case PYA_cancel:
   832           return true;
   833         default:
   834           break;
   835         }
   837       }
   838     }
   839     return false;
   840   }
   842   unsigned cards_processed() { return _cards_processed; }
   843 };
   846 void HRInto_G1RemSet::concurrentRefinementPass(ConcurrentG1Refine* cg1r) {
   847   ConcRefineRegionClosure cr_cl(ct_bs(), cg1r, this);
   848   _g1->heap_region_iterate(&cr_cl);
   849   _conc_refine_traversals++;
   850   _conc_refine_cards += cr_cl.cards_processed();
   851 }
   853 static IntHistogram out_of_histo(50, 50);
   857 void HRInto_G1RemSet::concurrentRefineOneCard(jbyte* card_ptr, int worker_i) {
   858   // If the card is no longer dirty, nothing to do.
   859   if (*card_ptr != CardTableModRefBS::dirty_card_val()) return;
   861   // Construct the region representing the card.
   862   HeapWord* start = _ct_bs->addr_for(card_ptr);
   863   // And find the region containing it.
   864   HeapRegion* r = _g1->heap_region_containing(start);
   865   if (r == NULL) {
   866     guarantee(_g1->is_in_permanent(start), "Or else where?");
   867     return;  // Not in the G1 heap (might be in perm, for example.)
   868   }
   869   // Why do we have to check here whether a card is on a young region,
   870   // given that we dirty young regions and, as a result, the
   871   // post-barrier is supposed to filter them out and never to enqueue
   872   // them? When we allocate a new region as the "allocation region" we
   873   // actually dirty its cards after we release the lock, since card
   874   // dirtying while holding the lock was a performance bottleneck. So,
   875   // as a result, it is possible for other threads to actually
   876   // allocate objects in the region (after the acquire the lock)
   877   // before all the cards on the region are dirtied. This is unlikely,
   878   // and it doesn't happen often, but it can happen. So, the extra
   879   // check below filters out those cards.
   880   if (r->is_young()) {
   881     return;
   882   }
   883   // While we are processing RSet buffers during the collection, we
   884   // actually don't want to scan any cards on the collection set,
   885   // since we don't want to update remebered sets with entries that
   886   // point into the collection set, given that live objects from the
   887   // collection set are about to move and such entries will be stale
   888   // very soon. This change also deals with a reliability issue which
   889   // involves scanning a card in the collection set and coming across
   890   // an array that was being chunked and looking malformed. Note,
   891   // however, that if evacuation fails, we have to scan any objects
   892   // that were not moved and create any missing entries.
   893   if (r->in_collection_set()) {
   894     return;
   895   }
   897   // Should we defer it?
   898   if (_cg1r->use_cache()) {
   899     card_ptr = _cg1r->cache_insert(card_ptr);
   900     // If it was not an eviction, nothing to do.
   901     if (card_ptr == NULL) return;
   903     // OK, we have to reset the card start, region, etc.
   904     start = _ct_bs->addr_for(card_ptr);
   905     r = _g1->heap_region_containing(start);
   906     if (r == NULL) {
   907       guarantee(_g1->is_in_permanent(start), "Or else where?");
   908       return;  // Not in the G1 heap (might be in perm, for example.)
   909     }
   910     guarantee(!r->is_young(), "It was evicted in the current minor cycle.");
   911   }
   913   HeapWord* end   = _ct_bs->addr_for(card_ptr + 1);
   914   MemRegion dirtyRegion(start, end);
   916 #if CARD_REPEAT_HISTO
   917   init_ct_freq_table(_g1->g1_reserved_obj_bytes());
   918   ct_freq_note_card(_ct_bs->index_for(start));
   919 #endif
   921   UpdateRSOopClosure update_rs_oop_cl(this, worker_i);
   922   update_rs_oop_cl.set_from(r);
   923   FilterOutOfRegionClosure filter_then_update_rs_oop_cl(r, &update_rs_oop_cl);
   925   // Undirty the card.
   926   *card_ptr = CardTableModRefBS::clean_card_val();
   927   // We must complete this write before we do any of the reads below.
   928   OrderAccess::storeload();
   929   // And process it, being careful of unallocated portions of TLAB's.
   930   HeapWord* stop_point =
   931     r->oops_on_card_seq_iterate_careful(dirtyRegion,
   932                                         &filter_then_update_rs_oop_cl);
   933   // If stop_point is non-null, then we encountered an unallocated region
   934   // (perhaps the unfilled portion of a TLAB.)  For now, we'll dirty the
   935   // card and re-enqueue: if we put off the card until a GC pause, then the
   936   // unallocated portion will be filled in.  Alternatively, we might try
   937   // the full complexity of the technique used in "regular" precleaning.
   938   if (stop_point != NULL) {
   939     // The card might have gotten re-dirtied and re-enqueued while we
   940     // worked.  (In fact, it's pretty likely.)
   941     if (*card_ptr != CardTableModRefBS::dirty_card_val()) {
   942       *card_ptr = CardTableModRefBS::dirty_card_val();
   943       MutexLockerEx x(Shared_DirtyCardQ_lock,
   944                       Mutex::_no_safepoint_check_flag);
   945       DirtyCardQueue* sdcq =
   946         JavaThread::dirty_card_queue_set().shared_dirty_card_queue();
   947       sdcq->enqueue(card_ptr);
   948     }
   949   } else {
   950     out_of_histo.add_entry(filter_then_update_rs_oop_cl.out_of_region());
   951     _conc_refine_cards++;
   952   }
   953 }
   955 class HRRSStatsIter: public HeapRegionClosure {
   956   size_t _occupied;
   957   size_t _total_mem_sz;
   958   size_t _max_mem_sz;
   959   HeapRegion* _max_mem_sz_region;
   960 public:
   961   HRRSStatsIter() :
   962     _occupied(0),
   963     _total_mem_sz(0),
   964     _max_mem_sz(0),
   965     _max_mem_sz_region(NULL)
   966   {}
   968   bool doHeapRegion(HeapRegion* r) {
   969     if (r->continuesHumongous()) return false;
   970     size_t mem_sz = r->rem_set()->mem_size();
   971     if (mem_sz > _max_mem_sz) {
   972       _max_mem_sz = mem_sz;
   973       _max_mem_sz_region = r;
   974     }
   975     _total_mem_sz += mem_sz;
   976     size_t occ = r->rem_set()->occupied();
   977     _occupied += occ;
   978     return false;
   979   }
   980   size_t total_mem_sz() { return _total_mem_sz; }
   981   size_t max_mem_sz() { return _max_mem_sz; }
   982   size_t occupied() { return _occupied; }
   983   HeapRegion* max_mem_sz_region() { return _max_mem_sz_region; }
   984 };
   986 void HRInto_G1RemSet::print_summary_info() {
   987   G1CollectedHeap* g1 = G1CollectedHeap::heap();
   988   ConcurrentG1RefineThread* cg1r_thrd =
   989     g1->concurrent_g1_refine()->cg1rThread();
   991 #if CARD_REPEAT_HISTO
   992   gclog_or_tty->print_cr("\nG1 card_repeat count histogram: ");
   993   gclog_or_tty->print_cr("  # of repeats --> # of cards with that number.");
   994   card_repeat_count.print_on(gclog_or_tty);
   995 #endif
   997   if (FILTEROUTOFREGIONCLOSURE_DOHISTOGRAMCOUNT) {
   998     gclog_or_tty->print_cr("\nG1 rem-set out-of-region histogram: ");
   999     gclog_or_tty->print_cr("  # of CS ptrs --> # of cards with that number.");
  1000     out_of_histo.print_on(gclog_or_tty);
  1002   gclog_or_tty->print_cr("\n Concurrent RS processed %d cards in "
  1003                 "%5.2fs.",
  1004                 _conc_refine_cards, cg1r_thrd->vtime_accum());
  1006   DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
  1007   jint tot_processed_buffers =
  1008     dcqs.processed_buffers_mut() + dcqs.processed_buffers_rs_thread();
  1009   gclog_or_tty->print_cr("  Of %d completed buffers:", tot_processed_buffers);
  1010   gclog_or_tty->print_cr("     %8d (%5.1f%%) by conc RS thread.",
  1011                 dcqs.processed_buffers_rs_thread(),
  1012                 100.0*(float)dcqs.processed_buffers_rs_thread()/
  1013                 (float)tot_processed_buffers);
  1014   gclog_or_tty->print_cr("     %8d (%5.1f%%) by mutator threads.",
  1015                 dcqs.processed_buffers_mut(),
  1016                 100.0*(float)dcqs.processed_buffers_mut()/
  1017                 (float)tot_processed_buffers);
  1018   gclog_or_tty->print_cr("   Did %d concurrent refinement traversals.",
  1019                 _conc_refine_traversals);
  1020   if (!G1RSBarrierUseQueue) {
  1021     gclog_or_tty->print_cr("   Scanned %8.2f cards/traversal.",
  1022                   _conc_refine_traversals > 0 ?
  1023                   (float)_conc_refine_cards/(float)_conc_refine_traversals :
  1024                   0);
  1026   gclog_or_tty->print_cr("");
  1027   if (G1UseHRIntoRS) {
  1028     HRRSStatsIter blk;
  1029     g1->heap_region_iterate(&blk);
  1030     gclog_or_tty->print_cr("  Total heap region rem set sizes = " SIZE_FORMAT "K."
  1031                            "  Max = " SIZE_FORMAT "K.",
  1032                            blk.total_mem_sz()/K, blk.max_mem_sz()/K);
  1033     gclog_or_tty->print_cr("  Static structures = " SIZE_FORMAT "K,"
  1034                            " free_lists = " SIZE_FORMAT "K.",
  1035                            HeapRegionRemSet::static_mem_size()/K,
  1036                            HeapRegionRemSet::fl_mem_size()/K);
  1037     gclog_or_tty->print_cr("    %d occupied cards represented.",
  1038                            blk.occupied());
  1039     gclog_or_tty->print_cr("    Max sz region = [" PTR_FORMAT ", " PTR_FORMAT " )"
  1040                            ", cap = " SIZE_FORMAT "K, occ = " SIZE_FORMAT "K.",
  1041                            blk.max_mem_sz_region()->bottom(), blk.max_mem_sz_region()->end(),
  1042                            (blk.max_mem_sz_region()->rem_set()->mem_size() + K - 1)/K,
  1043                            (blk.max_mem_sz_region()->rem_set()->occupied() + K - 1)/K);
  1044     gclog_or_tty->print_cr("    Did %d coarsenings.",
  1045                   HeapRegionRemSet::n_coarsenings());
  1049 void HRInto_G1RemSet::prepare_for_verify() {
  1050   if (G1HRRSFlushLogBuffersOnVerify &&
  1051       (VerifyBeforeGC || VerifyAfterGC)
  1052       &&  !_g1->full_collection()) {
  1053     cleanupHRRS();
  1054     _g1->set_refine_cte_cl_concurrency(false);
  1055     if (SafepointSynchronize::is_at_safepoint()) {
  1056       DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
  1057       dcqs.concatenate_logs();
  1059     bool cg1r_use_cache = _cg1r->use_cache();
  1060     _cg1r->set_use_cache(false);
  1061     updateRS(0);
  1062     _cg1r->set_use_cache(cg1r_use_cache);
  1064     assert(JavaThread::dirty_card_queue_set().completed_buffers_num() == 0, "All should be consumed");

mercurial