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