1 /*
   2  * Copyright (c) 2001, 2017, 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 "gc/g1/dirtyCardQueue.hpp"
  27 #include "gc/g1/g1CollectedHeap.inline.hpp"
  28 #include "gc/g1/g1RemSet.hpp"
  29 #include "gc/g1/heapRegionRemSet.hpp"
  30 #include "gc/shared/workgroup.hpp"
  31 #include "runtime/atomic.hpp"
  32 #include "runtime/mutexLocker.hpp"
  33 #include "runtime/safepoint.hpp"
  34 #include "runtime/thread.inline.hpp"
  35 #include "runtime/threadSMR.hpp"
  36 
  37 // Closure used for updating remembered sets and recording references that
  38 // point into the collection set while the mutator is running.
  39 // Assumed to be only executed concurrently with the mutator. Yields via
  40 // SuspendibleThreadSet after every card.
  41 class G1RefineCardConcurrentlyClosure: public CardTableEntryClosure {
  42 public:
  43   bool do_card_ptr(jbyte* card_ptr, uint worker_i) {
  44     G1CollectedHeap::heap()->g1_rem_set()->refine_card_concurrently(card_ptr, worker_i);
  45 
  46     if (SuspendibleThreadSet::should_yield()) {
  47       // Caller will actually yield.
  48       return false;
  49     }
  50     // Otherwise, we finished successfully; return true.
  51     return true;
  52   }
  53 };
  54 
  55 // Represents a set of free small integer ids.
  56 class FreeIdSet : public CHeapObj<mtGC> {
  57   enum {
  58     end_of_list = UINT_MAX,
  59     claimed = UINT_MAX - 1
  60   };
  61 
  62   uint _size;
  63   Monitor* _mon;
  64 
  65   uint* _ids;
  66   uint _hd;
  67   uint _waiters;
  68   uint _claimed;
  69 
  70 public:
  71   FreeIdSet(uint size, Monitor* mon);
  72   ~FreeIdSet();
  73 
  74   // Returns an unclaimed parallel id (waiting for one to be released if
  75   // necessary).
  76   uint claim_par_id();
  77 
  78   void release_par_id(uint id);
  79 };
  80 
  81 FreeIdSet::FreeIdSet(uint size, Monitor* mon) :
  82   _size(size), _mon(mon), _hd(0), _waiters(0), _claimed(0)
  83 {
  84   guarantee(size != 0, "must be");
  85   _ids = NEW_C_HEAP_ARRAY(uint, size, mtGC);
  86   for (uint i = 0; i < size - 1; i++) {
  87     _ids[i] = i+1;
  88   }
  89   _ids[size-1] = end_of_list; // end of list.
  90 }
  91 
  92 FreeIdSet::~FreeIdSet() {
  93   FREE_C_HEAP_ARRAY(uint, _ids);
  94 }
  95 
  96 uint FreeIdSet::claim_par_id() {
  97   MutexLockerEx x(_mon, Mutex::_no_safepoint_check_flag);
  98   while (_hd == end_of_list) {
  99     _waiters++;
 100     _mon->wait(Mutex::_no_safepoint_check_flag);
 101     _waiters--;
 102   }
 103   uint res = _hd;
 104   _hd = _ids[res];
 105   _ids[res] = claimed;  // For debugging.
 106   _claimed++;
 107   return res;
 108 }
 109 
 110 void FreeIdSet::release_par_id(uint id) {
 111   MutexLockerEx x(_mon, Mutex::_no_safepoint_check_flag);
 112   assert(_ids[id] == claimed, "Precondition.");
 113   _ids[id] = _hd;
 114   _hd = id;
 115   _claimed--;
 116   if (_waiters > 0) {
 117     _mon->notify_all();
 118   }
 119 }
 120 
 121 DirtyCardQueue::DirtyCardQueue(DirtyCardQueueSet* qset, bool permanent) :
 122   // Dirty card queues are always active, so we create them with their
 123   // active field set to true.
 124   PtrQueue(qset, permanent, true /* active */)
 125 { }
 126 
 127 DirtyCardQueue::~DirtyCardQueue() {
 128   if (!is_permanent()) {
 129     flush();
 130   }
 131 }
 132 
 133 DirtyCardQueueSet::DirtyCardQueueSet(bool notify_when_complete) :
 134   PtrQueueSet(notify_when_complete),
 135   _shared_dirty_card_queue(this, true /* permanent */),
 136   _free_ids(NULL),
 137   _processed_buffers_mut(0), _processed_buffers_rs_thread(0)
 138 {
 139   _all_active = true;
 140 }
 141 
 142 // Determines how many mutator threads can process the buffers in parallel.
 143 uint DirtyCardQueueSet::num_par_ids() {
 144   return (uint)os::initial_active_processor_count();
 145 }
 146 
 147 void DirtyCardQueueSet::initialize(Monitor* cbl_mon,
 148                                    Mutex* fl_lock,
 149                                    int process_completed_threshold,
 150                                    int max_completed_queue,
 151                                    Mutex* lock,
 152                                    DirtyCardQueueSet* fl_owner,
 153                                    bool init_free_ids) {
 154   PtrQueueSet::initialize(cbl_mon,
 155                           fl_lock,
 156                           process_completed_threshold,
 157                           max_completed_queue,
 158                           fl_owner);
 159   set_buffer_size(G1UpdateBufferSize);
 160   _shared_dirty_card_queue.set_lock(lock);
 161   if (init_free_ids) {
 162     _free_ids = new FreeIdSet(num_par_ids(), _cbl_mon);
 163   }
 164 }
 165 
 166 void DirtyCardQueueSet::handle_zero_index_for_thread(JavaThread* t) {
 167   t->dirty_card_queue().handle_zero_index();
 168 }
 169 
 170 bool DirtyCardQueueSet::apply_closure_to_buffer(CardTableEntryClosure* cl,
 171                                                 BufferNode* node,
 172                                                 bool consume,
 173                                                 uint worker_i) {
 174   if (cl == NULL) return true;
 175   bool result = true;
 176   void** buf = BufferNode::make_buffer_from_node(node);
 177   size_t i = node->index();
 178   size_t limit = buffer_size();
 179   for ( ; i < limit; ++i) {
 180     jbyte* card_ptr = static_cast<jbyte*>(buf[i]);
 181     assert(card_ptr != NULL, "invariant");
 182     if (!cl->do_card_ptr(card_ptr, worker_i)) {
 183       result = false;           // Incomplete processing.
 184       break;
 185     }
 186   }
 187   if (consume) {
 188     assert(i <= buffer_size(), "invariant");
 189     node->set_index(i);
 190   }
 191   return result;
 192 }
 193 
 194 #ifndef ASSERT
 195 #define assert_fully_consumed(node, buffer_size)
 196 #else
 197 #define assert_fully_consumed(node, buffer_size)                \
 198   do {                                                          \
 199     size_t _afc_index = (node)->index();                        \
 200     size_t _afc_size = (buffer_size);                           \
 201     assert(_afc_index == _afc_size,                             \
 202            "Buffer was not fully consumed as claimed: index: "  \
 203            SIZE_FORMAT ", size: " SIZE_FORMAT,                  \
 204             _afc_index, _afc_size);                             \
 205   } while (0)
 206 #endif // ASSERT
 207 
 208 bool DirtyCardQueueSet::mut_process_buffer(BufferNode* node) {
 209   guarantee(_free_ids != NULL, "must be");
 210 
 211   uint worker_i = _free_ids->claim_par_id(); // temporarily claim an id
 212   G1RefineCardConcurrentlyClosure cl;
 213   bool result = apply_closure_to_buffer(&cl, node, true, worker_i);
 214   _free_ids->release_par_id(worker_i); // release the id
 215 
 216   if (result) {
 217     assert_fully_consumed(node, buffer_size());
 218     Atomic::inc(&_processed_buffers_mut);
 219   }
 220   return result;
 221 }
 222 
 223 
 224 BufferNode* DirtyCardQueueSet::get_completed_buffer(size_t stop_at) {
 225   BufferNode* nd = NULL;
 226   MutexLockerEx x(_cbl_mon, Mutex::_no_safepoint_check_flag);
 227 
 228   if (_n_completed_buffers <= stop_at) {
 229     _process_completed = false;
 230     return NULL;
 231   }
 232 
 233   if (_completed_buffers_head != NULL) {
 234     nd = _completed_buffers_head;
 235     assert(_n_completed_buffers > 0, "Invariant");
 236     _completed_buffers_head = nd->next();
 237     _n_completed_buffers--;
 238     if (_completed_buffers_head == NULL) {
 239       assert(_n_completed_buffers == 0, "Invariant");
 240       _completed_buffers_tail = NULL;
 241     }
 242   }
 243   DEBUG_ONLY(assert_completed_buffer_list_len_correct_locked());
 244   return nd;
 245 }
 246 
 247 bool DirtyCardQueueSet::refine_completed_buffer_concurrently(uint worker_i, size_t stop_at) {
 248   G1RefineCardConcurrentlyClosure cl;
 249   return apply_closure_to_completed_buffer(&cl, worker_i, stop_at, false);
 250 }
 251 
 252 bool DirtyCardQueueSet::apply_closure_during_gc(CardTableEntryClosure* cl, uint worker_i) {
 253   assert_at_safepoint(false);
 254   return apply_closure_to_completed_buffer(cl, worker_i, 0, true);
 255 }
 256 
 257 bool DirtyCardQueueSet::apply_closure_to_completed_buffer(CardTableEntryClosure* cl,
 258                                                           uint worker_i,
 259                                                           size_t stop_at,
 260                                                           bool during_pause) {
 261   assert(!during_pause || stop_at == 0, "Should not leave any completed buffers during a pause");
 262   BufferNode* nd = get_completed_buffer(stop_at);
 263   if (nd == NULL) {
 264     return false;
 265   } else {
 266     if (apply_closure_to_buffer(cl, nd, true, worker_i)) {
 267       assert_fully_consumed(nd, buffer_size());
 268       // Done with fully processed buffer.
 269       deallocate_buffer(nd);
 270       Atomic::inc(&_processed_buffers_rs_thread);
 271     } else {
 272       // Return partially processed buffer to the queue.
 273       guarantee(!during_pause, "Should never stop early");
 274       enqueue_complete_buffer(nd);
 275     }
 276     return true;
 277   }
 278 }
 279 
 280 void DirtyCardQueueSet::par_apply_closure_to_all_completed_buffers(CardTableEntryClosure* cl) {
 281   BufferNode* nd = _cur_par_buffer_node;
 282   while (nd != NULL) {
 283     BufferNode* next = nd->next();
 284     BufferNode* actual = Atomic::cmpxchg(next, &_cur_par_buffer_node, nd);
 285     if (actual == nd) {
 286       bool b = apply_closure_to_buffer(cl, nd, false);
 287       guarantee(b, "Should not stop early.");
 288       nd = next;
 289     } else {
 290       nd = actual;
 291     }
 292   }
 293 }
 294 
 295 // Deallocates any completed log buffers
 296 void DirtyCardQueueSet::clear() {
 297   BufferNode* buffers_to_delete = NULL;
 298   {
 299     MutexLockerEx x(_cbl_mon, Mutex::_no_safepoint_check_flag);
 300     while (_completed_buffers_head != NULL) {
 301       BufferNode* nd = _completed_buffers_head;
 302       _completed_buffers_head = nd->next();
 303       nd->set_next(buffers_to_delete);
 304       buffers_to_delete = nd;
 305     }
 306     _n_completed_buffers = 0;
 307     _completed_buffers_tail = NULL;
 308     DEBUG_ONLY(assert_completed_buffer_list_len_correct_locked());
 309   }
 310   while (buffers_to_delete != NULL) {
 311     BufferNode* nd = buffers_to_delete;
 312     buffers_to_delete = nd->next();
 313     deallocate_buffer(nd);
 314   }
 315 
 316 }
 317 
 318 void DirtyCardQueueSet::abandon_logs() {
 319   assert(SafepointSynchronize::is_at_safepoint(), "Must be at safepoint.");
 320   clear();
 321   // Since abandon is done only at safepoints, we can safely manipulate
 322   // these queues.
 323   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
 324     t->dirty_card_queue().reset();
 325   }
 326   shared_dirty_card_queue()->reset();
 327 }
 328 
 329 void DirtyCardQueueSet::concatenate_log(DirtyCardQueue& dcq) {
 330   if (!dcq.is_empty()) {
 331     dcq.flush();
 332   }
 333 }
 334 
 335 void DirtyCardQueueSet::concatenate_logs() {
 336   // Iterate over all the threads, if we find a partial log add it to
 337   // the global list of logs.  Temporarily turn off the limit on the number
 338   // of outstanding buffers.
 339   int save_max_completed_queue = _max_completed_queue;
 340   _max_completed_queue = max_jint;
 341   assert(SafepointSynchronize::is_at_safepoint(), "Must be at safepoint.");
 342   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
 343     concatenate_log(t->dirty_card_queue());
 344   }
 345   concatenate_log(_shared_dirty_card_queue);
 346   // Restore the completed buffer queue limit.
 347   _max_completed_queue = save_max_completed_queue;
 348 }