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