1 /*
   2  * Copyright (c) 2016, 2019, 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 "classfile/javaClasses.hpp"
  27 #include "jfr/recorder/jfrRecorder.hpp"
  28 #include "jfr/recorder/checkpoint/jfrCheckpointManager.hpp"
  29 #include "jfr/recorder/checkpoint/jfrCheckpointWriter.hpp"
  30 #include "jfr/recorder/checkpoint/types/jfrTypeManager.hpp"
  31 #include "jfr/recorder/checkpoint/types/traceid/jfrTraceIdEpoch.hpp"
  32 #include "jfr/recorder/service/jfrOptionSet.hpp"
  33 #include "jfr/recorder/storage/jfrMemorySpace.inline.hpp"
  34 #include "jfr/recorder/storage/jfrStorageUtils.inline.hpp"
  35 #include "jfr/recorder/repository/jfrChunkWriter.hpp"
  36 #include "jfr/utilities/jfrBigEndian.hpp"
  37 #include "jfr/utilities/jfrTypes.hpp"
  38 #include "memory/resourceArea.hpp"
  39 #include "runtime/mutexLocker.hpp"
  40 #include "runtime/orderAccess.inline.hpp"
  41 #include "runtime/os.hpp"
  42 #include "runtime/safepoint.hpp"
  43 
  44 typedef JfrCheckpointManager::Buffer* BufferPtr;
  45 
  46 static JfrCheckpointManager* _instance = NULL;
  47 
  48 JfrCheckpointManager& JfrCheckpointManager::instance() {
  49   return *_instance;
  50 }
  51 
  52 JfrCheckpointManager* JfrCheckpointManager::create(JfrChunkWriter& cw) {
  53   assert(_instance == NULL, "invariant");
  54   _instance = new JfrCheckpointManager(cw);
  55   return _instance;
  56 }
  57 
  58 void JfrCheckpointManager::destroy() {
  59   assert(_instance != NULL, "invariant");
  60   delete _instance;
  61   _instance = NULL;
  62 }
  63 
  64 JfrCheckpointManager::JfrCheckpointManager(JfrChunkWriter& cw) :
  65   _free_list_mspace(NULL),
  66   _epoch_transition_mspace(NULL),
  67   _lock(NULL),
  68   _service_thread(NULL),
  69   _chunkwriter(cw),
  70   _checkpoint_epoch_state(JfrTraceIdEpoch::current()) {}
  71 
  72 JfrCheckpointManager::~JfrCheckpointManager() {
  73   if (_free_list_mspace != NULL) {
  74     delete _free_list_mspace;
  75   }
  76   if (_epoch_transition_mspace != NULL) {
  77     delete _epoch_transition_mspace;
  78   }
  79   if (_lock != NULL) {
  80     delete _lock;
  81   }
  82   JfrTypeManager::clear();
  83 }
  84 
  85 static const size_t unlimited_mspace_size = 0;
  86 static const size_t checkpoint_buffer_cache_count = 2;
  87 static const size_t checkpoint_buffer_size = 512 * K;
  88 
  89 static JfrCheckpointMspace* create_mspace(size_t buffer_size, size_t limit, size_t cache_count, JfrCheckpointManager* system) {
  90   JfrCheckpointMspace* mspace = new JfrCheckpointMspace(buffer_size, limit, cache_count, system);
  91   if (mspace != NULL) {
  92     mspace->initialize();
  93   }
  94   return mspace;
  95 }
  96 
  97 bool JfrCheckpointManager::initialize() {
  98   assert(_free_list_mspace == NULL, "invariant");
  99   _free_list_mspace = create_mspace(checkpoint_buffer_size, unlimited_mspace_size, checkpoint_buffer_cache_count, this);
 100   if (_free_list_mspace == NULL) {
 101     return false;
 102   }
 103   assert(_epoch_transition_mspace == NULL, "invariant");
 104   _epoch_transition_mspace = create_mspace(checkpoint_buffer_size, unlimited_mspace_size, checkpoint_buffer_cache_count, this);
 105   if (_epoch_transition_mspace == NULL) {
 106     return false;
 107   }
 108   assert(_lock == NULL, "invariant");
 109   _lock = new Mutex(Monitor::leaf - 1, "Checkpoint mutex", Mutex::_allow_vm_block_flag);
 110   if (_lock == NULL) {
 111     return false;
 112   }
 113   return JfrTypeManager::initialize();
 114 }
 115 
 116 bool JfrCheckpointManager::use_epoch_transition_mspace(const Thread* thread) const {
 117   return _service_thread != thread && OrderAccess::load_acquire((u1*)&_checkpoint_epoch_state) != JfrTraceIdEpoch::current();
 118 }
 119 
 120 void JfrCheckpointManager::synchronize_epoch() {
 121   assert(_checkpoint_epoch_state != JfrTraceIdEpoch::current(), "invariant");
 122   OrderAccess::storestore();
 123   _checkpoint_epoch_state = JfrTraceIdEpoch::current();
 124 }
 125 
 126 void JfrCheckpointManager::shift_epoch() {
 127   debug_only(const u1 current_epoch = JfrTraceIdEpoch::current();)
 128   JfrTraceIdEpoch::shift_epoch();
 129   assert(current_epoch != JfrTraceIdEpoch::current(), "invariant");
 130 }
 131 
 132 void JfrCheckpointManager::register_service_thread(const Thread* thread) {
 133   _service_thread = thread;
 134 }
 135 
 136 void JfrCheckpointManager::register_full(BufferPtr t, Thread* thread) {
 137   // nothing here at the moment
 138   assert(t != NULL, "invariant");
 139   assert(t->acquired_by(thread), "invariant");
 140   assert(t->retired(), "invariant");
 141 }
 142 
 143 void JfrCheckpointManager::lock() {
 144   assert(!_lock->owned_by_self(), "invariant");
 145   _lock->lock_without_safepoint_check();
 146 }
 147 
 148 void JfrCheckpointManager::unlock() {
 149   _lock->unlock();
 150 }
 151 
 152 #ifdef ASSERT
 153 
 154 bool JfrCheckpointManager::is_locked() const {
 155   return _lock->owned_by_self();
 156 }
 157 
 158 static void assert_free_lease(const BufferPtr buffer) {
 159   assert(buffer != NULL, "invariant");
 160   assert(buffer->acquired_by_self(), "invariant");
 161   assert(buffer->lease(), "invariant");
 162 }
 163 
 164 static void assert_release(const BufferPtr buffer) {
 165   assert(buffer != NULL, "invariant");
 166   assert(buffer->lease(), "invariant");
 167   assert(buffer->acquired_by_self(), "invariant");
 168 }
 169 
 170 #endif // ASSERT
 171 
 172 static BufferPtr lease_free(size_t size, JfrCheckpointMspace* mspace, size_t retry_count, Thread* thread) {
 173   static const size_t max_elem_size = mspace->min_elem_size(); // min is max
 174   BufferPtr buffer;
 175   if (size <= max_elem_size) {
 176     BufferPtr buffer = mspace_get_free_lease_with_retry(size, mspace, retry_count, thread);
 177     if (buffer != NULL) {
 178       DEBUG_ONLY(assert_free_lease(buffer);)
 179       return buffer;
 180     }
 181   }
 182   buffer = mspace_allocate_transient_lease_to_free(size, mspace, thread);
 183   DEBUG_ONLY(assert_free_lease(buffer);)
 184   return buffer;
 185 }
 186 
 187 static const size_t lease_retry = 10;
 188 
 189 BufferPtr JfrCheckpointManager::lease_buffer(Thread* thread, size_t size /* 0 */) {
 190   JfrCheckpointManager& manager = instance();
 191   if (manager.use_epoch_transition_mspace(thread)) {
 192     return lease_free(size, manager._epoch_transition_mspace, lease_retry, thread);
 193   }
 194   return lease_free(size, manager._free_list_mspace, lease_retry, thread);
 195 }
 196 
 197 /*
 198 * If the buffer was a "lease" from the free list, release back.
 199 *
 200 * The buffer is effectively invalidated for the thread post-return,
 201 * and the caller should take means to ensure that it is not referenced.
 202 */
 203 static void release(BufferPtr const buffer, Thread* thread) {
 204   DEBUG_ONLY(assert_release(buffer);)
 205   buffer->clear_lease();
 206   buffer->release();
 207 }
 208 
 209 BufferPtr JfrCheckpointManager::flush(BufferPtr old, size_t used, size_t requested, Thread* thread) {
 210   assert(old != NULL, "invariant");
 211   assert(old->lease(), "invariant");
 212   if (0 == requested) {
 213     // indicates a lease is being returned
 214     release(old, thread);
 215     return NULL;
 216   }
 217   // migration of in-flight information
 218   BufferPtr const new_buffer = lease_buffer(thread, used + requested);
 219   if (new_buffer != NULL) {
 220     migrate_outstanding_writes(old, new_buffer, used, requested);
 221   }
 222   release(old, thread);
 223   return new_buffer; // might be NULL
 224 }
 225 
 226 // offsets into the JfrCheckpointEntry
 227 static const juint starttime_offset = sizeof(jlong);
 228 static const juint duration_offset = starttime_offset + sizeof(jlong);
 229 static const juint flushpoint_offset = duration_offset + sizeof(jlong);
 230 static const juint types_offset = flushpoint_offset + sizeof(juint);
 231 static const juint payload_offset = types_offset + sizeof(juint);
 232 
 233 template <typename Return>
 234 static Return read_data(const u1* data) {
 235   return JfrBigEndian::read<Return>(data);
 236 }
 237 
 238 static jlong total_size(const u1* data) {
 239   return read_data<jlong>(data);
 240 }
 241 
 242 static jlong starttime(const u1* data) {
 243   return read_data<jlong>(data + starttime_offset);
 244 }
 245 
 246 static jlong duration(const u1* data) {
 247   return read_data<jlong>(data + duration_offset);
 248 }
 249 
 250 static bool is_flushpoint(const u1* data) {
 251   return read_data<juint>(data + flushpoint_offset) == (juint)1;
 252 }
 253 
 254 static juint number_of_types(const u1* data) {
 255   return read_data<juint>(data + types_offset);
 256 }
 257 
 258 static void write_checkpoint_header(JfrChunkWriter& cw, intptr_t offset_prev_cp_event, const u1* data) {
 259   cw.reserve(sizeof(u4));
 260   cw.write((u8)EVENT_CHECKPOINT);
 261   cw.write(starttime(data));
 262   cw.write(duration(data));
 263   cw.write((jlong)offset_prev_cp_event);
 264   cw.write(is_flushpoint(data));
 265   cw.write(number_of_types(data));
 266 }
 267 
 268 static void write_checkpoint_content(JfrChunkWriter& cw, const u1* data, size_t size) {
 269   assert(data != NULL, "invariant");
 270   cw.write_unbuffered(data + payload_offset, size);
 271 }
 272 
 273 static size_t write_checkpoint_event(JfrChunkWriter& cw, const u1* data) {
 274   assert(data != NULL, "invariant");
 275   const intptr_t previous_checkpoint_event = cw.previous_checkpoint_offset();
 276   const intptr_t event_begin = cw.current_offset();
 277   const intptr_t offset_to_previous_checkpoint_event = 0 == previous_checkpoint_event ? 0 : previous_checkpoint_event - event_begin;
 278   const jlong total_checkpoint_size = total_size(data);
 279   write_checkpoint_header(cw, offset_to_previous_checkpoint_event, data);
 280   write_checkpoint_content(cw, data, total_checkpoint_size - sizeof(JfrCheckpointEntry));
 281   const jlong checkpoint_event_size = cw.current_offset() - event_begin;
 282   cw.write_padded_at_offset<u4>(checkpoint_event_size, event_begin);
 283   cw.set_previous_checkpoint_offset(event_begin);
 284   return (size_t)total_checkpoint_size;
 285 }
 286 
 287 static size_t write_checkpoints(JfrChunkWriter& cw, const u1* data, size_t size) {
 288   assert(cw.is_valid(), "invariant");
 289   assert(data != NULL, "invariant");
 290   assert(size > 0, "invariant");
 291   const u1* const limit = data + size;
 292   const u1* next_entry = data;
 293   size_t processed = 0;
 294   while (next_entry < limit) {
 295     const size_t checkpoint_size = write_checkpoint_event(cw, next_entry);
 296     processed += checkpoint_size;
 297     next_entry += checkpoint_size;
 298   }
 299   assert(next_entry == limit, "invariant");
 300   return processed;
 301 }
 302 
 303 template <typename T>
 304 class CheckpointWriteOp {
 305  private:
 306   JfrChunkWriter& _writer;
 307   size_t _processed;
 308  public:
 309   typedef T Type;
 310   CheckpointWriteOp(JfrChunkWriter& writer) : _writer(writer), _processed(0) {}
 311   bool write(Type* t, const u1* data, size_t size) {
 312     _processed += write_checkpoints(_writer, data, size);
 313     return true;
 314   }
 315   size_t processed() const { return _processed; }
 316 };
 317 
 318 typedef CheckpointWriteOp<JfrCheckpointMspace::Type> WriteOperation;
 319 typedef MutexedWriteOp<WriteOperation> MutexedWriteOperation;
 320 typedef ReleaseOp<JfrCheckpointMspace> CheckpointReleaseOperation;
 321 typedef CompositeOperation<MutexedWriteOperation, CheckpointReleaseOperation> CheckpointWriteOperation;
 322 
 323 static size_t write_mspace_exclusive(JfrCheckpointMspace* mspace, JfrChunkWriter& chunkwriter) {
 324   Thread* const thread = Thread::current();
 325   WriteOperation wo(chunkwriter);
 326   MutexedWriteOperation mwo(wo);
 327   CheckpointReleaseOperation cro(mspace, thread, false);
 328   CheckpointWriteOperation cpwo(&mwo, &cro);
 329   assert(mspace->is_full_empty(), "invariant");
 330   process_free_list(cpwo, mspace);
 331   return wo.processed();
 332 }
 333 
 334 size_t JfrCheckpointManager::write() {
 335   const size_t processed = write_mspace_exclusive(_free_list_mspace, _chunkwriter);
 336   synchronize_epoch();
 337   return processed;
 338 }
 339 
 340 size_t JfrCheckpointManager::write_epoch_transition_mspace() {
 341   return write_mspace_exclusive(_epoch_transition_mspace, _chunkwriter);
 342 }
 343 
 344 typedef DiscardOp<DefaultDiscarder<JfrBuffer> > DiscardOperation;
 345 size_t JfrCheckpointManager::clear() {
 346   DiscardOperation discarder(mutexed); // mutexed discard mode
 347   process_free_list(discarder, _free_list_mspace);
 348   process_free_list(discarder, _epoch_transition_mspace);
 349   synchronize_epoch();
 350   return discarder.processed();
 351 }
 352 
 353 size_t JfrCheckpointManager::write_types() {
 354   JfrCheckpointWriter writer(false, true, Thread::current());
 355   JfrTypeManager::write_types(writer);
 356   return writer.used_size();
 357 }
 358 
 359 size_t JfrCheckpointManager::write_safepoint_types() {
 360   // this is also a "flushpoint"
 361   JfrCheckpointWriter writer(true, true, Thread::current());
 362   JfrTypeManager::write_safepoint_types(writer);
 363   return writer.used_size();
 364 }
 365 
 366 void JfrCheckpointManager::write_type_set() {
 367   JfrTypeManager::write_type_set();
 368 }
 369 
 370 void JfrCheckpointManager::write_type_set_for_unloaded_classes() {
 371   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
 372   JfrTypeManager::write_type_set_for_unloaded_classes();
 373 }
 374 
 375 void JfrCheckpointManager::create_thread_checkpoint(JavaThread* jt) {
 376   JfrTypeManager::create_thread_checkpoint(jt);
 377 }
 378 
 379 void JfrCheckpointManager::write_thread_checkpoint(JavaThread* jt) {
 380   JfrTypeManager::write_thread_checkpoint(jt);
 381 }