1 /*
   2  * Copyright (c) 2001, 2016, 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/ptrQueue.hpp"
  27 #include "memory/allocation.hpp"
  28 #include "memory/allocation.inline.hpp"
  29 #include "runtime/mutex.hpp"
  30 #include "runtime/mutexLocker.hpp"
  31 #include "runtime/thread.inline.hpp"
  32 
  33 #include <new>
  34 
  35 PtrQueue::PtrQueue(PtrQueueSet* qset, bool permanent, bool active) :
  36   _qset(qset), _buf(NULL), _index(0), _sz(0), _active(active),
  37   _permanent(permanent), _lock(NULL)
  38 {}
  39 
  40 PtrQueue::~PtrQueue() {
  41   assert(_permanent || (_buf == NULL), "queue must be flushed before delete");
  42 }
  43 
  44 void PtrQueue::flush_impl() {
  45   if (!_permanent && _buf != NULL) {
  46     if (_index == _sz) {
  47       // No work to do.
  48       qset()->deallocate_buffer(_buf);
  49     } else {
  50       // We must NULL out the unused entries, then enqueue.
  51       size_t limit = byte_index_to_index(_index);
  52       for (size_t i = 0; i < limit; ++i) {
  53         _buf[i] = NULL;
  54       }
  55       qset()->enqueue_complete_buffer(_buf);
  56     }
  57     _buf = NULL;
  58     _index = 0;
  59   }
  60 }
  61 
  62 
  63 void PtrQueue::enqueue_known_active(void* ptr) {
  64   assert(_index <= _sz, "Invariant.");
  65   assert(_index == 0 || _buf != NULL, "invariant");
  66 
  67   while (_index == 0) {
  68     handle_zero_index();
  69   }
  70 
  71   assert(_index > 0, "postcondition");
  72   _index -= sizeof(void*);
  73   _buf[byte_index_to_index(_index)] = ptr;
  74   assert(_index <= _sz, "Invariant.");
  75 }
  76 
  77 void PtrQueue::locking_enqueue_completed_buffer(void** buf) {
  78   assert(_lock->owned_by_self(), "Required.");
  79 
  80   // We have to unlock _lock (which may be Shared_DirtyCardQ_lock) before
  81   // we acquire DirtyCardQ_CBL_mon inside enqueue_complete_buffer as they
  82   // have the same rank and we may get the "possible deadlock" message
  83   _lock->unlock();
  84 
  85   qset()->enqueue_complete_buffer(buf);
  86   // We must relock only because the caller will unlock, for the normal
  87   // case.
  88   _lock->lock_without_safepoint_check();
  89 }
  90 
  91 
  92 BufferNode* BufferNode::allocate(size_t byte_size) {
  93   assert(byte_size > 0, "precondition");
  94   assert(is_size_aligned(byte_size, sizeof(void**)),
  95          "Invalid buffer size " SIZE_FORMAT, byte_size);
  96   void* data = NEW_C_HEAP_ARRAY(char, buffer_offset() + byte_size, mtGC);
  97   return new (data) BufferNode;
  98 }
  99 
 100 void BufferNode::deallocate(BufferNode* node) {
 101   node->~BufferNode();
 102   FREE_C_HEAP_ARRAY(char, node);
 103 }
 104 
 105 PtrQueueSet::PtrQueueSet(bool notify_when_complete) :
 106   _max_completed_queue(0),
 107   _cbl_mon(NULL), _fl_lock(NULL),
 108   _notify_when_complete(notify_when_complete),
 109   _sz(0),
 110   _completed_buffers_head(NULL),
 111   _completed_buffers_tail(NULL),
 112   _n_completed_buffers(0),
 113   _process_completed_threshold(0), _process_completed(false),
 114   _buf_free_list(NULL), _buf_free_list_sz(0)
 115 {
 116   _fl_owner = this;
 117 }
 118 
 119 PtrQueueSet::~PtrQueueSet() {
 120   // There are presently only a couple (derived) instances ever
 121   // created, and they are permanent, so no harm currently done by
 122   // doing nothing here.
 123 }
 124 
 125 void PtrQueueSet::initialize(Monitor* cbl_mon,
 126                              Mutex* fl_lock,
 127                              int process_completed_threshold,
 128                              int max_completed_queue,
 129                              PtrQueueSet *fl_owner) {
 130   _max_completed_queue = max_completed_queue;
 131   _process_completed_threshold = process_completed_threshold;
 132   _completed_queue_padding = 0;
 133   assert(cbl_mon != NULL && fl_lock != NULL, "Init order issue?");
 134   _cbl_mon = cbl_mon;
 135   _fl_lock = fl_lock;
 136   _fl_owner = (fl_owner != NULL) ? fl_owner : this;
 137 }
 138 
 139 void** PtrQueueSet::allocate_buffer() {
 140   assert(_sz > 0, "Didn't set a buffer size.");
 141   BufferNode* node = NULL;
 142   {
 143     MutexLockerEx x(_fl_owner->_fl_lock, Mutex::_no_safepoint_check_flag);
 144     node = _fl_owner->_buf_free_list;
 145     if (node != NULL) {
 146       _fl_owner->_buf_free_list = node->next();
 147       _fl_owner->_buf_free_list_sz--;
 148     }
 149   }
 150   if (node == NULL) {
 151     node = BufferNode::allocate(_sz);
 152   } else {
 153     // Reinitialize buffer obtained from free list.
 154     node->set_index(0);
 155     node->set_next(NULL);
 156   }
 157   return BufferNode::make_buffer_from_node(node);
 158 }
 159 
 160 void PtrQueueSet::deallocate_buffer(void** buf) {
 161   assert(_sz > 0, "Didn't set a buffer size.");
 162   MutexLockerEx x(_fl_owner->_fl_lock, Mutex::_no_safepoint_check_flag);
 163   BufferNode *node = BufferNode::make_node_from_buffer(buf);
 164   node->set_next(_fl_owner->_buf_free_list);
 165   _fl_owner->_buf_free_list = node;
 166   _fl_owner->_buf_free_list_sz++;
 167 }
 168 
 169 void PtrQueueSet::reduce_free_list() {
 170   assert(_fl_owner == this, "Free list reduction is allowed only for the owner");
 171   // For now we'll adopt the strategy of deleting half.
 172   MutexLockerEx x(_fl_lock, Mutex::_no_safepoint_check_flag);
 173   size_t n = _buf_free_list_sz / 2;
 174   for (size_t i = 0; i < n; ++i) {
 175     assert(_buf_free_list != NULL,
 176            "_buf_free_list_sz is wrong: " SIZE_FORMAT, _buf_free_list_sz);
 177     BufferNode* node = _buf_free_list;
 178     _buf_free_list = node->next();
 179     _buf_free_list_sz--;
 180     BufferNode::deallocate(node);
 181   }
 182 }
 183 
 184 void PtrQueue::handle_zero_index() {
 185   assert(_index == 0, "Precondition.");
 186 
 187   // This thread records the full buffer and allocates a new one (while
 188   // holding the lock if there is one).
 189   if (_buf != NULL) {
 190     if (!should_enqueue_buffer()) {
 191       assert(_index > 0, "the buffer can only be re-used if it's not full");
 192       return;
 193     }
 194 
 195     if (_lock) {
 196       assert(_lock->owned_by_self(), "Required.");
 197 
 198       // The current PtrQ may be the shared dirty card queue and
 199       // may be being manipulated by more than one worker thread
 200       // during a pause. Since the enqueueing of the completed
 201       // buffer unlocks the Shared_DirtyCardQ_lock more than one
 202       // worker thread can 'race' on reading the shared queue attributes
 203       // (_buf and _index) and multiple threads can call into this
 204       // routine for the same buffer. This will cause the completed
 205       // buffer to be added to the CBL multiple times.
 206 
 207       // We "claim" the current buffer by caching value of _buf in
 208       // a local and clearing the field while holding _lock. When
 209       // _lock is released (while enqueueing the completed buffer)
 210       // the thread that acquires _lock will skip this code,
 211       // preventing the subsequent the multiple enqueue, and
 212       // install a newly allocated buffer below.
 213 
 214       void** buf = _buf;   // local pointer to completed buffer
 215       _buf = NULL;         // clear shared _buf field
 216 
 217       locking_enqueue_completed_buffer(buf);  // enqueue completed buffer
 218 
 219       // While the current thread was enqueueing the buffer another thread
 220       // may have a allocated a new buffer and inserted it into this pointer
 221       // queue. If that happens then we just return so that the current
 222       // thread doesn't overwrite the buffer allocated by the other thread
 223       // and potentially losing some dirtied cards.
 224 
 225       if (_buf != NULL) return;
 226     } else {
 227       if (qset()->process_or_enqueue_complete_buffer(_buf)) {
 228         // Recycle the buffer. No allocation.
 229         _sz = qset()->buffer_size();
 230         _index = _sz;
 231         return;
 232       }
 233     }
 234   }
 235   // Reallocate the buffer
 236   _buf = qset()->allocate_buffer();
 237   _sz = qset()->buffer_size();
 238   _index = _sz;
 239 }
 240 
 241 bool PtrQueueSet::process_or_enqueue_complete_buffer(void** buf) {
 242   if (Thread::current()->is_Java_thread()) {
 243     // We don't lock. It is fine to be epsilon-precise here.
 244     if (_max_completed_queue == 0 || _max_completed_queue > 0 &&
 245         _n_completed_buffers >= _max_completed_queue + _completed_queue_padding) {
 246       bool b = mut_process_buffer(buf);
 247       if (b) {
 248         // True here means that the buffer hasn't been deallocated and the caller may reuse it.
 249         return true;
 250       }
 251     }
 252   }
 253   // The buffer will be enqueued. The caller will have to get a new one.
 254   enqueue_complete_buffer(buf);
 255   return false;
 256 }
 257 
 258 void PtrQueueSet::enqueue_complete_buffer(void** buf, size_t index) {
 259   MutexLockerEx x(_cbl_mon, Mutex::_no_safepoint_check_flag);
 260   BufferNode* cbn = BufferNode::make_node_from_buffer(buf);
 261   cbn->set_index(index);
 262   cbn->set_next(NULL);
 263   if (_completed_buffers_tail == NULL) {
 264     assert(_completed_buffers_head == NULL, "Well-formedness");
 265     _completed_buffers_head = cbn;
 266     _completed_buffers_tail = cbn;
 267   } else {
 268     _completed_buffers_tail->set_next(cbn);
 269     _completed_buffers_tail = cbn;
 270   }
 271   _n_completed_buffers++;
 272 
 273   if (!_process_completed && _process_completed_threshold >= 0 &&
 274       _n_completed_buffers >= _process_completed_threshold) {
 275     _process_completed = true;
 276     if (_notify_when_complete)
 277       _cbl_mon->notify();
 278   }
 279   DEBUG_ONLY(assert_completed_buffer_list_len_correct_locked());
 280 }
 281 
 282 int PtrQueueSet::completed_buffers_list_length() {
 283   int n = 0;
 284   BufferNode* cbn = _completed_buffers_head;
 285   while (cbn != NULL) {
 286     n++;
 287     cbn = cbn->next();
 288   }
 289   return n;
 290 }
 291 
 292 void PtrQueueSet::assert_completed_buffer_list_len_correct() {
 293   MutexLockerEx x(_cbl_mon, Mutex::_no_safepoint_check_flag);
 294   assert_completed_buffer_list_len_correct_locked();
 295 }
 296 
 297 void PtrQueueSet::assert_completed_buffer_list_len_correct_locked() {
 298   guarantee(completed_buffers_list_length() ==  _n_completed_buffers,
 299             "Completed buffer length is wrong.");
 300 }
 301 
 302 void PtrQueueSet::set_buffer_size(size_t sz) {
 303   assert(_sz == 0 && sz > 0, "Should be called only once.");
 304   _sz = sz * sizeof(void*);
 305 }
 306 
 307 // Merge lists of buffers. Notify the processing threads.
 308 // The source queue is emptied as a result. The queues
 309 // must share the monitor.
 310 void PtrQueueSet::merge_bufferlists(PtrQueueSet *src) {
 311   assert(_cbl_mon == src->_cbl_mon, "Should share the same lock");
 312   MutexLockerEx x(_cbl_mon, Mutex::_no_safepoint_check_flag);
 313   if (_completed_buffers_tail == NULL) {
 314     assert(_completed_buffers_head == NULL, "Well-formedness");
 315     _completed_buffers_head = src->_completed_buffers_head;
 316     _completed_buffers_tail = src->_completed_buffers_tail;
 317   } else {
 318     assert(_completed_buffers_head != NULL, "Well formedness");
 319     if (src->_completed_buffers_head != NULL) {
 320       _completed_buffers_tail->set_next(src->_completed_buffers_head);
 321       _completed_buffers_tail = src->_completed_buffers_tail;
 322     }
 323   }
 324   _n_completed_buffers += src->_n_completed_buffers;
 325 
 326   src->_n_completed_buffers = 0;
 327   src->_completed_buffers_head = NULL;
 328   src->_completed_buffers_tail = NULL;
 329 
 330   assert(_completed_buffers_head == NULL && _completed_buffers_tail == NULL ||
 331          _completed_buffers_head != NULL && _completed_buffers_tail != NULL,
 332          "Sanity");
 333 }
 334 
 335 void PtrQueueSet::notify_if_necessary() {
 336   MutexLockerEx x(_cbl_mon, Mutex::_no_safepoint_check_flag);
 337   if (_n_completed_buffers >= _process_completed_threshold || _max_completed_queue == 0) {
 338     _process_completed = true;
 339     if (_notify_when_complete)
 340       _cbl_mon->notify();
 341   }
 342 }