1 /*
   2  * Copyright (c) 2012, 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 "jfr/jni/jfrJavaSupport.hpp"
  27 #include "jfr/recorder/jfrRecorder.hpp"
  28 #include "jfr/recorder/access/jfrOptionSet.hpp"
  29 #include "jfr/recorder/repository/jfrChunkWriter.hpp"
  30 #include "jfr/recorder/service/jfrPostBox.hpp"
  31 #include "jfr/recorder/storage/jfrMemorySpace.inline.hpp"
  32 #include "jfr/recorder/storage/jfrStorage.hpp"
  33 #include "jfr/recorder/storage/jfrStorageControl.hpp"
  34 #include "jfr/recorder/storage/jfrStorageUtils.inline.hpp"
  35 #include "jfr/utilities/jfrIterator.hpp"
  36 #include "logging/log.hpp"
  37 
  38 #include "runtime/mutexLocker.hpp"
  39 #include "runtime/orderAccess.inline.hpp"
  40 #include "runtime/safepoint.hpp"
  41 #include "runtime/thread.hpp"
  42 #include "trace/tracing.hpp"
  43 
  44 typedef JfrStorage::Buffer* BufferPtr;
  45 
  46 static JfrStorage* _instance = NULL;
  47 static JfrStorageControl* _control;
  48 
  49 JfrStorage& JfrStorage::instance() {
  50   return *_instance;
  51 }
  52 
  53 JfrStorage* JfrStorage::create(JfrChunkWriter& chunkwriter, JfrPostBox& post_box) {
  54   assert(_instance == NULL, "invariant");
  55   _instance = new JfrStorage(chunkwriter, post_box);
  56   return _instance;
  57 }
  58 
  59 void JfrStorage::destroy() {
  60   if (_instance != NULL) {
  61     delete _instance;
  62     _instance = NULL;
  63   }
  64 }
  65 
  66 JfrStorage::JfrStorage(JfrChunkWriter& chunkwriter, JfrPostBox& post_box) :
  67   _control(NULL),
  68   _global_mspace(NULL),
  69   _thread_local_mspace(NULL),
  70   _transient_mspace(NULL),
  71   _age_mspace(NULL),
  72   _chunkwriter(chunkwriter),
  73   _post_box(post_box) {}
  74 
  75 JfrStorage::~JfrStorage() {
  76   if (_control != NULL) {
  77     delete _control;
  78   }
  79   if (_global_mspace != NULL) {
  80     delete _global_mspace;
  81   }
  82   if (_thread_local_mspace != NULL) {
  83     delete _thread_local_mspace;
  84   }
  85   if (_transient_mspace != NULL) {
  86     delete _transient_mspace;
  87   }
  88   if (_age_mspace != NULL) {
  89     delete _age_mspace;
  90   }
  91   _instance = NULL;
  92 }
  93 
  94 static const size_t in_memory_discard_threshold_delta = 2; // start to discard data when the only this number of free buffers are left
  95 static const size_t unlimited_mspace_size = 0;
  96 static const size_t thread_local_cache_count = 8;
  97 static const size_t thread_local_scavenge_threshold = thread_local_cache_count / 2;
  98 static const size_t transient_buffer_size_multiplier = 8; // against thread local buffer size
  99 
 100 static JfrStorageMspace* create_mspace(size_t buffer_size, size_t limit, size_t cache_count, JfrStorage* storage_instance) {
 101   JfrStorageMspace* mspace = new JfrStorageMspace(buffer_size, limit, cache_count, storage_instance);
 102   if (mspace != NULL) {
 103     mspace->initialize();
 104   }
 105   return mspace;
 106 }
 107 
 108 bool JfrStorage::initialize() {
 109   assert(_control == NULL, "invariant");
 110   assert(_global_mspace == NULL, "invariant");
 111   assert(_thread_local_mspace == NULL, "invariant");
 112   assert(_transient_mspace == NULL, "invariant");
 113   assert(_age_mspace == NULL, "invariant");
 114 
 115   const size_t num_global_buffers = (size_t)JfrOptionSet::num_global_buffers();
 116   assert(num_global_buffers >= in_memory_discard_threshold_delta, "invariant");
 117   const size_t memory_size = (size_t)JfrOptionSet::memory_size();
 118   const size_t global_buffer_size = (size_t)JfrOptionSet::global_buffer_size();
 119   const size_t thread_buffer_size = (size_t)JfrOptionSet::thread_buffer_size();
 120 
 121   _control = new JfrStorageControl(num_global_buffers, num_global_buffers - in_memory_discard_threshold_delta);
 122   if (_control == NULL) {
 123     return false;
 124   }
 125   _global_mspace = create_mspace(global_buffer_size, memory_size, num_global_buffers, this);
 126   if (_global_mspace == NULL) {
 127     return false;
 128   }
 129   _thread_local_mspace = create_mspace(thread_buffer_size, unlimited_mspace_size, thread_local_cache_count, this);
 130   if (_thread_local_mspace == NULL) {
 131     return false;
 132   }
 133   _transient_mspace = create_mspace(thread_buffer_size * transient_buffer_size_multiplier, unlimited_mspace_size, 0, this);
 134   if (_transient_mspace == NULL) {
 135     return false;
 136   }
 137   _age_mspace = new JfrStorageAgeMspace(0 /* no extra size except header */, unlimited_mspace_size, num_global_buffers, this);
 138 
 139   if (_age_mspace == NULL || !_age_mspace->initialize()) {
 140     return false;
 141   }
 142   control().set_scavenge_threshold(thread_local_scavenge_threshold);
 143   return true;
 144 }
 145 
 146 JfrStorageControl& JfrStorage::control() {
 147   return *instance()._control;
 148 }
 149 
 150 static void log_allocation_failure(const char* msg, size_t size) {
 151   log_warning(jfr)("Unable to allocate " SIZE_FORMAT " bytes of %s.", size, msg);
 152 }
 153 
 154 BufferPtr JfrStorage::acquire_thread_local(Thread* thread, size_t size /* 0 */) {
 155   BufferPtr buffer = mspace_get_to_full(size, instance()._thread_local_mspace, thread);
 156   if (buffer == NULL) {
 157     log_allocation_failure("thread local_memory", size);
 158     return NULL;
 159   }
 160   assert(buffer->acquired_by_self(), "invariant");
 161   return buffer;
 162 }
 163 
 164 BufferPtr JfrStorage::acquire_transient(size_t size, Thread* thread) {
 165   BufferPtr buffer = mspace_allocate_transient_lease_to_full(size, instance()._transient_mspace, thread);
 166   if (buffer == NULL) {
 167     log_allocation_failure("transient memory", size);
 168     return NULL;
 169   }
 170   assert(buffer->acquired_by_self(), "invariant");
 171   assert(buffer->transient(), "invariant");
 172   assert(buffer->lease(), "invariant");
 173   return buffer;
 174 }
 175 
 176 static BufferPtr get_lease(size_t size, JfrStorageMspace* mspace, JfrStorage& storage_instance, size_t retry_count, Thread* thread) {
 177   assert(size <= mspace->min_elem_size(), "invariant");
 178   while (true) {
 179     BufferPtr t = mspace_get_free_lease_with_retry(size, mspace, retry_count, thread);
 180     if (t == NULL && storage_instance.control().should_discard()) {
 181       storage_instance.discard_oldest(thread);
 182       continue;
 183     }
 184     return t;
 185   }
 186 }
 187 
 188 static BufferPtr get_promotion_buffer(size_t size, JfrStorageMspace* mspace, JfrStorage& storage_instance, size_t retry_count, Thread* thread) {
 189   assert(size <= mspace->min_elem_size(), "invariant");
 190   while (true) {
 191     BufferPtr t = mspace_get_free_with_retry(size, mspace, retry_count, thread);
 192     if (t == NULL && storage_instance.control().should_discard()) {
 193       storage_instance.discard_oldest(thread);
 194       continue;
 195     }
 196     return t;
 197   }
 198 }
 199 
 200 static const size_t lease_retry = 10;
 201 
 202 BufferPtr JfrStorage::acquire_large(size_t size, Thread* thread) {
 203   JfrStorage& storage_instance = instance();
 204   const size_t max_elem_size = storage_instance._global_mspace->min_elem_size(); // min is also max
 205   // if not too large and capacity is still available, ask for a lease from the global system
 206   if (size < max_elem_size && storage_instance.control().is_global_lease_allowed()) {
 207     BufferPtr const buffer = get_lease(size, storage_instance._global_mspace, storage_instance, lease_retry, thread);
 208     if (buffer != NULL) {
 209       assert(buffer->acquired_by_self(), "invariant");
 210       assert(!buffer->transient(), "invariant");
 211       assert(buffer->lease(), "invariant");
 212       storage_instance.control().increment_leased();
 213       return buffer;
 214     }
 215   }
 216   return acquire_transient(size, thread);
 217 }
 218 
 219 static void write_data_loss_event(size_t unflushed_size, Thread* thread) {
 220   const u8 total_data_loss = thread->trace_data()->add_data_lost(unflushed_size);
 221   if (EventDataLoss::is_enabled()) {
 222     EventDataLoss dataloss;
 223     dataloss.set_amount(unflushed_size);
 224     dataloss.set_total(total_data_loss);
 225     dataloss.commit();
 226   }
 227 }
 228 
 229 static void write_data_loss(BufferPtr buffer, Thread* thread) {
 230   assert(buffer != NULL, "invariant");
 231   const size_t unflushed_size = buffer->unflushed_size();
 232   buffer->concurrent_reinitialization();
 233   if (unflushed_size == 0) {
 234     return;
 235   }
 236   assert(buffer->empty(), "invariant");
 237   write_data_loss_event(unflushed_size, thread);
 238 }
 239 
 240 static const size_t promotion_retry = 100;
 241 
 242 bool JfrStorage::flush_regular_buffer(BufferPtr buffer, Thread* thread) {
 243   assert(buffer != NULL, "invariant");
 244   assert(!buffer->lease(), "invariant");
 245   assert(!buffer->transient(), "invariant");
 246   const size_t unflushed_size = buffer->unflushed_size();
 247   if (unflushed_size == 0) {
 248     buffer->concurrent_reinitialization();
 249     assert(buffer->empty(), "invariant");
 250     return true;
 251   }
 252   BufferPtr const promotion_buffer = get_promotion_buffer(unflushed_size, _global_mspace, *this, promotion_retry, thread);
 253   if (promotion_buffer == NULL) {
 254     write_data_loss(buffer, thread);
 255     return false;
 256   }
 257   assert(promotion_buffer->acquired_by_self(), "invariant");
 258   assert(promotion_buffer->free_size() >= unflushed_size, "invariant");
 259   buffer->concurrent_move_and_reinitialize(promotion_buffer, unflushed_size);
 260   assert(buffer->empty(), "invariant");
 261   return true;
 262 }
 263 
 264 /*
 265 * 1. If the buffer was a "lease" from the global system, release back.
 266 * 2. If the buffer is transient (temporal dynamically allocated), retire and register full.
 267 *
 268 * The buffer is effectively invalidated for the thread post-return,
 269 * and the caller should take means to ensure that it is not referenced any longer.
 270 */
 271 void JfrStorage::release_large(BufferPtr buffer, Thread* thread) {
 272   assert(buffer != NULL, "invariant");
 273   assert(buffer->lease(), "invariant");
 274   assert(buffer->acquired_by_self(), "invariant");
 275   buffer->clear_lease();
 276   if (buffer->transient()) {
 277     buffer->set_retired();
 278     register_full(buffer, thread);
 279   } else {
 280     buffer->release();
 281     control().decrement_leased();
 282   }
 283 }
 284 
 285 static JfrAgeNode* new_age_node(BufferPtr buffer, JfrStorageAgeMspace* age_mspace, Thread* thread) {
 286   assert(buffer != NULL, "invariant");
 287   assert(age_mspace != NULL, "invariant");
 288   return mspace_allocate_transient(0, age_mspace, thread);
 289 }
 290 
 291 static void log_registration_failure(size_t unflushed_size) {
 292   log_warning(jfr)("Unable to register a full buffer of " SIZE_FORMAT " bytes.", unflushed_size);
 293   log_debug(jfr, system)("Cleared 1 full buffer of " SIZE_FORMAT " bytes.", unflushed_size);
 294 }
 295 
 296 static void handle_registration_failure(BufferPtr buffer) {
 297   assert(buffer != NULL, "invariant");
 298   assert(buffer->retired(), "invariant");
 299   const size_t unflushed_size = buffer->unflushed_size();
 300   buffer->reinitialize();
 301   log_registration_failure(unflushed_size);
 302 }
 303 
 304 static JfrAgeNode* get_free_age_node(JfrStorageAgeMspace* age_mspace, Thread* thread) {
 305   assert(JfrBuffer_lock->owned_by_self(), "invariant");
 306   return mspace_get_free_with_detach(0, age_mspace, thread);
 307 }
 308 
 309 static bool insert_full_age_node(JfrAgeNode* age_node, JfrStorageAgeMspace* age_mspace, Thread* thread) {
 310   assert(JfrBuffer_lock->owned_by_self(), "invariant");
 311   assert(age_node->retired_buffer()->retired(), "invariant");
 312   age_mspace->insert_full_head(age_node);
 313   return true;
 314 }
 315 
 316 static bool full_buffer_registration(BufferPtr buffer, JfrStorageAgeMspace* age_mspace, JfrStorageControl& control, Thread* thread) {
 317   assert(buffer != NULL, "invariant");
 318   assert(buffer->retired(), "invariant");
 319   assert(age_mspace != NULL, "invariant");
 320   MutexLockerEx lock(JfrBuffer_lock, Mutex::_no_safepoint_check_flag);
 321   JfrAgeNode* age_node = get_free_age_node(age_mspace, thread);
 322   if (age_node == NULL) {
 323     age_node = new_age_node(buffer, age_mspace, thread);
 324     if (age_node == NULL) {
 325       return false;
 326     }
 327   }
 328   assert(age_node->acquired_by_self(), "invariant");
 329   assert(age_node != NULL, "invariant");
 330   age_node->set_retired_buffer(buffer);
 331   return insert_full_age_node(age_node, age_mspace, thread);
 332 }
 333 
 334 void JfrStorage::register_full(BufferPtr buffer, Thread* thread) {
 335   assert(buffer != NULL, "invariant");
 336   assert(buffer->retired(), "invariant");
 337   if (!full_buffer_registration(buffer, _age_mspace, control(), thread)) {
 338     handle_registration_failure(buffer);
 339     buffer->release();
 340   }
 341   if (control().should_post_buffer_full_message()) {
 342     _post_box.post(MSG_FULLBUFFER);
 343   }
 344 }
 345 
 346 void JfrStorage::lock() {
 347   assert(!JfrBuffer_lock->owned_by_self(), "invariant");
 348   JfrBuffer_lock->lock_without_safepoint_check();
 349 }
 350 
 351 void JfrStorage::unlock() {
 352   assert(JfrBuffer_lock->owned_by_self(), "invariant");
 353   JfrBuffer_lock->unlock();
 354 }
 355 
 356 // don't use buffer on return, it is gone
 357 void JfrStorage::release(BufferPtr buffer, Thread* thread) {
 358   assert(buffer != NULL, "invariant");
 359   assert(!buffer->lease(), "invariant");
 360   assert(!buffer->transient(), "invariant");
 361   assert(!buffer->retired(), "invariant");
 362   if (!buffer->empty()) {
 363     if (!flush_regular_buffer(buffer, thread)) {
 364       buffer->concurrent_reinitialization();
 365     }
 366   }
 367   assert(buffer->empty(), "invariant");
 368   control().increment_dead();
 369   buffer->release();
 370   buffer->set_retired();
 371 }
 372 
 373 void JfrStorage::release_thread_local(BufferPtr buffer, Thread* thread) {
 374   assert(buffer != NULL, "invariant");
 375   JfrStorage& storage_instance = instance();
 376   storage_instance.release(buffer, thread);
 377   if (storage_instance.control().should_scavenge()) {
 378     storage_instance._post_box.post(MSG_DEADBUFFER);
 379   }
 380 }
 381 
 382 static void log_discard(size_t count, size_t amount, size_t current) {
 383   if (log_is_enabled(Debug, jfr, system)) {
 384     assert(count > 0, "invariant");
 385     log_debug(jfr, system)("Cleared " SIZE_FORMAT " full buffer(s) of " SIZE_FORMAT" bytes.", count, amount);
 386     log_debug(jfr, system)("Current number of full buffers " SIZE_FORMAT "", current);
 387   }
 388 }
 389 
 390 void JfrStorage::discard_oldest(Thread* thread) {
 391   if (JfrBuffer_lock->try_lock()) {
 392     if (!control().should_discard()) {
 393       // another thread handled it
 394       return;
 395     }
 396     const size_t num_full_pre_discard = control().full_count();
 397     size_t num_full_post_discard = 0;
 398     size_t discarded_size = 0;
 399     while (true) {
 400       JfrAgeNode* const oldest_age_node = _age_mspace->full_tail();
 401       if (oldest_age_node == NULL) {
 402         break;
 403       }
 404       BufferPtr const buffer = oldest_age_node->retired_buffer();
 405       assert(buffer->retired(), "invariant");
 406       discarded_size += buffer->unflushed_size();
 407       num_full_post_discard = control().decrement_full();
 408       if (buffer->transient()) {
 409         mspace_release(buffer, _transient_mspace);
 410         mspace_release(oldest_age_node, _age_mspace);
 411         continue;
 412       } else {
 413         mspace_release(oldest_age_node, _age_mspace);
 414         buffer->reinitialize();
 415         buffer->release(); // pusb
 416         break;
 417       }
 418     }
 419     JfrBuffer_lock->unlock();
 420     const size_t number_of_discards = num_full_pre_discard - num_full_post_discard;
 421     if (number_of_discards > 0) {
 422       log_discard(number_of_discards, discarded_size, num_full_post_discard);
 423     }
 424   }
 425 }
 426 
 427 #ifdef ASSERT
 428 typedef const BufferPtr ConstBufferPtr;
 429 
 430 static void assert_flush_precondition(ConstBufferPtr cur, size_t used, bool native, const Thread* t) {
 431   assert(t != NULL, "invariant");
 432   assert(cur != NULL, "invariant");
 433   assert(cur->pos() + used <= cur->end(), "invariant");
 434   assert(native ? t->trace_data()->native_buffer() == cur : t->trace_data()->java_buffer() == cur, "invariant");
 435 }
 436 
 437 static void assert_flush_regular_precondition(ConstBufferPtr cur, const u1* const cur_pos, size_t used, size_t req, const Thread* t) {
 438   assert(t != NULL, "invariant");
 439   assert(t->trace_data()->shelved_buffer() == NULL, "invariant");
 440   assert(cur != NULL, "invariant");
 441   assert(!cur->lease(), "invariant");
 442   assert(cur_pos != NULL, "invariant");
 443   assert(req >= used, "invariant");
 444 }
 445 
 446 static void assert_provision_large_precondition(ConstBufferPtr cur, size_t used, size_t req, const Thread* t) {
 447   assert(cur != NULL, "invariant");
 448   assert(t != NULL, "invariant");
 449   assert(t->trace_data()->shelved_buffer() != NULL, "invariant");
 450   assert(req >= used, "invariant");
 451 }
 452 
 453 static void assert_flush_large_precondition(ConstBufferPtr cur, const u1* const cur_pos, size_t used, size_t req, bool native, Thread* t) {
 454   assert(t != NULL, "invariant");
 455   assert(cur != NULL, "invariant");
 456   assert(cur->lease(), "invariant");
 457   assert(cur_pos != NULL, "invariant");
 458   assert(native ? t->trace_data()->native_buffer() == cur : t->trace_data()->java_buffer() == cur, "invariant");
 459   assert(t->trace_data()->shelved_buffer() != NULL, "invariant");
 460   assert(req >= used, "invariant");
 461   assert(cur != t->trace_data()->shelved_buffer(), "invariant");
 462 }
 463 #endif // ASSERT
 464 
 465 BufferPtr JfrStorage::flush(BufferPtr cur, size_t used, size_t req, bool native, Thread* t) {
 466   debug_only(assert_flush_precondition(cur, used, native, t);)
 467   const u1* const cur_pos = cur->pos();
 468   req += used;
 469   // requested size now encompass the outstanding used size
 470   if (cur->lease()) {
 471     return instance().flush_large(cur, cur_pos, used, req, native, t);
 472   }
 473   // "regular" == !lease
 474   return instance().flush_regular(cur, cur_pos, used, req, native, t);
 475 }
 476 
 477 BufferPtr JfrStorage::flush_regular(BufferPtr cur, const u1* const cur_pos, size_t used, size_t req, bool native, Thread* t) {
 478   debug_only(assert_flush_regular_precondition(cur, cur_pos, used, req, t);)
 479   // A flush is needed before memcpy since a non-large buffer is thread stable
 480   // (thread local). The flush will not modify memory in addresses above pos()
 481   // which is where the "used / uncommitted" data resides. It is therefore both
 482   // possible and valid to migrate data after the flush. This is however only
 483   // the case for stable thread local buffers; it is not the case for large buffers.
 484   if (!cur->empty()) {
 485     flush_regular_buffer(cur, t);
 486   }
 487   assert(t->trace_data()->shelved_buffer() == NULL, "invariant");
 488   if (cur->free_size() >= req) {
 489     // simplest case, no switching of buffers
 490     if (used > 0) {
 491       memcpy(cur->pos(), (void*)cur_pos, used);
 492     }
 493     assert(native ? t->trace_data()->native_buffer() == cur : t->trace_data()->java_buffer() == cur, "invariant");
 494     return cur;
 495   }
 496   // Going for a "larger-than-regular" buffer.
 497   // Shelve the current buffer to make room for a temporary lease.
 498   t->trace_data()->shelve_buffer(cur);
 499   return provision_large(cur, cur_pos, used, req, native, t);
 500 }
 501 
 502 static BufferPtr store_buffer_to_thread_local(BufferPtr buffer, JfrThreadData* trace_data, bool native) {
 503   assert(buffer != NULL, "invariant");
 504   if (native) {
 505     trace_data->set_native_buffer(buffer);
 506   } else {
 507    trace_data->set_java_buffer(buffer);
 508   }
 509   return buffer;
 510 }
 511 
 512 static BufferPtr restore_shelved_buffer(bool native, Thread* t) {
 513   JfrThreadData* const trace_data = t->trace_data();
 514   BufferPtr shelved = trace_data->shelved_buffer();
 515   assert(shelved != NULL, "invariant");
 516   t->trace_data()->shelve_buffer(NULL);
 517   // restore shelved buffer back as primary
 518   return store_buffer_to_thread_local(shelved, trace_data, native);
 519 }
 520 
 521 BufferPtr JfrStorage::flush_large(BufferPtr cur, const u1* const cur_pos, size_t used, size_t req, bool native, Thread* t) {
 522   debug_only(assert_flush_large_precondition(cur, cur_pos, used, req, native, t);)
 523   // Can the "regular" buffer (now shelved) accommodate the requested size?
 524   BufferPtr shelved = t->trace_data()->shelved_buffer();
 525   assert(shelved != NULL, "invariant");
 526   if (shelved->free_size() >= req) {
 527     if (req > 0) {
 528       memcpy(shelved->pos(), (void*)cur_pos, (size_t)used);
 529     }
 530     // release and invalidate
 531     release_large(cur, t);
 532     return restore_shelved_buffer(native, t);
 533   }
 534   // regular too small
 535   return provision_large(cur, cur_pos,  used, req, native, t);
 536 }
 537 
 538 static BufferPtr large_fail(BufferPtr cur, bool native, JfrStorage& storage_instance, Thread* t) {
 539   assert(cur != NULL, "invariant");
 540   assert(t != NULL, "invariant");
 541   if (cur->lease()) {
 542     storage_instance.release_large(cur, t);
 543   }
 544   return restore_shelved_buffer(native, t);
 545 }
 546 
 547 // Always returns a non-null buffer.
 548 // If accommodating the large request fails, the shelved buffer is returned
 549 // even though it might be smaller than the requested size.
 550 // Caller needs to ensure if the size was successfully accommodated.
 551 BufferPtr JfrStorage::provision_large(BufferPtr cur, const u1* const cur_pos, size_t used, size_t req, bool native, Thread* t) {
 552   debug_only(assert_provision_large_precondition(cur, used, req, t);)
 553   assert(t->trace_data()->shelved_buffer() != NULL, "invariant");
 554   BufferPtr const buffer = acquire_large(req, t);
 555   if (buffer == NULL) {
 556     // unable to allocate and serve the request
 557     return large_fail(cur, native, *this, t);
 558   }
 559   // ok managed to acquire a "large" buffer for the requested size
 560   assert(buffer->free_size() >= req, "invariant");
 561   assert(buffer->lease(), "invariant");
 562   // transfer outstanding data
 563   memcpy(buffer->pos(), (void*)cur_pos, used);
 564   if (cur->lease()) {
 565     release_large(cur, t);
 566     // don't use current anymore, it is gone
 567   }
 568   return store_buffer_to_thread_local(buffer, t->trace_data(), native);
 569 }
 570 
 571 typedef UnBufferedWriteToChunk<JfrBuffer> WriteOperation;
 572 typedef MutexedWriteOp<WriteOperation> MutexedWriteOperation;
 573 typedef ConcurrentWriteOp<WriteOperation> ConcurrentWriteOperation;
 574 typedef ThreadLocalReleaseOp<JfrStorageMspace> ThreadLocalRelease;
 575 typedef CompositeOperation<ConcurrentWriteOperation, ThreadLocalRelease> ThreadLocalWriteOperation;
 576 
 577 size_t JfrStorage::write() {
 578   const size_t full_size_processed = write_full();
 579   WriteOperation wo(_chunkwriter);
 580   ConcurrentWriteOperation cwo(wo);
 581   ThreadLocalRelease tlr(_thread_local_mspace);
 582   ThreadLocalWriteOperation tlwo(&cwo, &tlr);
 583   process_full_list(tlwo, _thread_local_mspace);
 584   process_free_list(cwo, _global_mspace);
 585   return full_size_processed + wo.processed();
 586 }
 587 
 588 size_t JfrStorage::write_at_safepoint() {
 589   assert(SafepointSynchronize::is_at_safepoint(), "invariant");
 590   WriteOperation wo(_chunkwriter);
 591   MutexedWriteOperation writer(wo); // mutexed write mode
 592   process_full_list(writer, _thread_local_mspace);
 593   assert(_transient_mspace->is_free_empty(), "invariant");
 594   process_full_list(writer, _transient_mspace);
 595   assert(_global_mspace->is_full_empty(), "invariant");
 596   process_free_list(writer, _global_mspace);
 597   return wo.processed();
 598 }
 599 
 600 typedef DiscardOp<DefaultDiscarder<JfrStorage::Buffer> > DiscardOperation;
 601 typedef CompositeOperation<DiscardOperation, ThreadLocalRelease> ThreadLocalDiscardOperation;
 602 typedef ReleaseOp<JfrStorageMspace> ReleaseOperation;
 603 typedef CompositeOperation<MutexedWriteOperation, ReleaseOperation> FullOperation;
 604 
 605 size_t JfrStorage::clear() {
 606   const size_t full_size_processed = clear_full();
 607   DiscardOperation discarder(concurrent); // concurrent discard mode
 608   ThreadLocalRelease tlr(_thread_local_mspace);
 609   ThreadLocalDiscardOperation tldo(&discarder, &tlr);
 610   process_full_list(tldo, _thread_local_mspace);
 611   assert(_transient_mspace->is_free_empty(), "invariant");
 612   process_full_list(discarder, _transient_mspace);
 613   assert(_global_mspace->is_full_empty(), "invariant");
 614   process_free_list(discarder, _global_mspace);
 615   return full_size_processed + discarder.processed();
 616 }
 617 
 618 static void insert_free_age_nodes(JfrStorageAgeMspace* age_mspace, JfrAgeNode* head, JfrAgeNode* tail, size_t count) {
 619   if (tail != NULL) {
 620     assert(tail->next() == NULL, "invariant");
 621     assert(head != NULL, "invariant");
 622     assert(head->prev() == NULL, "invariant");
 623     MutexLockerEx buffer_lock(JfrBuffer_lock, Mutex::_no_safepoint_check_flag);
 624     age_mspace->insert_free_tail(head, tail, count);
 625   }
 626 }
 627 
 628 template <typename Processor>
 629 static void process_age_list(Processor& processor, JfrStorageAgeMspace* age_mspace, JfrAgeNode* head, size_t count) {
 630   assert(age_mspace != NULL, "invariant");
 631   assert(head != NULL, "invariant");
 632   JfrAgeNode* node = head;
 633   JfrAgeNode* last = NULL;
 634   while (node != NULL) {
 635     last = node;
 636     BufferPtr const buffer = node->retired_buffer();
 637     assert(buffer != NULL, "invariant");
 638     assert(buffer->retired(), "invariant");
 639     processor.process(buffer);
 640     // at this point, buffer is already live or destroyed
 641     node->clear_identity();
 642     JfrAgeNode* const next = (JfrAgeNode*)node->next();
 643     if (node->transient()) {
 644       // detach
 645       last = (JfrAgeNode*)last->prev();
 646       if (last != NULL) {
 647         last->set_next(next);
 648       } else {
 649         head = next;
 650       }
 651       if (next != NULL) {
 652         next->set_prev(last);
 653       }
 654       --count;
 655       age_mspace->deallocate(node);
 656     }
 657     node = next;
 658   }
 659   insert_free_age_nodes(age_mspace, head, last, count);
 660 }
 661 
 662 template <typename Processor>
 663 static size_t process_full(Processor& processor, JfrStorageControl& control, JfrStorageAgeMspace* age_mspace) {
 664   assert(age_mspace != NULL, "invariant");
 665   if (age_mspace->is_full_empty()) {
 666     // nothing to do
 667     return 0;
 668   }
 669   size_t count;
 670   JfrAgeNode* head;;
 671   {
 672     // fetch age list
 673     MutexLockerEx buffer_lock(JfrBuffer_lock, Mutex::_no_safepoint_check_flag);
 674     count = age_mspace->full_count();
 675     head = age_mspace->clear_full();
 676     control.reset_full();
 677   }
 678   assert(head != NULL, "invariant");
 679   process_age_list(processor, age_mspace, head, count);
 680   return count;
 681 }
 682 
 683 static void log(size_t count, size_t amount, bool clear = false) {
 684   if (log_is_enabled(Debug, jfr, system)) {
 685     if (count > 0) {
 686       log_debug(jfr, system)( "%s " SIZE_FORMAT " full buffer(s) of " SIZE_FORMAT" B of data%s",
 687         clear ? "Discarded" : "Wrote", count, amount, clear ? "." : " to chunk.");
 688     }
 689   }
 690 }
 691 
 692 // full writer
 693 // Assumption is retired only; exclusive access
 694 // MutexedWriter -> ReleaseOp
 695 //
 696 size_t JfrStorage::write_full() {
 697   assert(_chunkwriter.is_valid(), "invariant");
 698   WriteOperation wo(_chunkwriter);
 699   MutexedWriteOperation writer(wo); // a retired buffer implies mutexed access
 700   ReleaseOperation ro(_transient_mspace);
 701   FullOperation cmd(&writer, &ro);
 702   const size_t count = process_full(cmd, control(), _age_mspace);
 703   log(count, writer.processed());
 704   return writer.processed();
 705 }
 706 
 707 size_t JfrStorage::clear_full() {
 708   DiscardOperation discarder(mutexed); // a retired buffer implies mutexed access
 709   const size_t count = process_full(discarder, control(), _age_mspace);
 710   log(count, discarder.processed(), true);
 711   return discarder.processed();
 712 }
 713 
 714 static void scavenge_log(size_t count, size_t amount, size_t current) {
 715   if (count > 0) {
 716     if (log_is_enabled(Debug, jfr, system)) {
 717       log_debug(jfr, system)("Released " SIZE_FORMAT " dead buffer(s) of " SIZE_FORMAT" B of data.", count, amount);
 718       log_debug(jfr, system)("Current number of dead buffers " SIZE_FORMAT "", current);
 719     }
 720   }
 721 }
 722 
 723 template <typename Mspace>
 724 class Scavenger {
 725  private:
 726   JfrStorageControl& _control;
 727   Mspace* _mspace;
 728   size_t _count;
 729   size_t _amount;
 730  public:
 731   typedef typename Mspace::Type Type;
 732   Scavenger(JfrStorageControl& control, Mspace* mspace) : _control(control), _mspace(mspace), _count(0), _amount(0) {}
 733   bool process(Type* t) {
 734     if (t->retired()) {
 735       assert(!t->transient(), "invariant");
 736       assert(!t->lease(), "invariant");
 737       assert(t->identity() == NULL, "invariant");
 738       assert(t->empty(), "invariant");
 739       ++_count;
 740       _amount += t->total_size();
 741       _control.decrement_dead();
 742       t->clear_retired();
 743       mspace_release_critical(t, _mspace);
 744     }
 745     return true;
 746   }
 747   size_t processed() const { return _count; }
 748   size_t amount() const { return _amount; }
 749 };
 750 
 751 size_t JfrStorage::scavenge() {
 752   if (control().dead_count() > 0) {
 753     Scavenger<JfrStorageMspace> scavenger(control(), _thread_local_mspace);
 754     process_full_list(scavenger, _thread_local_mspace);
 755     scavenge_log(scavenger.processed(), scavenger.amount(), control().dead_count());
 756     return scavenger.processed();
 757   }
 758   return 0;
 759 }