1 /*
  2  * Copyright (c) 2001, 2026, 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_GC_G1_G1CONCURRENTMARK_INLINE_HPP
 26 #define SHARE_GC_G1_G1CONCURRENTMARK_INLINE_HPP
 27 
 28 #include "gc/g1/g1ConcurrentMark.hpp"
 29 
 30 #include "gc/g1/g1CollectedHeap.inline.hpp"
 31 #include "gc/g1/g1CollectorState.inline.hpp"
 32 #include "gc/g1/g1ConcurrentMarkBitMap.inline.hpp"
 33 #include "gc/g1/g1HeapRegion.hpp"
 34 #include "gc/g1/g1HeapRegionRemSet.inline.hpp"
 35 #include "gc/g1/g1OopClosures.inline.hpp"
 36 #include "gc/g1/g1Policy.hpp"
 37 #include "gc/g1/g1RegionMarkStatsCache.inline.hpp"
 38 #include "gc/g1/g1RemSetTrackingPolicy.hpp"
 39 #include "gc/shared/suspendibleThreadSet.hpp"
 40 #include "gc/shared/taskqueue.inline.hpp"
 41 #include "utilities/bitMap.inline.hpp"
 42 #include "utilities/checkedCast.hpp"
 43 
 44 inline bool G1CMIsAliveClosure::do_object_b(oop obj) {
 45   // Check whether the passed in object is null. During discovery the referent
 46   // may be cleared between the initial check and being passed in here.
 47   if (obj == nullptr) {
 48     // Return true to avoid discovery when the referent is null.
 49     return true;
 50   }
 51 
 52   // All objects allocated since the start of marking are considered live.
 53   if (_cm->obj_allocated_since_mark_start(obj)) {
 54     return true;
 55   }
 56 
 57   // All objects that are marked are live.
 58   return _cm->is_marked_in_bitmap(obj);
 59 }
 60 
 61 inline bool G1CMSubjectToDiscoveryClosure::do_object_b(oop obj) {
 62   assert(obj != nullptr, "precondition");
 63   assert(_g1h->is_in_reserved(obj), "Trying to discover obj " PTR_FORMAT " not in heap", p2i(obj));
 64 
 65   return _g1h->heap_region_containing(obj)->is_old_or_humongous();
 66 }
 67 
 68 inline bool G1ConcurrentMark::mark_in_bitmap(uint const worker_id, oop const obj) {
 69   if (obj_allocated_since_mark_start(obj)) {
 70     return false;
 71   }
 72 
 73   // Some callers may have stale objects to mark above TAMS after humongous reclaim.
 74   // Can't assert that this is a valid object at this point, since it might be in the process of being copied by another thread.
 75   DEBUG_ONLY(G1HeapRegion* const hr = _g1h->heap_region_containing(obj);)
 76   assert(!hr->is_continues_humongous(),
 77          "Should not try to mark object " PTR_FORMAT " in Humongous continues region %u above TAMS " PTR_FORMAT,
 78          p2i(obj), hr->hrm_index(), p2i(top_at_mark_start(hr)));
 79 
 80   bool success = _mark_bitmap.par_mark(obj);
 81   if (success) {
 82     add_to_liveness(worker_id, obj, obj->size());
 83   }
 84   return success;
 85 }
 86 
 87 #ifndef PRODUCT
 88 template<typename Fn>
 89 inline void G1CMMarkStack::iterate(Fn fn) const {
 90   assert_at_safepoint_on_vm_thread();
 91 
 92   size_t num_chunks = 0;
 93 
 94   TaskQueueEntryChunk* cur = _chunk_list.load_relaxed();
 95   while (cur != nullptr) {
 96     guarantee(num_chunks <= _chunks_in_chunk_list, "Found %zu oop chunks which is more than there should be", num_chunks);
 97 
 98     for (size_t i = 0; i < EntriesPerChunk; ++i) {
 99       if (cur->data[i].is_null()) {
100         break;
101       }
102       fn(cur->data[i]);
103     }
104     cur = cur->next;
105     num_chunks++;
106   }
107 }
108 #endif
109 
110 inline void G1CMTask::process_klass(Klass* klass) {
111   _cm_oop_closure->do_klass(klass);
112 }
113 
114 // It scans an object and visits its children.
115 inline void G1CMTask::process_entry(G1TaskQueueEntry task_entry, bool stolen) {
116   assert(task_entry.is_partial_array_state() || _mark_bitmap->is_marked(cast_from_oop<HeapWord*>(task_entry.to_oop())),
117          "Any stolen object should be a slice or marked");
118 
119   if (task_entry.is_partial_array_state()) {
120     _words_scanned += process_partial_array(task_entry, stolen);
121   } else {
122     oop obj = task_entry.to_oop();
123     if (should_be_sliced(obj)) {
124       _words_scanned += start_partial_array_processing(objArrayOop(obj));
125     } else {
126       _words_scanned += obj->oop_iterate_size(_cm_oop_closure);
127     }
128   }
129 
130   check_limits();
131 }
132 
133 inline void G1CMTask::push(G1TaskQueueEntry task_entry) {
134   assert(task_entry.is_partial_array_state() || _g1h->is_in_reserved(task_entry.to_oop()), "invariant");
135   assert(task_entry.is_partial_array_state() || !_g1h->is_on_master_free_list(
136               _g1h->heap_region_containing(task_entry.to_oop())), "invariant");
137   assert(task_entry.is_partial_array_state() || _mark_bitmap->is_marked(cast_from_oop<HeapWord*>(task_entry.to_oop())), "invariant");
138 
139   if (!_task_queue->push(task_entry)) {
140     // The local task queue looks full. We need to push some entries
141     // to the global stack.
142     move_entries_to_global_stack();
143 
144     // this should succeed since, even if we overflow the global
145     // stack, we should have definitely removed some entries from the
146     // local queue. So, there must be space on it.
147     bool success = _task_queue->push(task_entry);
148     assert(success, "invariant");
149   }
150 }
151 
152 inline bool G1CMTask::is_below_finger(oop obj, HeapWord* global_finger) const {
153   // If obj is above the global finger, then the mark bitmap scan
154   // will find it later, and no push is needed.  Similarly, if we have
155   // a current region and obj is between the local finger and the
156   // end of the current region, then no push is needed.  The tradeoff
157   // of checking both vs only checking the global finger is that the
158   // local check will be more accurate and so result in fewer pushes,
159   // but may also be a little slower.
160   HeapWord* objAddr = cast_from_oop<HeapWord*>(obj);
161   if (_finger != nullptr) {
162     // We have a current region.
163 
164     // Finger and region values are all null or all non-null.  We
165     // use _finger to check since we immediately use its value.
166     assert(_curr_region != nullptr, "invariant");
167     assert(_region_limit != nullptr, "invariant");
168     assert(_region_limit <= global_finger, "invariant");
169 
170     // True if obj is less than the local finger, or is between
171     // the region limit and the global finger.
172     if (objAddr < _finger) {
173       return true;
174     } else if (objAddr < _region_limit) {
175       return false;
176     } // Else check global finger.
177   }
178   // Check global finger.
179   return objAddr < global_finger;
180 }
181 
182 inline bool G1CMTask::should_be_sliced(oop obj) {
183   return obj->is_objArray() && ((objArrayOop)obj)->length() >= (int)ObjArrayMarkingStride;
184 }
185 
186 inline void G1CMTask::process_array_chunk(objArrayOop obj, size_t start, size_t end) {
187   obj->oop_iterate_elements_range(_cm_oop_closure,
188                                   checked_cast<int>(start),
189                                   checked_cast<int>(end));
190 }
191 
192 inline void G1ConcurrentMark::update_top_at_mark_start(G1HeapRegion* r) {
193   assert_fully_initialized();
194   assert(_g1h->collector_state()->is_in_concurrent_start_gc(), "must be");
195   uint const region = r->hrm_index();
196   assert(region < _g1h->max_num_regions(), "Tried to access TAMS for region %u out of bounds", region);
197   _top_at_mark_starts[region].store_relaxed(r->top());
198 }
199 
200 inline void G1ConcurrentMark::set_top_at_mark_start_to_bottom(G1HeapRegion* r) {
201   assert_fully_initialized();
202   _top_at_mark_starts[r->hrm_index()].store_relaxed(r->bottom());
203 }
204 
205 inline void G1ConcurrentMark::assert_top_at_mark_start_is_bottom(G1HeapRegion* r) {
206   // Can not assert anything if not initialized.
207   if (!tams_may_be_read()) {
208     return;
209   }
210   HeapWord* local_top_at_mark_start = top_at_mark_start(r);
211   assert(local_top_at_mark_start == r->bottom(),
212          "must be, but tams for r %u (%s) is" PTR_FORMAT,
213          r->hrm_index(), r->get_short_type_str(), p2i(local_top_at_mark_start));
214 }
215 
216 inline HeapWord* G1ConcurrentMark::top_at_mark_start_or_bottom(const G1HeapRegion* r) const {
217   if (!tams_may_be_read()) {
218     return r->bottom();
219   }
220   return top_at_mark_start(r);
221 }
222 
223 inline HeapWord* G1ConcurrentMark::top_at_mark_start_for_verification(const G1HeapRegion* r,
224                                                                       bool concurrent_cycle_aborted) const {
225   if (!is_fully_initialized()) {
226     // We do not have TAMS data yet.
227     return r->bottom();
228   }
229   if (tams_may_be_read()) {
230     // Normal case, we can read TAMS data and it is valid.
231     return top_at_mark_start(r);
232   }
233   if (concurrent_cycle_aborted) {
234     assert(_g1h->collector_state()->is_in_full_gc(), "Must be in Full GC if concurrent cycle has aborted");
235     assert(r->hrm_index() < _g1h->max_num_regions(),
236            "Tried to access TAMS for region %u out of bounds", r->hrm_index());
237     return _top_at_mark_starts[r->hrm_index()].load_relaxed();
238   }
239   return r->bottom();
240 }
241 
242 inline bool G1ConcurrentMark::tams_may_be_read() const {
243   // We need the TAMS to be valid even outside of actual marking for e.g. clearing the bitmap.
244   G1CollectorState* state = _g1h->collector_state();
245   return is_fully_initialized() &&
246          (state->is_in_concurrent_cycle() || state->is_in_concurrent_start_gc());
247 }
248 
249 inline HeapWord* G1ConcurrentMark::top_at_mark_start(const G1HeapRegion* r) const {
250   return top_at_mark_start(r->hrm_index());
251 }
252 
253 inline HeapWord* G1ConcurrentMark::top_at_mark_start(uint region) const {
254   assert_fully_initialized();
255   assert(tams_may_be_read(), "must be");
256   assert(region < _g1h->max_num_regions(), "Tried to access TARS for region %u out of bounds", region);
257   return _top_at_mark_starts[region].load_relaxed();
258 }
259 
260 inline bool G1ConcurrentMark::obj_allocated_since_mark_start(oop obj) const {
261   uint const region = _g1h->addr_to_region(obj);
262   assert(region < _g1h->max_num_regions(), "obj " PTR_FORMAT " outside heap %u", p2i(obj), region);
263   return cast_from_oop<HeapWord*>(obj) >= top_at_mark_start(region);
264 }
265 
266 inline HeapWord* G1ConcurrentMark::top_at_rebuild_start(G1HeapRegion* r) const {
267   assert_fully_initialized();
268   return _top_at_rebuild_starts[r->hrm_index()].load_relaxed();
269 }
270 
271 inline void G1ConcurrentMark::update_top_at_rebuild_start(G1HeapRegion* r) {
272   assert_fully_initialized();
273   assert(r->is_old() || r->is_humongous(), "precondition");
274 
275   uint const region = r->hrm_index();
276   assert(region < _g1h->max_num_regions(), "Tried to access TARS for region %u out of bounds", region);
277   assert(top_at_rebuild_start(r) == nullptr,
278          "TARS for region %u has already been set to " PTR_FORMAT " should be null",
279          region, p2i(top_at_rebuild_start(r)));
280   _top_at_rebuild_starts[region].store_relaxed(r->top());
281 }
282 
283 inline void G1CMTask::update_liveness(oop const obj, const size_t obj_size) {
284   _mark_stats_cache.add_live_words(_g1h->addr_to_region(obj), obj_size);
285 }
286 
287 inline void G1CMTask::inc_incoming_refs(oop const obj) {
288   _mark_stats_cache.inc_incoming_refs(_g1h->addr_to_region(obj));
289 }
290 
291 inline void G1ConcurrentMark::add_to_liveness(uint worker_id, oop const obj, size_t size) {
292   task(worker_id)->update_liveness(obj, size);
293 }
294 
295 inline bool G1ConcurrentMark::contains_live_object(uint region) const {
296   assert_fully_initialized();
297   return _region_mark_stats[region].live_words() != 0;
298 }
299 
300 inline size_t G1ConcurrentMark::live_bytes(uint region) const {
301   assert_fully_initialized();
302   return _region_mark_stats[region].live_words() * HeapWordSize;
303 }
304 
305 inline void G1ConcurrentMark::set_live_bytes(uint region, size_t live_bytes) {
306   assert_fully_initialized();
307   _region_mark_stats[region]._live_words.store_relaxed(live_bytes / HeapWordSize);
308 }
309 
310 inline size_t G1ConcurrentMark::incoming_refs(uint region) const {
311   assert_fully_initialized();
312   return _region_mark_stats[region].incoming_refs();
313 }
314 
315 inline void G1CMTask::abort_marking_if_regular_check_fail() {
316   if (!regular_clock_call()) {
317     set_has_aborted();
318   }
319 }
320 
321 inline bool G1CMTask::make_reference_grey(oop obj) {
322   if (!_cm->mark_in_bitmap(_worker_id, obj)) {
323     return false;
324   }
325 
326   // No OrderAccess:store_load() is needed. It is implicit in the
327   // CAS done in G1CMBitMap::parMark() call in the routine above.
328   HeapWord* global_finger = _cm->finger();
329 
330   // We only need to push a newly grey object on the mark
331   // stack if it is in a section of memory the mark bitmap
332   // scan has already examined.  Mark bitmap scanning
333   // maintains progress "fingers" for determining that.
334   //
335   // Notice that the global finger might be moving forward
336   // concurrently. This is not a problem. In the worst case, we
337   // mark the object while it is above the global finger and, by
338   // the time we read the global finger, it has moved forward
339   // past this object. In this case, the object will probably
340   // be visited when a task is scanning the region and will also
341   // be pushed on the stack. So, some duplicate work, but no
342   // correctness problems.
343   if (is_below_finger(obj, global_finger)) {
344     if (obj->is_typeArray()) {
345       // Immediately process arrays of primitive types, rather
346       // than pushing on the mark stack.  This keeps us from
347       // adding humongous objects to the mark stack that might
348       // be reclaimed before the entry is processed - see
349       // selection of candidates for eager reclaim of humongous
350       // objects.  The cost of the additional type test is
351       // mitigated by avoiding a trip through the mark stack,
352       // by only doing a bookkeeping update and avoiding the
353       // actual scan of the object - a typeArray contains no
354       // references, and the metadata is built-in.
355     } else {
356       G1TaskQueueEntry entry(obj);
357       push(entry);
358     }
359   }
360   return true;
361 }
362 
363 template <class T>
364 inline bool G1CMTask::deal_with_reference(T* p) {
365   increment_refs_reached();
366   oop const obj = RawAccess<MO_RELAXED>::oop_load(p);
367   if (obj == nullptr) {
368     return false;
369   }
370 
371   if (!G1HeapRegion::is_in_same_region(p, obj)) {
372     inc_incoming_refs(obj);
373   }
374   return make_reference_grey(obj);
375 }
376 
377 inline void G1ConcurrentMark::raw_mark_in_bitmap(oop obj) {
378   _mark_bitmap.par_mark(obj);
379 }
380 
381 bool G1ConcurrentMark::is_marked_in_bitmap(oop p) const {
382   assert(p != nullptr && oopDesc::is_oop(p), "expected an oop");
383   return _mark_bitmap.is_marked(cast_from_oop<HeapWord*>(p));
384 }
385 
386 inline bool G1ConcurrentMark::do_yield_check() {
387   if (SuspendibleThreadSet::should_yield()) {
388     SuspendibleThreadSet::yield();
389     return true;
390   } else {
391     return false;
392   }
393 }
394 
395 #endif // SHARE_GC_G1_G1CONCURRENTMARK_INLINE_HPP