Fri, 01 Oct 2010 18:23:16 -0700
6983311: G1: LoopTest hangs when run with -XX:+ExplicitInvokesConcurrent
Summary: Clear the concurrent marking "in progress" flag while the FullGCCount_lock is held. This avoids a race that can cause back to back System.gc() calls, when ExplicitGCInvokesConcurrent is enabled, to fail to initiate a marking cycle causing the requesting thread to hang.
Reviewed-by: tonyp, ysr
1 /*
2 * Copyright (c) 2001, 2010, 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 */
25 class G1CollectedHeap;
26 class CMTask;
27 typedef GenericTaskQueue<oop> CMTaskQueue;
28 typedef GenericTaskQueueSet<CMTaskQueue> CMTaskQueueSet;
30 // A generic CM bit map. This is essentially a wrapper around the BitMap
31 // class, with one bit per (1<<_shifter) HeapWords.
33 class CMBitMapRO VALUE_OBJ_CLASS_SPEC {
34 protected:
35 HeapWord* _bmStartWord; // base address of range covered by map
36 size_t _bmWordSize; // map size (in #HeapWords covered)
37 const int _shifter; // map to char or bit
38 VirtualSpace _virtual_space; // underlying the bit map
39 BitMap _bm; // the bit map itself
41 public:
42 // constructor
43 CMBitMapRO(ReservedSpace rs, int shifter);
45 enum { do_yield = true };
47 // inquiries
48 HeapWord* startWord() const { return _bmStartWord; }
49 size_t sizeInWords() const { return _bmWordSize; }
50 // the following is one past the last word in space
51 HeapWord* endWord() const { return _bmStartWord + _bmWordSize; }
53 // read marks
55 bool isMarked(HeapWord* addr) const {
56 assert(_bmStartWord <= addr && addr < (_bmStartWord + _bmWordSize),
57 "outside underlying space?");
58 return _bm.at(heapWordToOffset(addr));
59 }
61 // iteration
62 bool iterate(BitMapClosure* cl) { return _bm.iterate(cl); }
63 bool iterate(BitMapClosure* cl, MemRegion mr);
65 // Return the address corresponding to the next marked bit at or after
66 // "addr", and before "limit", if "limit" is non-NULL. If there is no
67 // such bit, returns "limit" if that is non-NULL, or else "endWord()".
68 HeapWord* getNextMarkedWordAddress(HeapWord* addr,
69 HeapWord* limit = NULL) const;
70 // Return the address corresponding to the next unmarked bit at or after
71 // "addr", and before "limit", if "limit" is non-NULL. If there is no
72 // such bit, returns "limit" if that is non-NULL, or else "endWord()".
73 HeapWord* getNextUnmarkedWordAddress(HeapWord* addr,
74 HeapWord* limit = NULL) const;
76 // conversion utilities
77 // XXX Fix these so that offsets are size_t's...
78 HeapWord* offsetToHeapWord(size_t offset) const {
79 return _bmStartWord + (offset << _shifter);
80 }
81 size_t heapWordToOffset(HeapWord* addr) const {
82 return pointer_delta(addr, _bmStartWord) >> _shifter;
83 }
84 int heapWordDiffToOffsetDiff(size_t diff) const;
85 HeapWord* nextWord(HeapWord* addr) {
86 return offsetToHeapWord(heapWordToOffset(addr) + 1);
87 }
89 void mostly_disjoint_range_union(BitMap* from_bitmap,
90 size_t from_start_index,
91 HeapWord* to_start_word,
92 size_t word_num);
94 // debugging
95 NOT_PRODUCT(bool covers(ReservedSpace rs) const;)
96 };
98 class CMBitMap : public CMBitMapRO {
100 public:
101 // constructor
102 CMBitMap(ReservedSpace rs, int shifter) :
103 CMBitMapRO(rs, shifter) {}
105 // write marks
106 void mark(HeapWord* addr) {
107 assert(_bmStartWord <= addr && addr < (_bmStartWord + _bmWordSize),
108 "outside underlying space?");
109 _bm.at_put(heapWordToOffset(addr), true);
110 }
111 void clear(HeapWord* addr) {
112 assert(_bmStartWord <= addr && addr < (_bmStartWord + _bmWordSize),
113 "outside underlying space?");
114 _bm.at_put(heapWordToOffset(addr), false);
115 }
116 bool parMark(HeapWord* addr) {
117 assert(_bmStartWord <= addr && addr < (_bmStartWord + _bmWordSize),
118 "outside underlying space?");
119 return _bm.par_at_put(heapWordToOffset(addr), true);
120 }
121 bool parClear(HeapWord* addr) {
122 assert(_bmStartWord <= addr && addr < (_bmStartWord + _bmWordSize),
123 "outside underlying space?");
124 return _bm.par_at_put(heapWordToOffset(addr), false);
125 }
126 void markRange(MemRegion mr);
127 void clearAll();
128 void clearRange(MemRegion mr);
130 // Starting at the bit corresponding to "addr" (inclusive), find the next
131 // "1" bit, if any. This bit starts some run of consecutive "1"'s; find
132 // the end of this run (stopping at "end_addr"). Return the MemRegion
133 // covering from the start of the region corresponding to the first bit
134 // of the run to the end of the region corresponding to the last bit of
135 // the run. If there is no "1" bit at or after "addr", return an empty
136 // MemRegion.
137 MemRegion getAndClearMarkedRegion(HeapWord* addr, HeapWord* end_addr);
138 };
140 // Represents a marking stack used by the CM collector.
141 // Ideally this should be GrowableArray<> just like MSC's marking stack(s).
142 class CMMarkStack VALUE_OBJ_CLASS_SPEC {
143 ConcurrentMark* _cm;
144 oop* _base; // bottom of stack
145 jint _index; // one more than last occupied index
146 jint _capacity; // max #elements
147 jint _oops_do_bound; // Number of elements to include in next iteration.
148 NOT_PRODUCT(jint _max_depth;) // max depth plumbed during run
150 bool _overflow;
151 DEBUG_ONLY(bool _drain_in_progress;)
152 DEBUG_ONLY(bool _drain_in_progress_yields;)
154 public:
155 CMMarkStack(ConcurrentMark* cm);
156 ~CMMarkStack();
158 void allocate(size_t size);
160 oop pop() {
161 if (!isEmpty()) {
162 return _base[--_index] ;
163 }
164 return NULL;
165 }
167 // If overflow happens, don't do the push, and record the overflow.
168 // *Requires* that "ptr" is already marked.
169 void push(oop ptr) {
170 if (isFull()) {
171 // Record overflow.
172 _overflow = true;
173 return;
174 } else {
175 _base[_index++] = ptr;
176 NOT_PRODUCT(_max_depth = MAX2(_max_depth, _index));
177 }
178 }
179 // Non-block impl. Note: concurrency is allowed only with other
180 // "par_push" operations, not with "pop" or "drain". We would need
181 // parallel versions of them if such concurrency was desired.
182 void par_push(oop ptr);
184 // Pushes the first "n" elements of "ptr_arr" on the stack.
185 // Non-block impl. Note: concurrency is allowed only with other
186 // "par_adjoin_arr" or "push" operations, not with "pop" or "drain".
187 void par_adjoin_arr(oop* ptr_arr, int n);
189 // Pushes the first "n" elements of "ptr_arr" on the stack.
190 // Locking impl: concurrency is allowed only with
191 // "par_push_arr" and/or "par_pop_arr" operations, which use the same
192 // locking strategy.
193 void par_push_arr(oop* ptr_arr, int n);
195 // If returns false, the array was empty. Otherwise, removes up to "max"
196 // elements from the stack, and transfers them to "ptr_arr" in an
197 // unspecified order. The actual number transferred is given in "n" ("n
198 // == 0" is deliberately redundant with the return value.) Locking impl:
199 // concurrency is allowed only with "par_push_arr" and/or "par_pop_arr"
200 // operations, which use the same locking strategy.
201 bool par_pop_arr(oop* ptr_arr, int max, int* n);
203 // Drain the mark stack, applying the given closure to all fields of
204 // objects on the stack. (That is, continue until the stack is empty,
205 // even if closure applications add entries to the stack.) The "bm"
206 // argument, if non-null, may be used to verify that only marked objects
207 // are on the mark stack. If "yield_after" is "true", then the
208 // concurrent marker performing the drain offers to yield after
209 // processing each object. If a yield occurs, stops the drain operation
210 // and returns false. Otherwise, returns true.
211 template<class OopClosureClass>
212 bool drain(OopClosureClass* cl, CMBitMap* bm, bool yield_after = false);
214 bool isEmpty() { return _index == 0; }
215 bool isFull() { return _index == _capacity; }
216 int maxElems() { return _capacity; }
218 bool overflow() { return _overflow; }
219 void clear_overflow() { _overflow = false; }
221 int size() { return _index; }
223 void setEmpty() { _index = 0; clear_overflow(); }
225 // Record the current size; a subsequent "oops_do" will iterate only over
226 // indices valid at the time of this call.
227 void set_oops_do_bound(jint bound = -1) {
228 if (bound == -1) {
229 _oops_do_bound = _index;
230 } else {
231 _oops_do_bound = bound;
232 }
233 }
234 jint oops_do_bound() { return _oops_do_bound; }
235 // iterate over the oops in the mark stack, up to the bound recorded via
236 // the call above.
237 void oops_do(OopClosure* f);
238 };
240 class CMRegionStack VALUE_OBJ_CLASS_SPEC {
241 MemRegion* _base;
242 jint _capacity;
243 jint _index;
244 jint _oops_do_bound;
245 bool _overflow;
246 public:
247 CMRegionStack();
248 ~CMRegionStack();
249 void allocate(size_t size);
251 // This is lock-free; assumes that it will only be called in parallel
252 // with other "push" operations (no pops).
253 void push_lock_free(MemRegion mr);
255 // Lock-free; assumes that it will only be called in parallel
256 // with other "pop" operations (no pushes).
257 MemRegion pop_lock_free();
259 #if 0
260 // The routines that manipulate the region stack with a lock are
261 // not currently used. They should be retained, however, as a
262 // diagnostic aid.
264 // These two are the implementations that use a lock. They can be
265 // called concurrently with each other but they should not be called
266 // concurrently with the lock-free versions (push() / pop()).
267 void push_with_lock(MemRegion mr);
268 MemRegion pop_with_lock();
269 #endif
271 bool isEmpty() { return _index == 0; }
272 bool isFull() { return _index == _capacity; }
274 bool overflow() { return _overflow; }
275 void clear_overflow() { _overflow = false; }
277 int size() { return _index; }
279 // It iterates over the entries in the region stack and it
280 // invalidates (i.e. assigns MemRegion()) the ones that point to
281 // regions in the collection set.
282 bool invalidate_entries_into_cset();
284 // This gives an upper bound up to which the iteration in
285 // invalidate_entries_into_cset() will reach. This prevents
286 // newly-added entries to be unnecessarily scanned.
287 void set_oops_do_bound() {
288 _oops_do_bound = _index;
289 }
291 void setEmpty() { _index = 0; clear_overflow(); }
292 };
294 // this will enable a variety of different statistics per GC task
295 #define _MARKING_STATS_ 0
296 // this will enable the higher verbose levels
297 #define _MARKING_VERBOSE_ 0
299 #if _MARKING_STATS_
300 #define statsOnly(statement) \
301 do { \
302 statement ; \
303 } while (0)
304 #else // _MARKING_STATS_
305 #define statsOnly(statement) \
306 do { \
307 } while (0)
308 #endif // _MARKING_STATS_
310 typedef enum {
311 no_verbose = 0, // verbose turned off
312 stats_verbose, // only prints stats at the end of marking
313 low_verbose, // low verbose, mostly per region and per major event
314 medium_verbose, // a bit more detailed than low
315 high_verbose // per object verbose
316 } CMVerboseLevel;
319 class ConcurrentMarkThread;
321 class ConcurrentMark: public CHeapObj {
322 friend class ConcurrentMarkThread;
323 friend class CMTask;
324 friend class CMBitMapClosure;
325 friend class CSMarkOopClosure;
326 friend class CMGlobalObjectClosure;
327 friend class CMRemarkTask;
328 friend class CMConcurrentMarkingTask;
329 friend class G1ParNoteEndTask;
330 friend class CalcLiveObjectsClosure;
332 protected:
333 ConcurrentMarkThread* _cmThread; // the thread doing the work
334 G1CollectedHeap* _g1h; // the heap.
335 size_t _parallel_marking_threads; // the number of marking
336 // threads we'll use
337 double _sleep_factor; // how much we have to sleep, with
338 // respect to the work we just did, to
339 // meet the marking overhead goal
340 double _marking_task_overhead; // marking target overhead for
341 // a single task
343 // same as the two above, but for the cleanup task
344 double _cleanup_sleep_factor;
345 double _cleanup_task_overhead;
347 // Stuff related to age cohort processing.
348 struct ParCleanupThreadState {
349 char _pre[64];
350 UncleanRegionList list;
351 char _post[64];
352 };
353 ParCleanupThreadState** _par_cleanup_thread_state;
355 // CMS marking support structures
356 CMBitMap _markBitMap1;
357 CMBitMap _markBitMap2;
358 CMBitMapRO* _prevMarkBitMap; // completed mark bitmap
359 CMBitMap* _nextMarkBitMap; // under-construction mark bitmap
360 bool _at_least_one_mark_complete;
362 BitMap _region_bm;
363 BitMap _card_bm;
365 // Heap bounds
366 HeapWord* _heap_start;
367 HeapWord* _heap_end;
369 // For gray objects
370 CMMarkStack _markStack; // Grey objects behind global finger.
371 CMRegionStack _regionStack; // Grey regions behind global finger.
372 HeapWord* volatile _finger; // the global finger, region aligned,
373 // always points to the end of the
374 // last claimed region
376 // marking tasks
377 size_t _max_task_num; // maximum task number
378 size_t _active_tasks; // task num currently active
379 CMTask** _tasks; // task queue array (max_task_num len)
380 CMTaskQueueSet* _task_queues; // task queue set
381 ParallelTaskTerminator _terminator; // for termination
383 // Two sync barriers that are used to synchronise tasks when an
384 // overflow occurs. The algorithm is the following. All tasks enter
385 // the first one to ensure that they have all stopped manipulating
386 // the global data structures. After they exit it, they re-initialise
387 // their data structures and task 0 re-initialises the global data
388 // structures. Then, they enter the second sync barrier. This
389 // ensure, that no task starts doing work before all data
390 // structures (local and global) have been re-initialised. When they
391 // exit it, they are free to start working again.
392 WorkGangBarrierSync _first_overflow_barrier_sync;
393 WorkGangBarrierSync _second_overflow_barrier_sync;
396 // this is set by any task, when an overflow on the global data
397 // structures is detected.
398 volatile bool _has_overflown;
399 // true: marking is concurrent, false: we're in remark
400 volatile bool _concurrent;
401 // set at the end of a Full GC so that marking aborts
402 volatile bool _has_aborted;
404 // used when remark aborts due to an overflow to indicate that
405 // another concurrent marking phase should start
406 volatile bool _restart_for_overflow;
408 // This is true from the very start of concurrent marking until the
409 // point when all the tasks complete their work. It is really used
410 // to determine the points between the end of concurrent marking and
411 // time of remark.
412 volatile bool _concurrent_marking_in_progress;
414 // verbose level
415 CMVerboseLevel _verbose_level;
417 // These two fields are used to implement the optimisation that
418 // avoids pushing objects on the global/region stack if there are
419 // no collection set regions above the lowest finger.
421 // This is the lowest finger (among the global and local fingers),
422 // which is calculated before a new collection set is chosen.
423 HeapWord* _min_finger;
424 // If this flag is true, objects/regions that are marked below the
425 // finger should be pushed on the stack(s). If this is flag is
426 // false, it is safe not to push them on the stack(s).
427 bool _should_gray_objects;
429 // All of these times are in ms.
430 NumberSeq _init_times;
431 NumberSeq _remark_times;
432 NumberSeq _remark_mark_times;
433 NumberSeq _remark_weak_ref_times;
434 NumberSeq _cleanup_times;
435 double _total_counting_time;
436 double _total_rs_scrub_time;
438 double* _accum_task_vtime; // accumulated task vtime
440 WorkGang* _parallel_workers;
442 void weakRefsWork(bool clear_all_soft_refs);
444 void swapMarkBitMaps();
446 // It resets the global marking data structures, as well as the
447 // task local ones; should be called during initial mark.
448 void reset();
449 // It resets all the marking data structures.
450 void clear_marking_state();
452 // It should be called to indicate which phase we're in (concurrent
453 // mark or remark) and how many threads are currently active.
454 void set_phase(size_t active_tasks, bool concurrent);
455 // We do this after we're done with marking so that the marking data
456 // structures are initialised to a sensible and predictable state.
457 void set_non_marking_state();
459 // prints all gathered CM-related statistics
460 void print_stats();
462 // accessor methods
463 size_t parallel_marking_threads() { return _parallel_marking_threads; }
464 double sleep_factor() { return _sleep_factor; }
465 double marking_task_overhead() { return _marking_task_overhead;}
466 double cleanup_sleep_factor() { return _cleanup_sleep_factor; }
467 double cleanup_task_overhead() { return _cleanup_task_overhead;}
469 HeapWord* finger() { return _finger; }
470 bool concurrent() { return _concurrent; }
471 size_t active_tasks() { return _active_tasks; }
472 ParallelTaskTerminator* terminator() { return &_terminator; }
474 // It claims the next available region to be scanned by a marking
475 // task. It might return NULL if the next region is empty or we have
476 // run out of regions. In the latter case, out_of_regions()
477 // determines whether we've really run out of regions or the task
478 // should call claim_region() again. This might seem a bit
479 // awkward. Originally, the code was written so that claim_region()
480 // either successfully returned with a non-empty region or there
481 // were no more regions to be claimed. The problem with this was
482 // that, in certain circumstances, it iterated over large chunks of
483 // the heap finding only empty regions and, while it was working, it
484 // was preventing the calling task to call its regular clock
485 // method. So, this way, each task will spend very little time in
486 // claim_region() and is allowed to call the regular clock method
487 // frequently.
488 HeapRegion* claim_region(int task);
490 // It determines whether we've run out of regions to scan.
491 bool out_of_regions() { return _finger == _heap_end; }
493 // Returns the task with the given id
494 CMTask* task(int id) {
495 assert(0 <= id && id < (int) _active_tasks,
496 "task id not within active bounds");
497 return _tasks[id];
498 }
500 // Returns the task queue with the given id
501 CMTaskQueue* task_queue(int id) {
502 assert(0 <= id && id < (int) _active_tasks,
503 "task queue id not within active bounds");
504 return (CMTaskQueue*) _task_queues->queue(id);
505 }
507 // Returns the task queue set
508 CMTaskQueueSet* task_queues() { return _task_queues; }
510 // Access / manipulation of the overflow flag which is set to
511 // indicate that the global stack or region stack has overflown
512 bool has_overflown() { return _has_overflown; }
513 void set_has_overflown() { _has_overflown = true; }
514 void clear_has_overflown() { _has_overflown = false; }
516 bool has_aborted() { return _has_aborted; }
517 bool restart_for_overflow() { return _restart_for_overflow; }
519 // Methods to enter the two overflow sync barriers
520 void enter_first_sync_barrier(int task_num);
521 void enter_second_sync_barrier(int task_num);
523 public:
524 // Manipulation of the global mark stack.
525 // Notice that the first mark_stack_push is CAS-based, whereas the
526 // two below are Mutex-based. This is OK since the first one is only
527 // called during evacuation pauses and doesn't compete with the
528 // other two (which are called by the marking tasks during
529 // concurrent marking or remark).
530 bool mark_stack_push(oop p) {
531 _markStack.par_push(p);
532 if (_markStack.overflow()) {
533 set_has_overflown();
534 return false;
535 }
536 return true;
537 }
538 bool mark_stack_push(oop* arr, int n) {
539 _markStack.par_push_arr(arr, n);
540 if (_markStack.overflow()) {
541 set_has_overflown();
542 return false;
543 }
544 return true;
545 }
546 void mark_stack_pop(oop* arr, int max, int* n) {
547 _markStack.par_pop_arr(arr, max, n);
548 }
549 size_t mark_stack_size() { return _markStack.size(); }
550 size_t partial_mark_stack_size_target() { return _markStack.maxElems()/3; }
551 bool mark_stack_overflow() { return _markStack.overflow(); }
552 bool mark_stack_empty() { return _markStack.isEmpty(); }
554 // (Lock-free) Manipulation of the region stack
555 bool region_stack_push_lock_free(MemRegion mr) {
556 // Currently we only call the lock-free version during evacuation
557 // pauses.
558 assert(SafepointSynchronize::is_at_safepoint(), "world should be stopped");
560 _regionStack.push_lock_free(mr);
561 if (_regionStack.overflow()) {
562 set_has_overflown();
563 return false;
564 }
565 return true;
566 }
568 // Lock-free version of region-stack pop. Should only be
569 // called in tandem with other lock-free pops.
570 MemRegion region_stack_pop_lock_free() {
571 return _regionStack.pop_lock_free();
572 }
574 #if 0
575 // The routines that manipulate the region stack with a lock are
576 // not currently used. They should be retained, however, as a
577 // diagnostic aid.
579 bool region_stack_push_with_lock(MemRegion mr) {
580 // Currently we only call the lock-based version during either
581 // concurrent marking or remark.
582 assert(!SafepointSynchronize::is_at_safepoint() || !concurrent(),
583 "if we are at a safepoint it should be the remark safepoint");
585 _regionStack.push_with_lock(mr);
586 if (_regionStack.overflow()) {
587 set_has_overflown();
588 return false;
589 }
590 return true;
591 }
593 MemRegion region_stack_pop_with_lock() {
594 // Currently we only call the lock-based version during either
595 // concurrent marking or remark.
596 assert(!SafepointSynchronize::is_at_safepoint() || !concurrent(),
597 "if we are at a safepoint it should be the remark safepoint");
599 return _regionStack.pop_with_lock();
600 }
601 #endif
603 int region_stack_size() { return _regionStack.size(); }
604 bool region_stack_overflow() { return _regionStack.overflow(); }
605 bool region_stack_empty() { return _regionStack.isEmpty(); }
607 // Iterate over any regions that were aborted while draining the
608 // region stack (any such regions are saved in the corresponding
609 // CMTask) and invalidate (i.e. assign to the empty MemRegion())
610 // any regions that point into the collection set.
611 bool invalidate_aborted_regions_in_cset();
613 // Returns true if there are any aborted memory regions.
614 bool has_aborted_regions();
616 bool concurrent_marking_in_progress() {
617 return _concurrent_marking_in_progress;
618 }
619 void set_concurrent_marking_in_progress() {
620 _concurrent_marking_in_progress = true;
621 }
622 void clear_concurrent_marking_in_progress() {
623 _concurrent_marking_in_progress = false;
624 }
626 void update_accum_task_vtime(int i, double vtime) {
627 _accum_task_vtime[i] += vtime;
628 }
630 double all_task_accum_vtime() {
631 double ret = 0.0;
632 for (int i = 0; i < (int)_max_task_num; ++i)
633 ret += _accum_task_vtime[i];
634 return ret;
635 }
637 // Attempts to steal an object from the task queues of other tasks
638 bool try_stealing(int task_num, int* hash_seed, oop& obj) {
639 return _task_queues->steal(task_num, hash_seed, obj);
640 }
642 // It grays an object by first marking it. Then, if it's behind the
643 // global finger, it also pushes it on the global stack.
644 void deal_with_reference(oop obj);
646 ConcurrentMark(ReservedSpace rs, int max_regions);
647 ~ConcurrentMark();
648 ConcurrentMarkThread* cmThread() { return _cmThread; }
650 CMBitMapRO* prevMarkBitMap() const { return _prevMarkBitMap; }
651 CMBitMap* nextMarkBitMap() const { return _nextMarkBitMap; }
653 // The following three are interaction between CM and
654 // G1CollectedHeap
656 // This notifies CM that a root during initial-mark needs to be
657 // grayed and it's MT-safe. Currently, we just mark it. But, in the
658 // future, we can experiment with pushing it on the stack and we can
659 // do this without changing G1CollectedHeap.
660 void grayRoot(oop p);
661 // It's used during evacuation pauses to gray a region, if
662 // necessary, and it's MT-safe. It assumes that the caller has
663 // marked any objects on that region. If _should_gray_objects is
664 // true and we're still doing concurrent marking, the region is
665 // pushed on the region stack, if it is located below the global
666 // finger, otherwise we do nothing.
667 void grayRegionIfNecessary(MemRegion mr);
668 // It's used during evacuation pauses to mark and, if necessary,
669 // gray a single object and it's MT-safe. It assumes the caller did
670 // not mark the object. If _should_gray_objects is true and we're
671 // still doing concurrent marking, the objects is pushed on the
672 // global stack, if it is located below the global finger, otherwise
673 // we do nothing.
674 void markAndGrayObjectIfNecessary(oop p);
676 // It iterates over the heap and for each object it comes across it
677 // will dump the contents of its reference fields, as well as
678 // liveness information for the object and its referents. The dump
679 // will be written to a file with the following name:
680 // G1PrintReachableBaseFile + "." + str. use_prev_marking decides
681 // whether the prev (use_prev_marking == true) or next
682 // (use_prev_marking == false) marking information will be used to
683 // determine the liveness of each object / referent. If all is true,
684 // all objects in the heap will be dumped, otherwise only the live
685 // ones. In the dump the following symbols / abbreviations are used:
686 // M : an explicitly live object (its bitmap bit is set)
687 // > : an implicitly live object (over tams)
688 // O : an object outside the G1 heap (typically: in the perm gen)
689 // NOT : a reference field whose referent is not live
690 // AND MARKED : indicates that an object is both explicitly and
691 // implicitly live (it should be one or the other, not both)
692 void print_reachable(const char* str,
693 bool use_prev_marking, bool all) PRODUCT_RETURN;
695 // Clear the next marking bitmap (will be called concurrently).
696 void clearNextBitmap();
698 // main CMS steps and related support
699 void checkpointRootsInitial();
701 // These two do the work that needs to be done before and after the
702 // initial root checkpoint. Since this checkpoint can be done at two
703 // different points (i.e. an explicit pause or piggy-backed on a
704 // young collection), then it's nice to be able to easily share the
705 // pre/post code. It might be the case that we can put everything in
706 // the post method. TP
707 void checkpointRootsInitialPre();
708 void checkpointRootsInitialPost();
710 // Do concurrent phase of marking, to a tentative transitive closure.
711 void markFromRoots();
713 // Process all unprocessed SATB buffers. It is called at the
714 // beginning of an evacuation pause.
715 void drainAllSATBBuffers();
717 void checkpointRootsFinal(bool clear_all_soft_refs);
718 void checkpointRootsFinalWork();
719 void calcDesiredRegions();
720 void cleanup();
721 void completeCleanup();
723 // Mark in the previous bitmap. NB: this is usually read-only, so use
724 // this carefully!
725 void markPrev(oop p);
726 void clear(oop p);
727 // Clears marks for all objects in the given range, for both prev and
728 // next bitmaps. NB: the previous bitmap is usually read-only, so use
729 // this carefully!
730 void clearRangeBothMaps(MemRegion mr);
732 // Record the current top of the mark and region stacks; a
733 // subsequent oops_do() on the mark stack and
734 // invalidate_entries_into_cset() on the region stack will iterate
735 // only over indices valid at the time of this call.
736 void set_oops_do_bound() {
737 _markStack.set_oops_do_bound();
738 _regionStack.set_oops_do_bound();
739 }
740 // Iterate over the oops in the mark stack and all local queues. It
741 // also calls invalidate_entries_into_cset() on the region stack.
742 void oops_do(OopClosure* f);
743 // It is called at the end of an evacuation pause during marking so
744 // that CM is notified of where the new end of the heap is. It
745 // doesn't do anything if concurrent_marking_in_progress() is false,
746 // unless the force parameter is true.
747 void update_g1_committed(bool force = false);
749 void complete_marking_in_collection_set();
751 // It indicates that a new collection set is being chosen.
752 void newCSet();
753 // It registers a collection set heap region with CM. This is used
754 // to determine whether any heap regions are located above the finger.
755 void registerCSetRegion(HeapRegion* hr);
757 // Registers the maximum region-end associated with a set of
758 // regions with CM. Again this is used to determine whether any
759 // heap regions are located above the finger.
760 void register_collection_set_finger(HeapWord* max_finger) {
761 // max_finger is the highest heap region end of the regions currently
762 // contained in the collection set. If this value is larger than
763 // _min_finger then we need to gray objects.
764 // This routine is like registerCSetRegion but for an entire
765 // collection of regions.
766 if (max_finger > _min_finger)
767 _should_gray_objects = true;
768 }
770 // Returns "true" if at least one mark has been completed.
771 bool at_least_one_mark_complete() { return _at_least_one_mark_complete; }
773 bool isMarked(oop p) const {
774 assert(p != NULL && p->is_oop(), "expected an oop");
775 HeapWord* addr = (HeapWord*)p;
776 assert(addr >= _nextMarkBitMap->startWord() ||
777 addr < _nextMarkBitMap->endWord(), "in a region");
779 return _nextMarkBitMap->isMarked(addr);
780 }
782 inline bool not_yet_marked(oop p) const;
784 // XXX Debug code
785 bool containing_card_is_marked(void* p);
786 bool containing_cards_are_marked(void* start, void* last);
788 bool isPrevMarked(oop p) const {
789 assert(p != NULL && p->is_oop(), "expected an oop");
790 HeapWord* addr = (HeapWord*)p;
791 assert(addr >= _prevMarkBitMap->startWord() ||
792 addr < _prevMarkBitMap->endWord(), "in a region");
794 return _prevMarkBitMap->isMarked(addr);
795 }
797 inline bool do_yield_check(int worker_i = 0);
798 inline bool should_yield();
800 // Called to abort the marking cycle after a Full GC takes palce.
801 void abort();
803 // This prints the global/local fingers. It is used for debugging.
804 NOT_PRODUCT(void print_finger();)
806 void print_summary_info();
808 void print_worker_threads_on(outputStream* st) const;
810 // The following indicate whether a given verbose level has been
811 // set. Notice that anything above stats is conditional to
812 // _MARKING_VERBOSE_ having been set to 1
813 bool verbose_stats()
814 { return _verbose_level >= stats_verbose; }
815 bool verbose_low()
816 { return _MARKING_VERBOSE_ && _verbose_level >= low_verbose; }
817 bool verbose_medium()
818 { return _MARKING_VERBOSE_ && _verbose_level >= medium_verbose; }
819 bool verbose_high()
820 { return _MARKING_VERBOSE_ && _verbose_level >= high_verbose; }
821 };
823 // A class representing a marking task.
824 class CMTask : public TerminatorTerminator {
825 private:
826 enum PrivateConstants {
827 // the regular clock call is called once the scanned words reaches
828 // this limit
829 words_scanned_period = 12*1024,
830 // the regular clock call is called once the number of visited
831 // references reaches this limit
832 refs_reached_period = 384,
833 // initial value for the hash seed, used in the work stealing code
834 init_hash_seed = 17,
835 // how many entries will be transferred between global stack and
836 // local queues
837 global_stack_transfer_size = 16
838 };
840 int _task_id;
841 G1CollectedHeap* _g1h;
842 ConcurrentMark* _cm;
843 CMBitMap* _nextMarkBitMap;
844 // the task queue of this task
845 CMTaskQueue* _task_queue;
846 private:
847 // the task queue set---needed for stealing
848 CMTaskQueueSet* _task_queues;
849 // indicates whether the task has been claimed---this is only for
850 // debugging purposes
851 bool _claimed;
853 // number of calls to this task
854 int _calls;
856 // when the virtual timer reaches this time, the marking step should
857 // exit
858 double _time_target_ms;
859 // the start time of the current marking step
860 double _start_time_ms;
862 // the oop closure used for iterations over oops
863 OopClosure* _oop_closure;
865 // the region this task is scanning, NULL if we're not scanning any
866 HeapRegion* _curr_region;
867 // the local finger of this task, NULL if we're not scanning a region
868 HeapWord* _finger;
869 // limit of the region this task is scanning, NULL if we're not scanning one
870 HeapWord* _region_limit;
872 // This is used only when we scan regions popped from the region
873 // stack. It records what the last object on such a region we
874 // scanned was. It is used to ensure that, if we abort region
875 // iteration, we do not rescan the first part of the region. This
876 // should be NULL when we're not scanning a region from the region
877 // stack.
878 HeapWord* _region_finger;
880 // If we abort while scanning a region we record the remaining
881 // unscanned portion and check this field when marking restarts.
882 // This avoids having to push on the region stack while other
883 // marking threads may still be popping regions.
884 // If we were to push the unscanned portion directly to the
885 // region stack then we would need to using locking versions
886 // of the push and pop operations.
887 MemRegion _aborted_region;
889 // the number of words this task has scanned
890 size_t _words_scanned;
891 // When _words_scanned reaches this limit, the regular clock is
892 // called. Notice that this might be decreased under certain
893 // circumstances (i.e. when we believe that we did an expensive
894 // operation).
895 size_t _words_scanned_limit;
896 // the initial value of _words_scanned_limit (i.e. what it was
897 // before it was decreased).
898 size_t _real_words_scanned_limit;
900 // the number of references this task has visited
901 size_t _refs_reached;
902 // When _refs_reached reaches this limit, the regular clock is
903 // called. Notice this this might be decreased under certain
904 // circumstances (i.e. when we believe that we did an expensive
905 // operation).
906 size_t _refs_reached_limit;
907 // the initial value of _refs_reached_limit (i.e. what it was before
908 // it was decreased).
909 size_t _real_refs_reached_limit;
911 // used by the work stealing stuff
912 int _hash_seed;
913 // if this is true, then the task has aborted for some reason
914 bool _has_aborted;
915 // set when the task aborts because it has met its time quota
916 bool _has_aborted_timed_out;
917 // true when we're draining SATB buffers; this avoids the task
918 // aborting due to SATB buffers being available (as we're already
919 // dealing with them)
920 bool _draining_satb_buffers;
922 // number sequence of past step times
923 NumberSeq _step_times_ms;
924 // elapsed time of this task
925 double _elapsed_time_ms;
926 // termination time of this task
927 double _termination_time_ms;
928 // when this task got into the termination protocol
929 double _termination_start_time_ms;
931 // true when the task is during a concurrent phase, false when it is
932 // in the remark phase (so, in the latter case, we do not have to
933 // check all the things that we have to check during the concurrent
934 // phase, i.e. SATB buffer availability...)
935 bool _concurrent;
937 TruncatedSeq _marking_step_diffs_ms;
939 // LOTS of statistics related with this task
940 #if _MARKING_STATS_
941 NumberSeq _all_clock_intervals_ms;
942 double _interval_start_time_ms;
944 int _aborted;
945 int _aborted_overflow;
946 int _aborted_cm_aborted;
947 int _aborted_yield;
948 int _aborted_timed_out;
949 int _aborted_satb;
950 int _aborted_termination;
952 int _steal_attempts;
953 int _steals;
955 int _clock_due_to_marking;
956 int _clock_due_to_scanning;
958 int _local_pushes;
959 int _local_pops;
960 int _local_max_size;
961 int _objs_scanned;
963 int _global_pushes;
964 int _global_pops;
965 int _global_max_size;
967 int _global_transfers_to;
968 int _global_transfers_from;
970 int _region_stack_pops;
972 int _regions_claimed;
973 int _objs_found_on_bitmap;
975 int _satb_buffers_processed;
976 #endif // _MARKING_STATS_
978 // it updates the local fields after this task has claimed
979 // a new region to scan
980 void setup_for_region(HeapRegion* hr);
981 // it brings up-to-date the limit of the region
982 void update_region_limit();
983 // it resets the local fields after a task has finished scanning a
984 // region
985 void giveup_current_region();
987 // called when either the words scanned or the refs visited limit
988 // has been reached
989 void reached_limit();
990 // recalculates the words scanned and refs visited limits
991 void recalculate_limits();
992 // decreases the words scanned and refs visited limits when we reach
993 // an expensive operation
994 void decrease_limits();
995 // it checks whether the words scanned or refs visited reached their
996 // respective limit and calls reached_limit() if they have
997 void check_limits() {
998 if (_words_scanned >= _words_scanned_limit ||
999 _refs_reached >= _refs_reached_limit)
1000 reached_limit();
1001 }
1002 // this is supposed to be called regularly during a marking step as
1003 // it checks a bunch of conditions that might cause the marking step
1004 // to abort
1005 void regular_clock_call();
1006 bool concurrent() { return _concurrent; }
1008 public:
1009 // It resets the task; it should be called right at the beginning of
1010 // a marking phase.
1011 void reset(CMBitMap* _nextMarkBitMap);
1012 // it clears all the fields that correspond to a claimed region.
1013 void clear_region_fields();
1015 void set_concurrent(bool concurrent) { _concurrent = concurrent; }
1017 // The main method of this class which performs a marking step
1018 // trying not to exceed the given duration. However, it might exit
1019 // prematurely, according to some conditions (i.e. SATB buffers are
1020 // available for processing).
1021 void do_marking_step(double target_ms);
1023 // These two calls start and stop the timer
1024 void record_start_time() {
1025 _elapsed_time_ms = os::elapsedTime() * 1000.0;
1026 }
1027 void record_end_time() {
1028 _elapsed_time_ms = os::elapsedTime() * 1000.0 - _elapsed_time_ms;
1029 }
1031 // returns the task ID
1032 int task_id() { return _task_id; }
1034 // From TerminatorTerminator. It determines whether this task should
1035 // exit the termination protocol after it's entered it.
1036 virtual bool should_exit_termination();
1038 HeapWord* finger() { return _finger; }
1040 bool has_aborted() { return _has_aborted; }
1041 void set_has_aborted() { _has_aborted = true; }
1042 void clear_has_aborted() { _has_aborted = false; }
1043 bool claimed() { return _claimed; }
1045 // Support routines for the partially scanned region that may be
1046 // recorded as a result of aborting while draining the CMRegionStack
1047 MemRegion aborted_region() { return _aborted_region; }
1048 void set_aborted_region(MemRegion mr)
1049 { _aborted_region = mr; }
1051 // Clears any recorded partially scanned region
1052 void clear_aborted_region() { set_aborted_region(MemRegion()); }
1054 void set_oop_closure(OopClosure* oop_closure) {
1055 _oop_closure = oop_closure;
1056 }
1058 // It grays the object by marking it and, if necessary, pushing it
1059 // on the local queue
1060 void deal_with_reference(oop obj);
1062 // It scans an object and visits its children.
1063 void scan_object(oop obj) {
1064 assert(_nextMarkBitMap->isMarked((HeapWord*) obj), "invariant");
1066 if (_cm->verbose_high())
1067 gclog_or_tty->print_cr("[%d] we're scanning object "PTR_FORMAT,
1068 _task_id, (void*) obj);
1070 size_t obj_size = obj->size();
1071 _words_scanned += obj_size;
1073 obj->oop_iterate(_oop_closure);
1074 statsOnly( ++_objs_scanned );
1075 check_limits();
1076 }
1078 // It pushes an object on the local queue.
1079 void push(oop obj);
1081 // These two move entries to/from the global stack.
1082 void move_entries_to_global_stack();
1083 void get_entries_from_global_stack();
1085 // It pops and scans objects from the local queue. If partially is
1086 // true, then it stops when the queue size is of a given limit. If
1087 // partially is false, then it stops when the queue is empty.
1088 void drain_local_queue(bool partially);
1089 // It moves entries from the global stack to the local queue and
1090 // drains the local queue. If partially is true, then it stops when
1091 // both the global stack and the local queue reach a given size. If
1092 // partially if false, it tries to empty them totally.
1093 void drain_global_stack(bool partially);
1094 // It keeps picking SATB buffers and processing them until no SATB
1095 // buffers are available.
1096 void drain_satb_buffers();
1097 // It keeps popping regions from the region stack and processing
1098 // them until the region stack is empty.
1099 void drain_region_stack(BitMapClosure* closure);
1101 // moves the local finger to a new location
1102 inline void move_finger_to(HeapWord* new_finger) {
1103 assert(new_finger >= _finger && new_finger < _region_limit, "invariant");
1104 _finger = new_finger;
1105 }
1107 // moves the region finger to a new location
1108 inline void move_region_finger_to(HeapWord* new_finger) {
1109 assert(new_finger < _cm->finger(), "invariant");
1110 _region_finger = new_finger;
1111 }
1113 CMTask(int task_num, ConcurrentMark *cm,
1114 CMTaskQueue* task_queue, CMTaskQueueSet* task_queues);
1116 // it prints statistics associated with this task
1117 void print_stats();
1119 #if _MARKING_STATS_
1120 void increase_objs_found_on_bitmap() { ++_objs_found_on_bitmap; }
1121 #endif // _MARKING_STATS_
1122 };