1 /*
  2  * Copyright (c) 2001, 2024, 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/vmSymbols.hpp"
 27 #include "jvm.h"
 28 #include "logging/log.hpp"
 29 #include "memory/allocation.inline.hpp"
 30 #include "oops/oop.inline.hpp"
 31 #include "runtime/handles.inline.hpp"
 32 #include "runtime/java.hpp"
 33 #include "runtime/mutex.hpp"
 34 #include "runtime/mutexLocker.hpp"
 35 #include "runtime/os.hpp"
 36 #include "runtime/perfData.inline.hpp"
 37 #include "utilities/exceptions.hpp"
 38 #include "utilities/globalDefinitions.hpp"
 39 
 40 PerfDataList*   PerfDataManager::_all = nullptr;
 41 PerfDataList*   PerfDataManager::_sampled = nullptr;
 42 PerfDataList*   PerfDataManager::_constants = nullptr;
 43 volatile bool   PerfDataManager::_has_PerfData = 0;
 44 
 45 /*
 46  * The jvmstat global and subsystem jvmstat counter name spaces. The top
 47  * level name spaces imply the interface stability level of the counter,
 48  * which generally follows the Java package, class, and property naming
 49  * conventions. The CounterNS enumeration values should be used to index
 50  * into this array.
 51  */
 52 const char* PerfDataManager::_name_spaces[] = {
 53   // top level name spaces
 54   "java",                   // stable and supported name space
 55   "com.sun",                // unstable but supported name space
 56   "sun",                    // unstable and unsupported name space
 57   // subsystem name spaces
 58   "java.gc",                // Garbage Collection name spaces
 59   "com.sun.gc",
 60   "sun.gc",
 61   "java.ci",                // Compiler name spaces
 62   "com.sun.ci",
 63   "sun.ci",
 64   "java.cls",               // Class Loader name spaces
 65   "com.sun.cls",
 66   "sun.cls",
 67   "java.rt",                // Runtime name spaces
 68   "com.sun.rt",
 69   "sun.rt",
 70   "java.os",                // Operating System name spaces
 71   "com.sun.os",
 72   "sun.os",
 73   "java.threads",           // Threads System name spaces
 74   "com.sun.threads",
 75   "sun.threads",
 76   "java.threads.cpu_time", //Thread CPU time name spaces
 77   "com.sun.threads.cpu_time",
 78   "sun.threads.cpu_time",
 79   "java.property",          // Java Property name spaces
 80   "com.sun.property",
 81   "sun.property",
 82   "",
 83 };
 84 
 85 PerfData::PerfData(CounterNS ns, const char* name, Units u, Variability v)
 86                   : _name(nullptr), _v(v), _u(u), _on_c_heap(false), _valuep(nullptr) {
 87 
 88   const char* prefix = PerfDataManager::ns_to_string(ns);
 89 
 90   const size_t _name_size = strlen(name) + strlen(prefix) + 2;
 91   _name = NEW_C_HEAP_ARRAY(char, _name_size, mtInternal);
 92   assert(strlen(name) != 0, "invalid name");
 93 
 94   if (ns == NULL_NS) {
 95      // No prefix is added to counters with the NULL_NS namespace.
 96      strcpy(_name, name);
 97      // set the F_Supported flag based on the counter name prefix.
 98      if (PerfDataManager::is_stable_supported(_name) ||
 99          PerfDataManager::is_unstable_supported(_name)) {
100        _flags = F_Supported;
101      }
102      else {
103        _flags = F_None;
104      }
105   }
106   else {
107     os::snprintf_checked(_name, _name_size, "%s.%s", prefix, name);
108     // set the F_Supported flag based on the given namespace.
109     if (PerfDataManager::is_stable_supported(ns) ||
110         PerfDataManager::is_unstable_supported(ns)) {
111       _flags = F_Supported;
112     }
113     else {
114       _flags = F_None;
115     }
116   }
117 }
118 
119 PerfData::~PerfData() {
120   FREE_C_HEAP_ARRAY(char, _name);
121   if (is_on_c_heap()) {
122     FREE_C_HEAP_ARRAY(PerfDataEntry, _pdep);
123   }
124 }
125 
126 void PerfData::create_entry(BasicType dtype, size_t dsize, size_t vlen) {
127 
128   size_t dlen = vlen==0 ? 1 : vlen;
129 
130   size_t namelen = strlen(name()) + 1;  // include null terminator
131   size_t size = sizeof(PerfDataEntry) + namelen;
132   size_t pad_length = ((size % dsize) == 0) ? 0 : dsize - (size % dsize);
133   size += pad_length;
134   size_t data_start = size;
135   size += (dsize * dlen);
136 
137   // align size to assure allocation in units of 8 bytes
138   int align = sizeof(jlong) - 1;
139   size = ((size + align) & ~align);
140   char* psmp = PerfMemory::alloc(size);
141 
142   if (psmp == nullptr) {
143     // out of PerfMemory memory resources. allocate on the C heap
144     // to avoid vm termination.
145     psmp = NEW_C_HEAP_ARRAY(char, size, mtInternal);
146     _on_c_heap = true;
147   }
148 
149   // compute the addresses for the name and data
150   char* cname = psmp + sizeof(PerfDataEntry);
151 
152   // data is in the last dsize*dlen bytes of the entry
153   void* valuep = (void*) (psmp + data_start);
154 
155   assert(is_on_c_heap() || PerfMemory::contains(cname), "just checking");
156   assert(is_on_c_heap() || PerfMemory::contains((char*)valuep), "just checking");
157 
158   // copy the name, including null terminator, into PerfData memory
159   strcpy(cname, name());
160 
161 
162   // set the header values in PerfData memory
163   PerfDataEntry* pdep = (PerfDataEntry*)psmp;
164   pdep->entry_length = (jint)size;
165   pdep->name_offset = (jint) ((uintptr_t) cname - (uintptr_t) psmp);
166   pdep->vector_length = (jint)vlen;
167   pdep->data_type = (jbyte) type2char(dtype);
168   pdep->data_units = units();
169   pdep->data_variability = variability();
170   pdep->flags = (jbyte)flags();
171   pdep->data_offset = (jint) data_start;
172 
173   log_debug(perf, datacreation)("name = %s, dtype = %d, variability = %d,"
174                                 " units = %d, dsize = " SIZE_FORMAT ", vlen = " SIZE_FORMAT ","
175                                 " pad_length = " SIZE_FORMAT ", size = " SIZE_FORMAT ", on_c_heap = %s,"
176                                 " address = " INTPTR_FORMAT ","
177                                 " data address = " INTPTR_FORMAT,
178                                 cname, dtype, variability(),
179                                 units(), dsize, vlen,
180                                 pad_length, size, is_on_c_heap() ? "TRUE":"FALSE",
181                                 p2i(psmp), p2i(valuep));
182 
183   // record the start of the entry and the location of the data field.
184   _pdep = pdep;
185   _valuep = valuep;
186 
187   // mark the PerfData memory region as having been updated.
188   PerfMemory::mark_updated();
189 }
190 
191 bool PerfData::name_equals(const char* name) const {
192   return strcmp(name, this->name()) == 0;
193 }
194 
195 PerfLong::PerfLong(CounterNS ns, const char* namep, Units u, Variability v)
196                  : PerfData(ns, namep, u, v) {
197 
198   create_entry(T_LONG, sizeof(jlong));
199 }
200 
201 PerfLongVariant::PerfLongVariant(CounterNS ns, const char* namep, Units u,
202                                  Variability v, PerfLongSampleHelper* helper)
203                                 : PerfLong(ns, namep, u, v),
204                                   _sample_helper(helper) {
205 
206   sample();
207 }
208 
209 void PerfLongVariant::sample() {
210   if (_sample_helper != nullptr) {
211     *(jlong*)_valuep = _sample_helper->take_sample();
212   }
213 }
214 
215 PerfByteArray::PerfByteArray(CounterNS ns, const char* namep, Units u,
216                              Variability v, jint length)
217                             : PerfData(ns, namep, u, v), _length(length) {
218 
219   create_entry(T_BYTE, sizeof(jbyte), (size_t)_length);
220 }
221 
222 void PerfString::set_string(const char* s2) {
223 
224   // copy n bytes of the string, assuring the null string is
225   // copied if s2 == nullptr.
226   strncpy((char *)_valuep, s2 == nullptr ? "" : s2, _length);
227 
228   // assure the string is null terminated when strlen(s2) >= _length
229   ((char*)_valuep)[_length-1] = '\0';
230 }
231 
232 PerfStringConstant::PerfStringConstant(CounterNS ns, const char* namep,
233                                        const char* initial_value)
234                      : PerfString(ns, namep, V_Constant,
235                                   initial_value == nullptr ? 1 :
236                                   MIN2((jint)(strlen((char*)initial_value)+1),
237                                        (jint)(PerfMaxStringConstLength+1)),
238                                   initial_value) {
239 
240   if (PrintMiscellaneous && Verbose) {
241     if (is_valid() && initial_value != nullptr &&
242         ((jint)strlen(initial_value) > (jint)PerfMaxStringConstLength)) {
243 
244       warning("Truncating PerfStringConstant: name = %s,"
245               " length = " INT32_FORMAT ","
246               " PerfMaxStringConstLength = " INT32_FORMAT "\n",
247               namep,
248               (jint)strlen(initial_value),
249               (jint)PerfMaxStringConstLength);
250     }
251   }
252 }
253 
254 
255 void PerfDataManager::destroy() {
256 
257   if (_all == nullptr)
258     // destroy already called, or initialization never happened
259     return;
260 
261   // Clear the flag before we free the PerfData counters. Thus begins
262   // the race between this thread and another thread that has just
263   // queried PerfDataManager::has_PerfData() and gotten back 'true'.
264   // The hope is that the other thread will finish its PerfData
265   // manipulation before we free the memory. The two alternatives are
266   // 1) leak the PerfData memory or 2) do some form of synchronized
267   // access or check before every PerfData operation.
268   _has_PerfData = false;
269   os::naked_short_sleep(1);  // 1ms sleep to let other thread(s) run
270 
271   log_debug(perf, datacreation)("Total = %d, Sampled = %d, Constants = %d",
272                                 _all->length(), _sampled == nullptr ? 0 : _sampled->length(),
273                                 _constants == nullptr ? 0 : _constants->length());
274 
275   for (int index = 0; index < _all->length(); index++) {
276     PerfData* p = _all->at(index);
277     delete p;
278   }
279 
280   delete(_all);
281   delete(_sampled);
282   delete(_constants);
283 
284   _all = nullptr;
285   _sampled = nullptr;
286   _constants = nullptr;
287 }
288 
289 void PerfDataManager::add_item(PerfData* p, bool sampled) {
290 
291   MutexLocker ml(PerfDataManager_lock);
292 
293   // Default sizes determined using -Xlog:perf+datacreation=debug
294   if (_all == nullptr) {
295     _all = new PerfDataList(191);
296     _has_PerfData = true;
297   }
298 
299   assert(!_all->contains(p->name()), "duplicate name added: %s", p->name());
300 
301   // add to the list of all perf data items
302   _all->append(p);
303 
304   if (p->variability() == PerfData::V_Constant) {
305     if (_constants == nullptr) {
306       _constants = new PerfDataList(51);
307     }
308     _constants->append(p);
309     return;
310   }
311 
312   if (sampled) {
313     if (_sampled == nullptr) {
314       _sampled = new PerfDataList(1);
315     }
316     _sampled->append(p);
317   }
318 }
319 
320 PerfDataList* PerfDataManager::sampled() {
321 
322   MutexLocker ml(PerfDataManager_lock);
323 
324   if (_sampled == nullptr)
325     return nullptr;
326 
327   PerfDataList* clone = _sampled->clone();
328   return clone;
329 }
330 
331 char* PerfDataManager::counter_name(const char* ns, const char* name) {
332    assert(ns != nullptr, "ns string required");
333    assert(name != nullptr, "name string required");
334 
335    size_t len = strlen(ns) + strlen(name) + 2;
336    char* result = NEW_RESOURCE_ARRAY(char, len);
337    os::snprintf_checked(result, len, "%s.%s", ns, name);
338    return result;
339 }
340 
341 char* PerfDataManager::name_space(const char* ns, const char* sub,
342                                   int instance) {
343    char intbuf[40];
344    jio_snprintf(intbuf, 40, UINT32_FORMAT, instance);
345    return name_space(ns, name_space(sub, intbuf));
346 }
347 
348 char *PerfDataManager::name_space(const char* ns, int instance) {
349    char intbuf[40];
350    jio_snprintf(intbuf, 40, UINT32_FORMAT, instance);
351    return name_space(ns, intbuf);
352 }
353 
354 PerfStringConstant* PerfDataManager::create_string_constant(CounterNS ns,
355                                                             const char* name,
356                                                             const char* s,
357                                                             TRAPS) {
358 
359   PerfStringConstant* p = new PerfStringConstant(ns, name, s);
360 
361   if (!p->is_valid()) {
362     // allocation of native resources failed.
363     delete p;
364     THROW_NULL(vmSymbols::java_lang_OutOfMemoryError());
365   }
366 
367   add_item(p, false);
368 
369   return p;
370 }
371 
372 PerfLongConstant* PerfDataManager::create_long_constant(CounterNS ns,
373                                                         const char* name,
374                                                         PerfData::Units u,
375                                                         jlong val, TRAPS) {
376 
377   PerfLongConstant* p = new PerfLongConstant(ns, name, u, val);
378 
379   if (!p->is_valid()) {
380     // allocation of native resources failed.
381     delete p;
382     THROW_NULL(vmSymbols::java_lang_OutOfMemoryError());
383   }
384 
385   add_item(p, false);
386 
387   return p;
388 }
389 
390 PerfStringVariable* PerfDataManager::create_string_variable(CounterNS ns,
391                                                             const char* name,
392                                                             int max_length,
393                                                             const char* s,
394                                                             TRAPS) {
395 
396   if (max_length == 0 && s != nullptr) max_length = (int)strlen(s);
397 
398   assert(max_length != 0, "PerfStringVariable with length 0");
399 
400   PerfStringVariable* p = new PerfStringVariable(ns, name, max_length, s);
401 
402   if (!p->is_valid()) {
403     // allocation of native resources failed.
404     delete p;
405     THROW_NULL(vmSymbols::java_lang_OutOfMemoryError());
406   }
407 
408   add_item(p, false);
409 
410   return p;
411 }
412 
413 PerfLongVariable* PerfDataManager::create_long_variable(CounterNS ns,
414                                                         const char* name,
415                                                         PerfData::Units u,
416                                                         jlong ival, TRAPS) {
417 
418   PerfLongVariable* p = new PerfLongVariable(ns, name, u, ival);
419 
420   if (!p->is_valid()) {
421     // allocation of native resources failed.
422     delete p;
423     THROW_NULL(vmSymbols::java_lang_OutOfMemoryError());
424   }
425 
426   add_item(p, false);
427 
428   return p;
429 }
430 
431 PerfLongVariable* PerfDataManager::create_long_variable(CounterNS ns,
432                                                         const char* name,
433                                                         PerfData::Units u,
434                                                         PerfSampleHelper* sh,
435                                                         TRAPS) {
436 
437   // Sampled counters not supported if UsePerfData is false
438   if (!UsePerfData) return nullptr;
439 
440   PerfLongVariable* p = new PerfLongVariable(ns, name, u, sh);
441 
442   if (!p->is_valid()) {
443     // allocation of native resources failed.
444     delete p;
445     THROW_NULL(vmSymbols::java_lang_OutOfMemoryError());
446   }
447 
448   add_item(p, true);
449 
450   return p;
451 }
452 
453 PerfLongCounter* PerfDataManager::create_long_counter(CounterNS ns,
454                                                       const char* name,
455                                                       PerfData::Units u,
456                                                       jlong ival, TRAPS) {
457 
458   PerfLongCounter* p = new PerfLongCounter(ns, name, u, ival);
459 
460   if (!p->is_valid()) {
461     // allocation of native resources failed.
462     delete p;
463     THROW_NULL(vmSymbols::java_lang_OutOfMemoryError());
464   }
465 
466   add_item(p, false);
467 
468   return p;
469 }
470 
471 PerfLongCounter* PerfDataManager::create_long_counter(CounterNS ns,
472                                                       const char* name,
473                                                       PerfData::Units u,
474                                                       PerfSampleHelper* sh,
475                                                       TRAPS) {
476 
477   // Sampled counters not supported if UsePerfData is false
478   if (!UsePerfData) return nullptr;
479 
480   PerfLongCounter* p = new PerfLongCounter(ns, name, u, sh);
481 
482   if (!p->is_valid()) {
483     // allocation of native resources failed.
484     delete p;
485     THROW_NULL(vmSymbols::java_lang_OutOfMemoryError());
486   }
487 
488   add_item(p, true);
489 
490   return p;
491 }
492 
493 PerfDataList::PerfDataList(int length) {
494 
495   _set = new (mtInternal) PerfDataArray(length, mtInternal);
496 }
497 
498 PerfDataList::PerfDataList(PerfDataList* p) {
499 
500   _set = new (mtInternal) PerfDataArray(p->length(), mtInternal);
501 
502   _set->appendAll(p->get_impl());
503 }
504 
505 PerfDataList::~PerfDataList() {
506 
507   delete _set;
508 
509 }
510 
511 PerfData* PerfDataList::find_by_name(const char* name) {
512 
513   int i = _set->find_if([&](PerfData* pd) { return pd->name_equals(name); });
514 
515   if (i >= 0 && i <= _set->length())
516     return _set->at(i);
517   else
518     return nullptr;
519 }
520 
521 PerfDataList* PerfDataList::clone() {
522 
523   PerfDataList* copy = new PerfDataList(this);
524 
525   assert(copy != nullptr, "just checking");
526 
527   return copy;
528 }
529 
530 PerfTraceTimeBase::~PerfTraceTimeBase() {
531   if (!UsePerfData || !_t->is_active()) return;
532   if (_counter != nullptr) {
533     _t->stop();
534     _counter->inc(_t->ticks());
535   }
536 }