1 /*
  2  * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #include "precompiled.hpp"
 26 #include "jvm.h"
 27 #include "gc/g1/g1CollectedHeap.inline.hpp"
 28 #include "gc/g1/satbMarkQueue.hpp"
 29 #include "gc/shared/collectedHeap.hpp"
 30 #include "memory/allocation.inline.hpp"
 31 #include "oops/oop.inline.hpp"
 32 #include "runtime/mutexLocker.hpp"
 33 #include "runtime/safepoint.hpp"
 34 #include "runtime/thread.hpp"
 35 #include "runtime/threadSMR.hpp"
 36 #include "runtime/vmThread.hpp"
 37 
 38 SATBMarkQueue::SATBMarkQueue(SATBMarkQueueSet* qset, bool permanent) :
 39   // SATB queues are only active during marking cycles. We create
 40   // them with their active field set to false. If a thread is
 41   // created during a cycle and its SATB queue needs to be activated
 42   // before the thread starts running, we'll need to set its active
 43   // field to true. This is done in G1SATBCardTableLoggingModRefBS::
 44   // on_thread_attach().
 45   PtrQueue(qset, permanent, false /* active */)
 46 { }
 47 
 48 void SATBMarkQueue::flush() {
 49   // Filter now to possibly save work later.  If filtering empties the
 50   // buffer then flush_impl can deallocate the buffer.
 51   filter();
 52   flush_impl();
 53 }
 54 
 55 // Return true if a SATB buffer entry refers to an object that
 56 // requires marking.
 57 //
 58 // The entry must point into the G1 heap.  In particular, it must not
 59 // be a NULL pointer.  NULL pointers are pre-filtered and never
 60 // inserted into a SATB buffer.
 61 //
 62 // An entry that is below the NTAMS pointer for the containing heap
 63 // region requires marking. Such an entry must point to a valid object.
 64 //
 65 // An entry that is at least the NTAMS pointer for the containing heap
 66 // region might be any of the following, none of which should be marked.
 67 //
 68 // * A reference to an object allocated since marking started.
 69 //   According to SATB, such objects are implicitly kept live and do
 70 //   not need to be dealt with via SATB buffer processing.
 71 //
 72 // * A reference to a young generation object. Young objects are
 73 //   handled separately and are not marked by concurrent marking.
 74 //
 75 // * A stale reference to a young generation object. If a young
 76 //   generation object reference is recorded and not filtered out
 77 //   before being moved by a young collection, the reference becomes
 78 //   stale.
 79 //
 80 // * A stale reference to an eagerly reclaimed humongous object.  If a
 81 //   humongous object is recorded and then reclaimed, the reference
 82 //   becomes stale.
 83 //
 84 // The stale reference cases are implicitly handled by the NTAMS
 85 // comparison. Because of the possibility of stale references, buffer
 86 // processing must be somewhat circumspect and not assume entries
 87 // in an unfiltered buffer refer to valid objects.
 88 
 89 inline bool requires_marking(const void* entry, G1CollectedHeap* heap) {
 90   // Includes rejection of NULL pointers.
 91   assert(heap->is_in_reserved(entry),
 92          "Non-heap pointer in SATB buffer: " PTR_FORMAT, p2i(entry));
 93 
 94   HeapRegion* region = heap->heap_region_containing(entry);
 95   assert(region != NULL, "No region for " PTR_FORMAT, p2i(entry));
 96   if (entry >= region->next_top_at_mark_start()) {
 97     return false;
 98   }
 99 
100   assert(oopDesc::is_oop(oop(entry), true /* ignore mark word */),
101          "Invalid oop in SATB buffer: " PTR_FORMAT, p2i(entry));
102 
103   return true;
104 }
105 
106 inline bool retain_entry(const void* entry, G1CollectedHeap* heap) {
107   return requires_marking(entry, heap) && !heap->isMarkedNext((oop)entry);
108 }
109 
110 // This method removes entries from a SATB buffer that will not be
111 // useful to the concurrent marking threads.  Entries are retained if
112 // they require marking and are not already marked. Retained entries
113 // are compacted toward the top of the buffer.
114 
115 void SATBMarkQueue::filter() {
116   G1CollectedHeap* g1h = G1CollectedHeap::heap();
117   void** buf = _buf;
118 
119   if (buf == NULL) {
120     // nothing to do
121     return;
122   }
123 
124   // Two-fingered compaction toward the end.
125   void** src = &buf[index()];
126   void** dst = &buf[capacity()];
127   assert(src <= dst, "invariant");
128   for ( ; src < dst; ++src) {
129     // Search low to high for an entry to keep.
130     void* entry = *src;
131     if (retain_entry(entry, g1h)) {
132       // Found keeper.  Search high to low for an entry to discard.
133       while (src < --dst) {
134         if (!retain_entry(*dst, g1h)) {
135           *dst = entry;         // Replace discard with keeper.
136           break;
137         }
138       }
139       // If discard search failed (src == dst), the outer loop will also end.
140     }
141   }
142   // dst points to the lowest retained entry, or the end of the buffer
143   // if all the entries were filtered out.
144   set_index(dst - buf);
145 }
146 
147 // This method will first apply the above filtering to the buffer. If
148 // post-filtering a large enough chunk of the buffer has been cleared
149 // we can re-use the buffer (instead of enqueueing it) and we can just
150 // allow the mutator to carry on executing using the same buffer
151 // instead of replacing it.
152 
153 bool SATBMarkQueue::should_enqueue_buffer() {
154   assert(_lock == NULL || _lock->owned_by_self(),
155          "we should have taken the lock before calling this");
156 
157   // If G1SATBBufferEnqueueingThresholdPercent == 0 we could skip filtering.
158 
159   // This method should only be called if there is a non-NULL buffer
160   // that is full.
161   assert(index() == 0, "pre-condition");
162   assert(_buf != NULL, "pre-condition");
163 
164   filter();
165 
166   size_t cap = capacity();
167   size_t percent_used = ((cap - index()) * 100) / cap;
168   bool should_enqueue = percent_used > G1SATBBufferEnqueueingThresholdPercent;
169   return should_enqueue;
170 }
171 
172 void SATBMarkQueue::apply_closure_and_empty(SATBBufferClosure* cl) {
173   assert(SafepointSynchronize::is_at_safepoint(),
174          "SATB queues must only be processed at safepoints");
175   if (_buf != NULL) {
176     cl->do_buffer(&_buf[index()], size());
177     reset();
178   }
179 }
180 
181 #ifndef PRODUCT
182 // Helpful for debugging
183 
184 static void print_satb_buffer(const char* name,
185                               void** buf,
186                               size_t index,
187                               size_t capacity) {
188   tty->print_cr("  SATB BUFFER [%s] buf: " PTR_FORMAT " index: " SIZE_FORMAT
189                 " capacity: " SIZE_FORMAT,
190                 name, p2i(buf), index, capacity);
191 }
192 
193 void SATBMarkQueue::print(const char* name) {
194   print_satb_buffer(name, _buf, index(), capacity());
195 }
196 
197 #endif // PRODUCT
198 
199 SATBMarkQueueSet::SATBMarkQueueSet() :
200   PtrQueueSet(),
201   _shared_satb_queue(this, true /* permanent */) { }
202 
203 void SATBMarkQueueSet::initialize(Monitor* cbl_mon, Mutex* fl_lock,
204                                   int process_completed_threshold,
205                                   Mutex* lock) {
206   PtrQueueSet::initialize(cbl_mon, fl_lock, process_completed_threshold, -1);
207   _shared_satb_queue.set_lock(lock);
208 }
209 
210 void SATBMarkQueueSet::handle_zero_index_for_thread(JavaThread* t) {
211   t->satb_mark_queue().handle_zero_index();
212 }
213 
214 #ifdef ASSERT
215 void SATBMarkQueueSet::dump_active_states(bool expected_active) {
216   log_error(gc, verify)("Expected SATB active state: %s", expected_active ? "ACTIVE" : "INACTIVE");
217   log_error(gc, verify)("Actual SATB active states:");
218   log_error(gc, verify)("  Queue set: %s", is_active() ? "ACTIVE" : "INACTIVE");
219   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
220     log_error(gc, verify)("  Thread \"%s\" queue: %s", t->name(), t->satb_mark_queue().is_active() ? "ACTIVE" : "INACTIVE");
221   }
222   log_error(gc, verify)("  Shared queue: %s", shared_satb_queue()->is_active() ? "ACTIVE" : "INACTIVE");
223 }
224 
225 void SATBMarkQueueSet::verify_active_states(bool expected_active) {
226   // Verify queue set state
227   if (is_active() != expected_active) {
228     dump_active_states(expected_active);
229     guarantee(false, "SATB queue set has an unexpected active state");
230   }
231 
232   // Verify thread queue states
233   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
234     if (t->satb_mark_queue().is_active() != expected_active) {
235       dump_active_states(expected_active);
236       guarantee(false, "Thread SATB queue has an unexpected active state");
237     }
238   }
239 
240   // Verify shared queue state
241   if (shared_satb_queue()->is_active() != expected_active) {
242     dump_active_states(expected_active);
243     guarantee(false, "Shared SATB queue has an unexpected active state");
244   }
245 }
246 #endif // ASSERT
247 
248 void SATBMarkQueueSet::set_active_all_threads(bool active, bool expected_active) {
249   assert(SafepointSynchronize::is_at_safepoint(), "Must be at safepoint.");
250 #ifdef ASSERT
251   verify_active_states(expected_active);
252 #endif // ASSERT
253   _all_active = active;
254   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
255     t->satb_mark_queue().set_active(active);
256   }
257   shared_satb_queue()->set_active(active);
258 }
259 
260 void SATBMarkQueueSet::filter_thread_buffers() {
261   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
262     t->satb_mark_queue().filter();
263   }
264   shared_satb_queue()->filter();
265 }
266 
267 bool SATBMarkQueueSet::apply_closure_to_completed_buffer(SATBBufferClosure* cl) {
268   BufferNode* nd = NULL;
269   {
270     MutexLockerEx x(_cbl_mon, Mutex::_no_safepoint_check_flag);
271     if (_completed_buffers_head != NULL) {
272       nd = _completed_buffers_head;
273       _completed_buffers_head = nd->next();
274       if (_completed_buffers_head == NULL) _completed_buffers_tail = NULL;
275       _n_completed_buffers--;
276       if (_n_completed_buffers == 0) _process_completed = false;
277     }
278   }
279   if (nd != NULL) {
280     void **buf = BufferNode::make_buffer_from_node(nd);
281     size_t index = nd->index();
282     size_t size = buffer_size();
283     assert(index <= size, "invariant");
284     cl->do_buffer(buf + index, size - index);
285     deallocate_buffer(nd);
286     return true;
287   } else {
288     return false;
289   }
290 }
291 
292 #ifndef PRODUCT
293 // Helpful for debugging
294 
295 #define SATB_PRINTER_BUFFER_SIZE 256
296 
297 void SATBMarkQueueSet::print_all(const char* msg) {
298   char buffer[SATB_PRINTER_BUFFER_SIZE];
299   assert(SafepointSynchronize::is_at_safepoint(), "Must be at safepoint.");
300 
301   tty->cr();
302   tty->print_cr("SATB BUFFERS [%s]", msg);
303 
304   BufferNode* nd = _completed_buffers_head;
305   int i = 0;
306   while (nd != NULL) {
307     void** buf = BufferNode::make_buffer_from_node(nd);
308     jio_snprintf(buffer, SATB_PRINTER_BUFFER_SIZE, "Enqueued: %d", i);
309     print_satb_buffer(buffer, buf, nd->index(), buffer_size());
310     nd = nd->next();
311     i += 1;
312   }
313 
314   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
315     jio_snprintf(buffer, SATB_PRINTER_BUFFER_SIZE, "Thread: %s", t->name());
316     t->satb_mark_queue().print(buffer);
317   }
318 
319   shared_satb_queue()->print("Shared");
320 
321   tty->cr();
322 }
323 #endif // PRODUCT
324 
325 void SATBMarkQueueSet::abandon_partial_marking() {
326   BufferNode* buffers_to_delete = NULL;
327   {
328     MutexLockerEx x(_cbl_mon, Mutex::_no_safepoint_check_flag);
329     while (_completed_buffers_head != NULL) {
330       BufferNode* nd = _completed_buffers_head;
331       _completed_buffers_head = nd->next();
332       nd->set_next(buffers_to_delete);
333       buffers_to_delete = nd;
334     }
335     _completed_buffers_tail = NULL;
336     _n_completed_buffers = 0;
337     DEBUG_ONLY(assert_completed_buffer_list_len_correct_locked());
338   }
339   while (buffers_to_delete != NULL) {
340     BufferNode* nd = buffers_to_delete;
341     buffers_to_delete = nd->next();
342     deallocate_buffer(nd);
343   }
344   assert(SafepointSynchronize::is_at_safepoint(), "Must be at safepoint.");
345   // So we can safely manipulate these queues.
346   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
347     t->satb_mark_queue().reset();
348   }
349   shared_satb_queue()->reset();
350 }