1 /*
   2  * Copyright (c) 2001, 2016, 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 #ifndef SHARE_VM_GC_G1_G1CONCURRENTMARK_HPP
  26 #define SHARE_VM_GC_G1_G1CONCURRENTMARK_HPP
  27 
  28 #include "classfile/javaClasses.hpp"
  29 #include "gc/g1/g1RegionToSpaceMapper.hpp"
  30 #include "gc/g1/heapRegionSet.hpp"
  31 #include "gc/shared/taskqueue.hpp"
  32 
  33 class G1CollectedHeap;
  34 class G1CMBitMap;
  35 class G1CMTask;
  36 class G1ConcurrentMark;
  37 class ConcurrentGCTimer;
  38 class G1OldTracer;
  39 class G1SurvivorRegions;
  40 typedef GenericTaskQueue<oop, mtGC>              G1CMTaskQueue;
  41 typedef GenericTaskQueueSet<G1CMTaskQueue, mtGC> G1CMTaskQueueSet;
  42 
  43 // Closure used by CM during concurrent reference discovery
  44 // and reference processing (during remarking) to determine
  45 // if a particular object is alive. It is primarily used
  46 // to determine if referents of discovered reference objects
  47 // are alive. An instance is also embedded into the
  48 // reference processor as the _is_alive_non_header field
  49 class G1CMIsAliveClosure: public BoolObjectClosure {
  50   G1CollectedHeap* _g1;
  51  public:
  52   G1CMIsAliveClosure(G1CollectedHeap* g1) : _g1(g1) { }
  53 
  54   bool do_object_b(oop obj);
  55 };
  56 
  57 // A generic CM bit map.  This is essentially a wrapper around the BitMap
  58 // class, with one bit per (1<<_shifter) HeapWords.
  59 
  60 class G1CMBitMapRO VALUE_OBJ_CLASS_SPEC {
  61  protected:
  62   HeapWord*  _bmStartWord; // base address of range covered by map
  63   size_t     _bmWordSize;  // map size (in #HeapWords covered)
  64   const int  _shifter;     // map to char or bit
  65   BitMapView _bm;          // the bit map itself
  66 
  67  public:
  68   // constructor
  69   G1CMBitMapRO(int shifter);
  70 
  71   // inquiries
  72   HeapWord* startWord()   const { return _bmStartWord; }
  73   // the following is one past the last word in space
  74   HeapWord* endWord()     const { return _bmStartWord + _bmWordSize; }
  75 
  76   // read marks
  77 
  78   bool isMarked(HeapWord* addr) const {
  79     assert(_bmStartWord <= addr && addr < (_bmStartWord + _bmWordSize),
  80            "outside underlying space?");
  81     return _bm.at(heapWordToOffset(addr));
  82   }
  83 
  84   // iteration
  85   inline bool iterate(BitMapClosure* cl, MemRegion mr);
  86 
  87   // Return the address corresponding to the next marked bit at or after
  88   // "addr", and before "limit", if "limit" is non-NULL.  If there is no
  89   // such bit, returns "limit" if that is non-NULL, or else "endWord()".
  90   HeapWord* getNextMarkedWordAddress(const HeapWord* addr,
  91                                      const HeapWord* limit = NULL) const;
  92 
  93   // conversion utilities
  94   HeapWord* offsetToHeapWord(size_t offset) const {
  95     return _bmStartWord + (offset << _shifter);
  96   }
  97   size_t heapWordToOffset(const HeapWord* addr) const {
  98     return pointer_delta(addr, _bmStartWord) >> _shifter;
  99   }
 100 
 101   // The argument addr should be the start address of a valid object
 102   inline HeapWord* nextObject(HeapWord* addr);
 103 
 104   void print_on_error(outputStream* st, const char* prefix) const;
 105 
 106   // debugging
 107   NOT_PRODUCT(bool covers(MemRegion rs) const;)
 108 };
 109 
 110 class G1CMBitMapMappingChangedListener : public G1MappingChangedListener {
 111  private:
 112   G1CMBitMap* _bm;
 113  public:
 114   G1CMBitMapMappingChangedListener() : _bm(NULL) {}
 115 
 116   void set_bitmap(G1CMBitMap* bm) { _bm = bm; }
 117 
 118   virtual void on_commit(uint start_idx, size_t num_regions, bool zero_filled);
 119 };
 120 
 121 class G1CMBitMap : public G1CMBitMapRO {
 122  private:
 123   G1CMBitMapMappingChangedListener _listener;
 124 
 125  public:
 126   static size_t compute_size(size_t heap_size);
 127   // Returns the amount of bytes on the heap between two marks in the bitmap.
 128   static size_t mark_distance();
 129   // Returns how many bytes (or bits) of the heap a single byte (or bit) of the
 130   // mark bitmap corresponds to. This is the same as the mark distance above.
 131   static size_t heap_map_factor() {
 132     return mark_distance();
 133   }
 134 
 135   G1CMBitMap() : G1CMBitMapRO(LogMinObjAlignment), _listener() { _listener.set_bitmap(this); }
 136 
 137   // Initializes the underlying BitMap to cover the given area.
 138   void initialize(MemRegion heap, G1RegionToSpaceMapper* storage);
 139 
 140   // Write marks.
 141   inline void mark(HeapWord* addr);
 142   inline void clear(HeapWord* addr);
 143   inline bool parMark(HeapWord* addr);
 144 
 145   void clear_range(MemRegion mr);
 146 };
 147 
 148 // Represents the overflow mark stack used by concurrent marking.
 149 //
 150 // Stores oops in a huge buffer in virtual memory that is always fully committed.
 151 // Resizing may only happen during a STW pause when the stack is empty.
 152 //
 153 // Memory is allocated on a "chunk" basis, i.e. a set of oops. For this, the mark
 154 // stack memory is split into evenly sized chunks of oops. Users can only
 155 // add or remove entries on that basis.
 156 // Chunks are filled in increasing address order. Not completely filled chunks
 157 // have a NULL element as a terminating element.
 158 //
 159 // Every chunk has a header containing a single pointer element used for memory
 160 // management. This wastes some space, but is negligible (< .1% with current sizing).
 161 //
 162 // Memory management is done using a mix of tracking a high water-mark indicating
 163 // that all chunks at a lower address are valid chunks, and a singly linked free
 164 // list connecting all empty chunks.
 165 class G1CMMarkStack VALUE_OBJ_CLASS_SPEC {
 166 public:
 167   // Number of oops that can fit in a single chunk.
 168   static const size_t OopsPerChunk = 1024 - 1 /* One reference for the next pointer */;
 169 private:
 170   struct OopChunk {
 171     OopChunk* next;
 172     oop data[OopsPerChunk];
 173   };
 174 
 175   size_t _max_chunk_capacity;    // Maximum number of OopChunk elements on the stack.
 176 
 177   OopChunk* _base;               // Bottom address of allocated memory area.
 178   size_t _chunk_capacity;        // Current maximum number of OopChunk elements.
 179 
 180   char _pad0[DEFAULT_CACHE_LINE_SIZE];
 181   OopChunk* volatile _free_list;  // Linked list of free chunks that can be allocated by users.
 182   char _pad1[DEFAULT_CACHE_LINE_SIZE - sizeof(OopChunk*)];
 183   OopChunk* volatile _chunk_list; // List of chunks currently containing data.
 184   volatile size_t _chunks_in_chunk_list;
 185   char _pad2[DEFAULT_CACHE_LINE_SIZE - sizeof(OopChunk*) - sizeof(size_t)];
 186 
 187   volatile size_t _hwm;          // High water mark within the reserved space.
 188   char _pad4[DEFAULT_CACHE_LINE_SIZE - sizeof(size_t)];
 189 
 190   // Allocate a new chunk from the reserved memory, using the high water mark. Returns
 191   // NULL if out of memory.
 192   OopChunk* allocate_new_chunk();
 193 
 194   volatile bool _out_of_memory;
 195 
 196   // Atomically add the given chunk to the list.
 197   void add_chunk_to_list(OopChunk* volatile* list, OopChunk* elem);
 198   // Atomically remove and return a chunk from the given list. Returns NULL if the
 199   // list is empty.
 200   OopChunk* remove_chunk_from_list(OopChunk* volatile* list);
 201 
 202   void add_chunk_to_chunk_list(OopChunk* elem);
 203   void add_chunk_to_free_list(OopChunk* elem);
 204 
 205   OopChunk* remove_chunk_from_chunk_list();
 206   OopChunk* remove_chunk_from_free_list();
 207 
 208   bool  _should_expand;
 209 
 210   // Resizes the mark stack to the given new capacity. Releases any previous
 211   // memory if successful.
 212   bool resize(size_t new_capacity);
 213 
 214  public:
 215   G1CMMarkStack();
 216   ~G1CMMarkStack();
 217 
 218   // Alignment and minimum capacity of this mark stack in number of oops.
 219   static size_t capacity_alignment();
 220 
 221   // Allocate and initialize the mark stack with the given number of oops.
 222   bool initialize(size_t initial_capacity, size_t max_capacity);
 223 
 224   // Pushes the given buffer containing at most OopsPerChunk elements on the mark
 225   // stack. If less than OopsPerChunk elements are to be pushed, the array must
 226   // be terminated with a NULL.
 227   // Returns whether the buffer contents were successfully pushed to the global mark
 228   // stack.
 229   bool par_push_chunk(oop* buffer);
 230 
 231   // Pops a chunk from this mark stack, copying them into the given buffer. This
 232   // chunk may contain up to OopsPerChunk elements. If there are less, the last
 233   // element in the array is a NULL pointer.
 234   bool par_pop_chunk(oop* buffer);
 235 
 236   // Return whether the chunk list is empty. Racy due to unsynchronized access to
 237   // _chunk_list.
 238   bool is_empty() const { return _chunk_list == NULL; }
 239 
 240   size_t capacity() const  { return _chunk_capacity; }
 241 
 242   bool is_out_of_memory() const { return _out_of_memory; }
 243   void clear_out_of_memory() { _out_of_memory = false; }
 244 
 245   bool should_expand() const { return _should_expand; }
 246   void set_should_expand(bool value) { _should_expand = value; }
 247 
 248   // Expand the stack, typically in response to an overflow condition
 249   void expand();
 250 
 251   // Return the approximate number of oops on this mark stack. Racy due to
 252   // unsynchronized access to _chunks_in_chunk_list.
 253   size_t size() const { return _chunks_in_chunk_list * OopsPerChunk; }
 254 
 255   void set_empty();
 256 
 257   // Apply Fn to every oop on the mark stack. The mark stack must not
 258   // be modified while iterating.
 259   template<typename Fn> void iterate(Fn fn) const PRODUCT_RETURN;
 260 };
 261 
 262 // Root Regions are regions that are not empty at the beginning of a
 263 // marking cycle and which we might collect during an evacuation pause
 264 // while the cycle is active. Given that, during evacuation pauses, we
 265 // do not copy objects that are explicitly marked, what we have to do
 266 // for the root regions is to scan them and mark all objects reachable
 267 // from them. According to the SATB assumptions, we only need to visit
 268 // each object once during marking. So, as long as we finish this scan
 269 // before the next evacuation pause, we can copy the objects from the
 270 // root regions without having to mark them or do anything else to them.
 271 //
 272 // Currently, we only support root region scanning once (at the start
 273 // of the marking cycle) and the root regions are all the survivor
 274 // regions populated during the initial-mark pause.
 275 class G1CMRootRegions VALUE_OBJ_CLASS_SPEC {
 276 private:
 277   const G1SurvivorRegions* _survivors;
 278   G1ConcurrentMark*        _cm;
 279 
 280   volatile bool            _scan_in_progress;
 281   volatile bool            _should_abort;
 282   volatile int             _claimed_survivor_index;
 283 
 284   void notify_scan_done();
 285 
 286 public:
 287   G1CMRootRegions();
 288   // We actually do most of the initialization in this method.
 289   void init(const G1SurvivorRegions* survivors, G1ConcurrentMark* cm);
 290 
 291   // Reset the claiming / scanning of the root regions.
 292   void prepare_for_scan();
 293 
 294   // Forces get_next() to return NULL so that the iteration aborts early.
 295   void abort() { _should_abort = true; }
 296 
 297   // Return true if the CM thread are actively scanning root regions,
 298   // false otherwise.
 299   bool scan_in_progress() { return _scan_in_progress; }
 300 
 301   // Claim the next root region to scan atomically, or return NULL if
 302   // all have been claimed.
 303   HeapRegion* claim_next();
 304 
 305   // The number of root regions to scan.
 306   uint num_root_regions() const;
 307 
 308   void cancel_scan();
 309 
 310   // Flag that we're done with root region scanning and notify anyone
 311   // who's waiting on it. If aborted is false, assume that all regions
 312   // have been claimed.
 313   void scan_finished();
 314 
 315   // If CM threads are still scanning root regions, wait until they
 316   // are done. Return true if we had to wait, false otherwise.
 317   bool wait_until_scan_finished();
 318 };
 319 
 320 class ConcurrentMarkThread;
 321 
 322 class G1ConcurrentMark: public CHeapObj<mtGC> {
 323   friend class ConcurrentMarkThread;
 324   friend class G1ParNoteEndTask;
 325   friend class G1VerifyLiveDataClosure;
 326   friend class G1CMRefProcTaskProxy;
 327   friend class G1CMRefProcTaskExecutor;
 328   friend class G1CMKeepAliveAndDrainClosure;
 329   friend class G1CMDrainMarkingStackClosure;
 330   friend class G1CMBitMapClosure;
 331   friend class G1CMConcurrentMarkingTask;
 332   friend class G1CMRemarkTask;
 333   friend class G1CMTask;
 334 
 335 protected:
 336   ConcurrentMarkThread* _cmThread;   // The thread doing the work
 337   G1CollectedHeap*      _g1h;        // The heap
 338   uint                  _parallel_marking_threads; // The number of marking
 339                                                    // threads we're using
 340   uint                  _max_parallel_marking_threads; // Max number of marking
 341                                                        // threads we'll ever use
 342   double                _sleep_factor; // How much we have to sleep, with
 343                                        // respect to the work we just did, to
 344                                        // meet the marking overhead goal
 345   double                _marking_task_overhead; // Marking target overhead for
 346                                                 // a single task
 347 
 348   FreeRegionList        _cleanup_list;
 349 
 350   // Concurrent marking support structures
 351   G1CMBitMap              _markBitMap1;
 352   G1CMBitMap              _markBitMap2;
 353   G1CMBitMapRO*           _prevMarkBitMap; // Completed mark bitmap
 354   G1CMBitMap*             _nextMarkBitMap; // Under-construction mark bitmap
 355 
 356   // Heap bounds
 357   HeapWord*               _heap_start;
 358   HeapWord*               _heap_end;
 359 
 360   // Root region tracking and claiming
 361   G1CMRootRegions         _root_regions;
 362 
 363   // For gray objects
 364   G1CMMarkStack           _global_mark_stack; // Grey objects behind global finger
 365   HeapWord* volatile      _finger;  // The global finger, region aligned,
 366                                     // always points to the end of the
 367                                     // last claimed region
 368 
 369   // Marking tasks
 370   uint                    _max_worker_id;// Maximum worker id
 371   uint                    _active_tasks; // Task num currently active
 372   G1CMTask**              _tasks;        // Task queue array (max_worker_id len)
 373   G1CMTaskQueueSet*       _task_queues;  // Task queue set
 374   ParallelTaskTerminator  _terminator;   // For termination
 375 
 376   // Two sync barriers that are used to synchronize tasks when an
 377   // overflow occurs. The algorithm is the following. All tasks enter
 378   // the first one to ensure that they have all stopped manipulating
 379   // the global data structures. After they exit it, they re-initialize
 380   // their data structures and task 0 re-initializes the global data
 381   // structures. Then, they enter the second sync barrier. This
 382   // ensure, that no task starts doing work before all data
 383   // structures (local and global) have been re-initialized. When they
 384   // exit it, they are free to start working again.
 385   WorkGangBarrierSync     _first_overflow_barrier_sync;
 386   WorkGangBarrierSync     _second_overflow_barrier_sync;
 387 
 388   // This is set by any task, when an overflow on the global data
 389   // structures is detected
 390   volatile bool           _has_overflown;
 391   // True: marking is concurrent, false: we're in remark
 392   volatile bool           _concurrent;
 393   // Set at the end of a Full GC so that marking aborts
 394   volatile bool           _has_aborted;
 395 
 396   // Used when remark aborts due to an overflow to indicate that
 397   // another concurrent marking phase should start
 398   volatile bool           _restart_for_overflow;
 399 
 400   // This is true from the very start of concurrent marking until the
 401   // point when all the tasks complete their work. It is really used
 402   // to determine the points between the end of concurrent marking and
 403   // time of remark.
 404   volatile bool           _concurrent_marking_in_progress;
 405 
 406   ConcurrentGCTimer*      _gc_timer_cm;
 407 
 408   G1OldTracer*            _gc_tracer_cm;
 409 
 410   // All of these times are in ms
 411   NumberSeq _init_times;
 412   NumberSeq _remark_times;
 413   NumberSeq _remark_mark_times;
 414   NumberSeq _remark_weak_ref_times;
 415   NumberSeq _cleanup_times;
 416   double    _total_counting_time;
 417   double    _total_rs_scrub_time;
 418 
 419   double*   _accum_task_vtime;   // Accumulated task vtime
 420 
 421   WorkGang* _parallel_workers;
 422 
 423   void weakRefsWorkParallelPart(BoolObjectClosure* is_alive, bool purged_classes);
 424   void weakRefsWork(bool clear_all_soft_refs);
 425 
 426   void swapMarkBitMaps();
 427 
 428   // It resets the global marking data structures, as well as the
 429   // task local ones; should be called during initial mark.
 430   void reset();
 431 
 432   // Resets all the marking data structures. Called when we have to restart
 433   // marking or when marking completes (via set_non_marking_state below).
 434   void reset_marking_state(bool clear_overflow = true);
 435 
 436   // We do this after we're done with marking so that the marking data
 437   // structures are initialized to a sensible and predictable state.
 438   void set_non_marking_state();
 439 
 440   // Called to indicate how many threads are currently active.
 441   void set_concurrency(uint active_tasks);
 442 
 443   // It should be called to indicate which phase we're in (concurrent
 444   // mark or remark) and how many threads are currently active.
 445   void set_concurrency_and_phase(uint active_tasks, bool concurrent);
 446 
 447   // Prints all gathered CM-related statistics
 448   void print_stats();
 449 
 450   bool cleanup_list_is_empty() {
 451     return _cleanup_list.is_empty();
 452   }
 453 
 454   // Accessor methods
 455   uint parallel_marking_threads() const     { return _parallel_marking_threads; }
 456   uint max_parallel_marking_threads() const { return _max_parallel_marking_threads;}
 457   double sleep_factor()                     { return _sleep_factor; }
 458   double marking_task_overhead()            { return _marking_task_overhead;}
 459 
 460   HeapWord*               finger()          { return _finger;   }
 461   bool                    concurrent()      { return _concurrent; }
 462   uint                    active_tasks()    { return _active_tasks; }
 463   ParallelTaskTerminator* terminator()      { return &_terminator; }
 464 
 465   // It claims the next available region to be scanned by a marking
 466   // task/thread. It might return NULL if the next region is empty or
 467   // we have run out of regions. In the latter case, out_of_regions()
 468   // determines whether we've really run out of regions or the task
 469   // should call claim_region() again. This might seem a bit
 470   // awkward. Originally, the code was written so that claim_region()
 471   // either successfully returned with a non-empty region or there
 472   // were no more regions to be claimed. The problem with this was
 473   // that, in certain circumstances, it iterated over large chunks of
 474   // the heap finding only empty regions and, while it was working, it
 475   // was preventing the calling task to call its regular clock
 476   // method. So, this way, each task will spend very little time in
 477   // claim_region() and is allowed to call the regular clock method
 478   // frequently.
 479   HeapRegion* claim_region(uint worker_id);
 480 
 481   // It determines whether we've run out of regions to scan. Note that
 482   // the finger can point past the heap end in case the heap was expanded
 483   // to satisfy an allocation without doing a GC. This is fine, because all
 484   // objects in those regions will be considered live anyway because of
 485   // SATB guarantees (i.e. their TAMS will be equal to bottom).
 486   bool        out_of_regions() { return _finger >= _heap_end; }
 487 
 488   // Returns the task with the given id
 489   G1CMTask* task(int id) {
 490     assert(0 <= id && id < (int) _active_tasks,
 491            "task id not within active bounds");
 492     return _tasks[id];
 493   }
 494 
 495   // Returns the task queue with the given id
 496   G1CMTaskQueue* task_queue(int id) {
 497     assert(0 <= id && id < (int) _active_tasks,
 498            "task queue id not within active bounds");
 499     return (G1CMTaskQueue*) _task_queues->queue(id);
 500   }
 501 
 502   // Returns the task queue set
 503   G1CMTaskQueueSet* task_queues()  { return _task_queues; }
 504 
 505   // Access / manipulation of the overflow flag which is set to
 506   // indicate that the global stack has overflown
 507   bool has_overflown()           { return _has_overflown; }
 508   void set_has_overflown()       { _has_overflown = true; }
 509   void clear_has_overflown()     { _has_overflown = false; }
 510   bool restart_for_overflow()    { return _restart_for_overflow; }
 511 
 512   // Methods to enter the two overflow sync barriers
 513   void enter_first_sync_barrier(uint worker_id);
 514   void enter_second_sync_barrier(uint worker_id);
 515 
 516   // Card index of the bottom of the G1 heap. Used for biasing indices into
 517   // the card bitmaps.
 518   intptr_t _heap_bottom_card_num;
 519 
 520   // Set to true when initialization is complete
 521   bool _completed_initialization;
 522 
 523   // end_timer, true to end gc timer after ending concurrent phase.
 524   void register_concurrent_phase_end_common(bool end_timer);
 525 
 526   // Clear the given bitmap in parallel using the given WorkGang. If may_yield is
 527   // true, periodically insert checks to see if this method should exit prematurely.
 528   void clear_bitmap(G1CMBitMap* bitmap, WorkGang* workers, bool may_yield);
 529 public:
 530   // Manipulation of the global mark stack.
 531   // The push and pop operations are used by tasks for transfers
 532   // between task-local queues and the global mark stack.
 533   bool mark_stack_push(oop* arr) {
 534     if (!_global_mark_stack.par_push_chunk(arr)) {
 535       set_has_overflown();
 536       return false;
 537     }
 538     return true;
 539   }
 540   bool mark_stack_pop(oop* arr) {
 541     return _global_mark_stack.par_pop_chunk(arr);
 542   }
 543   size_t mark_stack_size()                { return _global_mark_stack.size(); }
 544   size_t partial_mark_stack_size_target() { return _global_mark_stack.capacity()/3; }
 545   bool mark_stack_overflow()              { return _global_mark_stack.is_out_of_memory(); }
 546   bool mark_stack_empty()                 { return _global_mark_stack.is_empty(); }
 547 
 548   G1CMRootRegions* root_regions() { return &_root_regions; }
 549 
 550   bool concurrent_marking_in_progress() {
 551     return _concurrent_marking_in_progress;
 552   }
 553   void set_concurrent_marking_in_progress() {
 554     _concurrent_marking_in_progress = true;
 555   }
 556   void clear_concurrent_marking_in_progress() {
 557     _concurrent_marking_in_progress = false;
 558   }
 559 
 560   void concurrent_cycle_start();
 561   void concurrent_cycle_end();
 562 
 563   void update_accum_task_vtime(int i, double vtime) {
 564     _accum_task_vtime[i] += vtime;
 565   }
 566 
 567   double all_task_accum_vtime() {
 568     double ret = 0.0;
 569     for (uint i = 0; i < _max_worker_id; ++i)
 570       ret += _accum_task_vtime[i];
 571     return ret;
 572   }
 573 
 574   // Attempts to steal an object from the task queues of other tasks
 575   bool try_stealing(uint worker_id, int* hash_seed, oop& obj);
 576 
 577   G1ConcurrentMark(G1CollectedHeap* g1h,
 578                    G1RegionToSpaceMapper* prev_bitmap_storage,
 579                    G1RegionToSpaceMapper* next_bitmap_storage);
 580   ~G1ConcurrentMark();
 581 
 582   ConcurrentMarkThread* cmThread() { return _cmThread; }
 583 
 584   G1CMBitMapRO* prevMarkBitMap() const { return _prevMarkBitMap; }
 585   G1CMBitMap*   nextMarkBitMap() const { return _nextMarkBitMap; }
 586 
 587   // Returns the number of GC threads to be used in a concurrent
 588   // phase based on the number of GC threads being used in a STW
 589   // phase.
 590   uint scale_parallel_threads(uint n_par_threads);
 591 
 592   // Calculates the number of GC threads to be used in a concurrent phase.
 593   uint calc_parallel_marking_threads();
 594 
 595   // The following three are interaction between CM and
 596   // G1CollectedHeap
 597 
 598   // This notifies CM that a root during initial-mark needs to be
 599   // grayed. It is MT-safe. hr is the region that
 600   // contains the object and it's passed optionally from callers who
 601   // might already have it (no point in recalculating it).
 602   inline void grayRoot(oop obj,
 603                        HeapRegion* hr = NULL);
 604 
 605   // Prepare internal data structures for the next mark cycle. This includes clearing
 606   // the next mark bitmap and some internal data structures. This method is intended
 607   // to be called concurrently to the mutator. It will yield to safepoint requests.
 608   void cleanup_for_next_mark();
 609 
 610   // Clear the previous marking bitmap during safepoint.
 611   void clear_prev_bitmap(WorkGang* workers);
 612 
 613   // Return whether the next mark bitmap has no marks set. To be used for assertions
 614   // only. Will not yield to pause requests.
 615   bool nextMarkBitmapIsClear();
 616 
 617   // These two do the work that needs to be done before and after the
 618   // initial root checkpoint. Since this checkpoint can be done at two
 619   // different points (i.e. an explicit pause or piggy-backed on a
 620   // young collection), then it's nice to be able to easily share the
 621   // pre/post code. It might be the case that we can put everything in
 622   // the post method. TP
 623   void checkpointRootsInitialPre();
 624   void checkpointRootsInitialPost();
 625 
 626   // Scan all the root regions and mark everything reachable from
 627   // them.
 628   void scan_root_regions();
 629 
 630   // Scan a single root region and mark everything reachable from it.
 631   void scanRootRegion(HeapRegion* hr);
 632 
 633   // Do concurrent phase of marking, to a tentative transitive closure.
 634   void mark_from_roots();
 635 
 636   void checkpointRootsFinal(bool clear_all_soft_refs);
 637   void checkpointRootsFinalWork();
 638   void cleanup();
 639   void complete_cleanup();
 640 
 641   // Mark in the previous bitmap.  NB: this is usually read-only, so use
 642   // this carefully!
 643   inline void markPrev(oop p);
 644 
 645   // Clears marks for all objects in the given range, for the prev or
 646   // next bitmaps.  NB: the previous bitmap is usually
 647   // read-only, so use this carefully!
 648   void clearRangePrevBitmap(MemRegion mr);
 649 
 650   // Verify that there are no CSet oops on the stacks (taskqueues /
 651   // global mark stack) and fingers (global / per-task).
 652   // If marking is not in progress, it's a no-op.
 653   void verify_no_cset_oops() PRODUCT_RETURN;
 654 
 655   inline bool isPrevMarked(oop p) const;
 656 
 657   inline bool do_yield_check();
 658 
 659   // Abandon current marking iteration due to a Full GC.
 660   void abort();
 661 
 662   bool has_aborted()      { return _has_aborted; }
 663 
 664   void print_summary_info();
 665 
 666   void print_worker_threads_on(outputStream* st) const;
 667   void threads_do(ThreadClosure* tc) const;
 668 
 669   void print_on_error(outputStream* st) const;
 670 
 671   // Attempts to mark the given object on the next mark bitmap.
 672   inline bool par_mark(oop obj);
 673 
 674   // Returns true if initialization was successfully completed.
 675   bool completed_initialization() const {
 676     return _completed_initialization;
 677   }
 678 
 679   ConcurrentGCTimer* gc_timer_cm() const { return _gc_timer_cm; }
 680   G1OldTracer* gc_tracer_cm() const { return _gc_tracer_cm; }
 681 
 682 private:
 683   // Clear (Reset) all liveness count data.
 684   void clear_live_data(WorkGang* workers);
 685 
 686 #ifdef ASSERT
 687   // Verify all of the above data structures that they are in initial state.
 688   void verify_live_data_clear();
 689 #endif
 690 
 691   // Aggregates the per-card liveness data based on the current marking. Also sets
 692   // the amount of marked bytes for each region.
 693   void create_live_data();
 694 
 695   void finalize_live_data();
 696 
 697   void verify_live_data();
 698 };
 699 
 700 // A class representing a marking task.
 701 class G1CMTask : public TerminatorTerminator {
 702 private:
 703   enum PrivateConstants {
 704     // The regular clock call is called once the scanned words reaches
 705     // this limit
 706     words_scanned_period          = 12*1024,
 707     // The regular clock call is called once the number of visited
 708     // references reaches this limit
 709     refs_reached_period           = 384,
 710     // Initial value for the hash seed, used in the work stealing code
 711     init_hash_seed                = 17
 712   };
 713 
 714   uint                        _worker_id;
 715   G1CollectedHeap*            _g1h;
 716   G1ConcurrentMark*           _cm;
 717   G1CMBitMap*                 _nextMarkBitMap;
 718   // the task queue of this task
 719   G1CMTaskQueue*              _task_queue;
 720 private:
 721   // the task queue set---needed for stealing
 722   G1CMTaskQueueSet*           _task_queues;
 723   // indicates whether the task has been claimed---this is only  for
 724   // debugging purposes
 725   bool                        _claimed;
 726 
 727   // number of calls to this task
 728   int                         _calls;
 729 
 730   // when the virtual timer reaches this time, the marking step should
 731   // exit
 732   double                      _time_target_ms;
 733   // the start time of the current marking step
 734   double                      _start_time_ms;
 735 
 736   // the oop closure used for iterations over oops
 737   G1CMOopClosure*             _cm_oop_closure;
 738 
 739   // the region this task is scanning, NULL if we're not scanning any
 740   HeapRegion*                 _curr_region;
 741   // the local finger of this task, NULL if we're not scanning a region
 742   HeapWord*                   _finger;
 743   // limit of the region this task is scanning, NULL if we're not scanning one
 744   HeapWord*                   _region_limit;
 745 
 746   // the number of words this task has scanned
 747   size_t                      _words_scanned;
 748   // When _words_scanned reaches this limit, the regular clock is
 749   // called. Notice that this might be decreased under certain
 750   // circumstances (i.e. when we believe that we did an expensive
 751   // operation).
 752   size_t                      _words_scanned_limit;
 753   // the initial value of _words_scanned_limit (i.e. what it was
 754   // before it was decreased).
 755   size_t                      _real_words_scanned_limit;
 756 
 757   // the number of references this task has visited
 758   size_t                      _refs_reached;
 759   // When _refs_reached reaches this limit, the regular clock is
 760   // called. Notice this this might be decreased under certain
 761   // circumstances (i.e. when we believe that we did an expensive
 762   // operation).
 763   size_t                      _refs_reached_limit;
 764   // the initial value of _refs_reached_limit (i.e. what it was before
 765   // it was decreased).
 766   size_t                      _real_refs_reached_limit;
 767 
 768   // used by the work stealing stuff
 769   int                         _hash_seed;
 770   // if this is true, then the task has aborted for some reason
 771   bool                        _has_aborted;
 772   // set when the task aborts because it has met its time quota
 773   bool                        _has_timed_out;
 774   // true when we're draining SATB buffers; this avoids the task
 775   // aborting due to SATB buffers being available (as we're already
 776   // dealing with them)
 777   bool                        _draining_satb_buffers;
 778 
 779   // number sequence of past step times
 780   NumberSeq                   _step_times_ms;
 781   // elapsed time of this task
 782   double                      _elapsed_time_ms;
 783   // termination time of this task
 784   double                      _termination_time_ms;
 785   // when this task got into the termination protocol
 786   double                      _termination_start_time_ms;
 787 
 788   // true when the task is during a concurrent phase, false when it is
 789   // in the remark phase (so, in the latter case, we do not have to
 790   // check all the things that we have to check during the concurrent
 791   // phase, i.e. SATB buffer availability...)
 792   bool                        _concurrent;
 793 
 794   TruncatedSeq                _marking_step_diffs_ms;
 795 
 796   // it updates the local fields after this task has claimed
 797   // a new region to scan
 798   void setup_for_region(HeapRegion* hr);
 799   // it brings up-to-date the limit of the region
 800   void update_region_limit();
 801 
 802   // called when either the words scanned or the refs visited limit
 803   // has been reached
 804   void reached_limit();
 805   // recalculates the words scanned and refs visited limits
 806   void recalculate_limits();
 807   // decreases the words scanned and refs visited limits when we reach
 808   // an expensive operation
 809   void decrease_limits();
 810   // it checks whether the words scanned or refs visited reached their
 811   // respective limit and calls reached_limit() if they have
 812   void check_limits() {
 813     if (_words_scanned >= _words_scanned_limit ||
 814         _refs_reached >= _refs_reached_limit) {
 815       reached_limit();
 816     }
 817   }
 818   // this is supposed to be called regularly during a marking step as
 819   // it checks a bunch of conditions that might cause the marking step
 820   // to abort
 821   void regular_clock_call();
 822   bool concurrent() { return _concurrent; }
 823 
 824   // Test whether obj might have already been passed over by the
 825   // mark bitmap scan, and so needs to be pushed onto the mark stack.
 826   bool is_below_finger(oop obj, HeapWord* global_finger) const;
 827 
 828   template<bool scan> void process_grey_object(oop obj);
 829 
 830 public:
 831   // It resets the task; it should be called right at the beginning of
 832   // a marking phase.
 833   void reset(G1CMBitMap* _nextMarkBitMap);
 834   // it clears all the fields that correspond to a claimed region.
 835   void clear_region_fields();
 836 
 837   void set_concurrent(bool concurrent) { _concurrent = concurrent; }
 838 
 839   // The main method of this class which performs a marking step
 840   // trying not to exceed the given duration. However, it might exit
 841   // prematurely, according to some conditions (i.e. SATB buffers are
 842   // available for processing).
 843   void do_marking_step(double target_ms,
 844                        bool do_termination,
 845                        bool is_serial);
 846 
 847   // These two calls start and stop the timer
 848   void record_start_time() {
 849     _elapsed_time_ms = os::elapsedTime() * 1000.0;
 850   }
 851   void record_end_time() {
 852     _elapsed_time_ms = os::elapsedTime() * 1000.0 - _elapsed_time_ms;
 853   }
 854 
 855   // returns the worker ID associated with this task.
 856   uint worker_id() { return _worker_id; }
 857 
 858   // From TerminatorTerminator. It determines whether this task should
 859   // exit the termination protocol after it's entered it.
 860   virtual bool should_exit_termination();
 861 
 862   // Resets the local region fields after a task has finished scanning a
 863   // region; or when they have become stale as a result of the region
 864   // being evacuated.
 865   void giveup_current_region();
 866 
 867   HeapWord* finger()            { return _finger; }
 868 
 869   bool has_aborted()            { return _has_aborted; }
 870   void set_has_aborted()        { _has_aborted = true; }
 871   void clear_has_aborted()      { _has_aborted = false; }
 872   bool has_timed_out()          { return _has_timed_out; }
 873   bool claimed()                { return _claimed; }
 874 
 875   void set_cm_oop_closure(G1CMOopClosure* cm_oop_closure);
 876 
 877   // Increment the number of references this task has visited.
 878   void increment_refs_reached() { ++_refs_reached; }
 879 
 880   // Grey the object by marking it.  If not already marked, push it on
 881   // the local queue if below the finger.
 882   // obj is below its region's NTAMS.
 883   inline void make_reference_grey(oop obj);
 884 
 885   // Grey the object (by calling make_grey_reference) if required,
 886   // e.g. obj is below its containing region's NTAMS.
 887   // Precondition: obj is a valid heap object.
 888   inline void deal_with_reference(oop obj);
 889 
 890   // It scans an object and visits its children.
 891   inline void scan_object(oop obj);
 892 
 893   // It pushes an object on the local queue.
 894   inline void push(oop obj);
 895 
 896   // Move entries to the global stack.
 897   void move_entries_to_global_stack();
 898   // Move entries from the global stack, return true if we were successful to do so.
 899   bool get_entries_from_global_stack();
 900 
 901   // It pops and scans objects from the local queue. If partially is
 902   // true, then it stops when the queue size is of a given limit. If
 903   // partially is false, then it stops when the queue is empty.
 904   void drain_local_queue(bool partially);
 905   // It moves entries from the global stack to the local queue and
 906   // drains the local queue. If partially is true, then it stops when
 907   // both the global stack and the local queue reach a given size. If
 908   // partially if false, it tries to empty them totally.
 909   void drain_global_stack(bool partially);
 910   // It keeps picking SATB buffers and processing them until no SATB
 911   // buffers are available.
 912   void drain_satb_buffers();
 913 
 914   // moves the local finger to a new location
 915   inline void move_finger_to(HeapWord* new_finger) {
 916     assert(new_finger >= _finger && new_finger < _region_limit, "invariant");
 917     _finger = new_finger;
 918   }
 919 
 920   G1CMTask(uint worker_id,
 921            G1ConcurrentMark *cm,
 922            G1CMTaskQueue* task_queue,
 923            G1CMTaskQueueSet* task_queues);
 924 
 925   // it prints statistics associated with this task
 926   void print_stats();
 927 };
 928 
 929 // Class that's used to to print out per-region liveness
 930 // information. It's currently used at the end of marking and also
 931 // after we sort the old regions at the end of the cleanup operation.
 932 class G1PrintRegionLivenessInfoClosure: public HeapRegionClosure {
 933 private:
 934   // Accumulators for these values.
 935   size_t _total_used_bytes;
 936   size_t _total_capacity_bytes;
 937   size_t _total_prev_live_bytes;
 938   size_t _total_next_live_bytes;
 939 
 940   // Accumulator for the remembered set size
 941   size_t _total_remset_bytes;
 942 
 943   // Accumulator for strong code roots memory size
 944   size_t _total_strong_code_roots_bytes;
 945 
 946   static double perc(size_t val, size_t total) {
 947     if (total == 0) {
 948       return 0.0;
 949     } else {
 950       return 100.0 * ((double) val / (double) total);
 951     }
 952   }
 953 
 954   static double bytes_to_mb(size_t val) {
 955     return (double) val / (double) M;
 956   }
 957 
 958 public:
 959   // The header and footer are printed in the constructor and
 960   // destructor respectively.
 961   G1PrintRegionLivenessInfoClosure(const char* phase_name);
 962   virtual bool doHeapRegion(HeapRegion* r);
 963   ~G1PrintRegionLivenessInfoClosure();
 964 };
 965 
 966 #endif // SHARE_VM_GC_G1_G1CONCURRENTMARK_HPP