Path: blob/master/src/hotspot/os/linux/os_linux.cpp
64440 views
/*1* Copyright (c) 1999, 2022, Oracle and/or its affiliates. All rights reserved.2* Copyright (c) 2015, 2022 SAP SE. 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 it6* under the terms of the GNU General Public License version 2 only, as7* published by the Free Software Foundation.8*9* This code is distributed in the hope that it will be useful, but WITHOUT10* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or11* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License12* version 2 for more details (a copy is included in the LICENSE file that13* accompanied this code).14*15* You should have received a copy of the GNU General Public License version16* 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 USA20* or visit www.oracle.com if you need additional information or have any21* questions.22*23*/2425// no precompiled headers26#include "jvm.h"27#include "classfile/vmSymbols.hpp"28#include "code/icBuffer.hpp"29#include "code/vtableStubs.hpp"30#include "compiler/compileBroker.hpp"31#include "compiler/disassembler.hpp"32#include "interpreter/interpreter.hpp"33#include "jvmtifiles/jvmti.h"34#include "logging/log.hpp"35#include "logging/logStream.hpp"36#include "memory/allocation.inline.hpp"37#include "oops/oop.inline.hpp"38#include "os_linux.inline.hpp"39#include "os_posix.inline.hpp"40#include "os_share_linux.hpp"41#include "osContainer_linux.hpp"42#include "prims/jniFastGetField.hpp"43#include "prims/jvm_misc.hpp"44#include "runtime/arguments.hpp"45#include "runtime/atomic.hpp"46#include "runtime/globals.hpp"47#include "runtime/globals_extension.hpp"48#include "runtime/interfaceSupport.inline.hpp"49#include "runtime/init.hpp"50#include "runtime/java.hpp"51#include "runtime/javaCalls.hpp"52#include "runtime/mutexLocker.hpp"53#include "runtime/objectMonitor.hpp"54#include "runtime/osThread.hpp"55#include "runtime/perfMemory.hpp"56#include "runtime/sharedRuntime.hpp"57#include "runtime/statSampler.hpp"58#include "runtime/stubRoutines.hpp"59#include "runtime/thread.inline.hpp"60#include "runtime/threadCritical.hpp"61#include "runtime/threadSMR.hpp"62#include "runtime/timer.hpp"63#include "runtime/vm_version.hpp"64#include "signals_posix.hpp"65#include "semaphore_posix.hpp"66#include "services/memTracker.hpp"67#include "services/runtimeService.hpp"68#include "utilities/align.hpp"69#include "utilities/decoder.hpp"70#include "utilities/defaultStream.hpp"71#include "utilities/events.hpp"72#include "utilities/elfFile.hpp"73#include "utilities/growableArray.hpp"74#include "utilities/macros.hpp"75#include "utilities/powerOfTwo.hpp"76#include "utilities/vmError.hpp"7778// put OS-includes here79# include <sys/types.h>80# include <sys/mman.h>81# include <sys/stat.h>82# include <sys/select.h>83# include <pthread.h>84# include <signal.h>85# include <endian.h>86# include <errno.h>87# include <dlfcn.h>88# include <stdio.h>89# include <unistd.h>90# include <sys/resource.h>91# include <pthread.h>92# include <sys/stat.h>93# include <sys/time.h>94# include <sys/times.h>95# include <sys/utsname.h>96# include <sys/socket.h>97# include <pwd.h>98# include <poll.h>99# include <fcntl.h>100# include <string.h>101# include <syscall.h>102# include <sys/sysinfo.h>103# include <sys/ipc.h>104# include <sys/shm.h>105# include <link.h>106# include <stdint.h>107# include <inttypes.h>108# include <sys/ioctl.h>109# include <linux/elf-em.h>110#ifdef __GLIBC__111# include <malloc.h>112#endif113114#ifndef _GNU_SOURCE115#define _GNU_SOURCE116#include <sched.h>117#undef _GNU_SOURCE118#else119#include <sched.h>120#endif121122// if RUSAGE_THREAD for getrusage() has not been defined, do it here. The code calling123// getrusage() is prepared to handle the associated failure.124#ifndef RUSAGE_THREAD125#define RUSAGE_THREAD (1) /* only the calling thread */126#endif127128#define MAX_PATH (2 * K)129130#define MAX_SECS 100000000131132// for timer info max values which include all bits133#define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)134135#ifdef MUSL_LIBC136// dlvsym is not a part of POSIX137// and musl libc doesn't implement it.138static void *dlvsym(void *handle,139const char *symbol,140const char *version) {141// load the latest version of symbol142return dlsym(handle, symbol);143}144#endif145146enum CoredumpFilterBit {147FILE_BACKED_PVT_BIT = 1 << 2,148FILE_BACKED_SHARED_BIT = 1 << 3,149LARGEPAGES_BIT = 1 << 6,150DAX_SHARED_BIT = 1 << 8151};152153////////////////////////////////////////////////////////////////////////////////154// global variables155julong os::Linux::_physical_memory = 0;156157address os::Linux::_initial_thread_stack_bottom = NULL;158uintptr_t os::Linux::_initial_thread_stack_size = 0;159160int (*os::Linux::_pthread_getcpuclockid)(pthread_t, clockid_t *) = NULL;161int (*os::Linux::_pthread_setname_np)(pthread_t, const char*) = NULL;162pthread_t os::Linux::_main_thread;163int os::Linux::_page_size = -1;164bool os::Linux::_supports_fast_thread_cpu_time = false;165const char * os::Linux::_libc_version = NULL;166const char * os::Linux::_libpthread_version = NULL;167size_t os::Linux::_default_large_page_size = 0;168169#ifdef __GLIBC__170os::Linux::mallinfo_func_t os::Linux::_mallinfo = NULL;171os::Linux::mallinfo2_func_t os::Linux::_mallinfo2 = NULL;172#endif // __GLIBC__173174static jlong initial_time_count=0;175176static int clock_tics_per_sec = 100;177178// If the VM might have been created on the primordial thread, we need to resolve the179// primordial thread stack bounds and check if the current thread might be the180// primordial thread in places. If we know that the primordial thread is never used,181// such as when the VM was created by one of the standard java launchers, we can182// avoid this183static bool suppress_primordial_thread_resolution = false;184185// utility functions186187julong os::available_memory() {188return Linux::available_memory();189}190191julong os::Linux::available_memory() {192// values in struct sysinfo are "unsigned long"193struct sysinfo si;194julong avail_mem;195196if (OSContainer::is_containerized()) {197jlong mem_limit, mem_usage;198if ((mem_limit = OSContainer::memory_limit_in_bytes()) < 1) {199log_debug(os, container)("container memory limit %s: " JLONG_FORMAT ", using host value",200mem_limit == OSCONTAINER_ERROR ? "failed" : "unlimited", mem_limit);201}202if (mem_limit > 0 && (mem_usage = OSContainer::memory_usage_in_bytes()) < 1) {203log_debug(os, container)("container memory usage failed: " JLONG_FORMAT ", using host value", mem_usage);204}205if (mem_limit > 0 && mem_usage > 0 ) {206avail_mem = mem_limit > mem_usage ? (julong)mem_limit - (julong)mem_usage : 0;207log_trace(os)("available container memory: " JULONG_FORMAT, avail_mem);208return avail_mem;209}210}211212sysinfo(&si);213avail_mem = (julong)si.freeram * si.mem_unit;214log_trace(os)("available memory: " JULONG_FORMAT, avail_mem);215return avail_mem;216}217218julong os::physical_memory() {219jlong phys_mem = 0;220if (OSContainer::is_containerized()) {221jlong mem_limit;222if ((mem_limit = OSContainer::memory_limit_in_bytes()) > 0) {223log_trace(os)("total container memory: " JLONG_FORMAT, mem_limit);224return mem_limit;225}226log_debug(os, container)("container memory limit %s: " JLONG_FORMAT ", using host value",227mem_limit == OSCONTAINER_ERROR ? "failed" : "unlimited", mem_limit);228}229230phys_mem = Linux::physical_memory();231log_trace(os)("total system memory: " JLONG_FORMAT, phys_mem);232return phys_mem;233}234235static uint64_t initial_total_ticks = 0;236static uint64_t initial_steal_ticks = 0;237static bool has_initial_tick_info = false;238239static void next_line(FILE *f) {240int c;241do {242c = fgetc(f);243} while (c != '\n' && c != EOF);244}245246bool os::Linux::get_tick_information(CPUPerfTicks* pticks, int which_logical_cpu) {247FILE* fh;248uint64_t userTicks, niceTicks, systemTicks, idleTicks;249// since at least kernel 2.6 : iowait: time waiting for I/O to complete250// irq: time servicing interrupts; softirq: time servicing softirqs251uint64_t iowTicks = 0, irqTicks = 0, sirqTicks= 0;252// steal (since kernel 2.6.11): time spent in other OS when running in a virtualized environment253uint64_t stealTicks = 0;254// guest (since kernel 2.6.24): time spent running a virtual CPU for guest OS under the255// control of the Linux kernel256uint64_t guestNiceTicks = 0;257int logical_cpu = -1;258const int required_tickinfo_count = (which_logical_cpu == -1) ? 4 : 5;259int n;260261memset(pticks, 0, sizeof(CPUPerfTicks));262263if ((fh = fopen("/proc/stat", "r")) == NULL) {264return false;265}266267if (which_logical_cpu == -1) {268n = fscanf(fh, "cpu " UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT " "269UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT " "270UINT64_FORMAT " " UINT64_FORMAT " ",271&userTicks, &niceTicks, &systemTicks, &idleTicks,272&iowTicks, &irqTicks, &sirqTicks,273&stealTicks, &guestNiceTicks);274} else {275// Move to next line276next_line(fh);277278// find the line for requested cpu faster to just iterate linefeeds?279for (int i = 0; i < which_logical_cpu; i++) {280next_line(fh);281}282283n = fscanf(fh, "cpu%u " UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT " "284UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT " "285UINT64_FORMAT " " UINT64_FORMAT " ",286&logical_cpu, &userTicks, &niceTicks,287&systemTicks, &idleTicks, &iowTicks, &irqTicks, &sirqTicks,288&stealTicks, &guestNiceTicks);289}290291fclose(fh);292if (n < required_tickinfo_count || logical_cpu != which_logical_cpu) {293return false;294}295pticks->used = userTicks + niceTicks;296pticks->usedKernel = systemTicks + irqTicks + sirqTicks;297pticks->total = userTicks + niceTicks + systemTicks + idleTicks +298iowTicks + irqTicks + sirqTicks + stealTicks + guestNiceTicks;299300if (n > required_tickinfo_count + 3) {301pticks->steal = stealTicks;302pticks->has_steal_ticks = true;303} else {304pticks->steal = 0;305pticks->has_steal_ticks = false;306}307308return true;309}310311// Return true if user is running as root.312313bool os::have_special_privileges() {314static bool init = false;315static bool privileges = false;316if (!init) {317privileges = (getuid() != geteuid()) || (getgid() != getegid());318init = true;319}320return privileges;321}322323324#ifndef SYS_gettid325// i386: 224, ia64: 1105, amd64: 186, sparc: 143326#ifdef __ia64__327#define SYS_gettid 1105328#else329#ifdef __i386__330#define SYS_gettid 224331#else332#ifdef __amd64__333#define SYS_gettid 186334#else335#ifdef __sparc__336#define SYS_gettid 143337#else338#error define gettid for the arch339#endif340#endif341#endif342#endif343#endif344345346// pid_t gettid()347//348// Returns the kernel thread id of the currently running thread. Kernel349// thread id is used to access /proc.350pid_t os::Linux::gettid() {351int rslt = syscall(SYS_gettid);352assert(rslt != -1, "must be."); // old linuxthreads implementation?353return (pid_t)rslt;354}355356// Most versions of linux have a bug where the number of processors are357// determined by looking at the /proc file system. In a chroot environment,358// the system call returns 1.359static bool unsafe_chroot_detected = false;360static const char *unstable_chroot_error = "/proc file system not found.\n"361"Java may be unstable running multithreaded in a chroot "362"environment on Linux when /proc filesystem is not mounted.";363364void os::Linux::initialize_system_info() {365set_processor_count(sysconf(_SC_NPROCESSORS_CONF));366if (processor_count() == 1) {367pid_t pid = os::Linux::gettid();368char fname[32];369jio_snprintf(fname, sizeof(fname), "/proc/%d", pid);370FILE *fp = fopen(fname, "r");371if (fp == NULL) {372unsafe_chroot_detected = true;373} else {374fclose(fp);375}376}377_physical_memory = (julong)sysconf(_SC_PHYS_PAGES) * (julong)sysconf(_SC_PAGESIZE);378assert(processor_count() > 0, "linux error");379}380381void os::init_system_properties_values() {382// The next steps are taken in the product version:383//384// Obtain the JAVA_HOME value from the location of libjvm.so.385// This library should be located at:386// <JAVA_HOME>/lib/{client|server}/libjvm.so.387//388// If "/jre/lib/" appears at the right place in the path, then we389// assume libjvm.so is installed in a JDK and we use this path.390//391// Otherwise exit with message: "Could not create the Java virtual machine."392//393// The following extra steps are taken in the debugging version:394//395// If "/jre/lib/" does NOT appear at the right place in the path396// instead of exit check for $JAVA_HOME environment variable.397//398// If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>,399// then we append a fake suffix "hotspot/libjvm.so" to this path so400// it looks like libjvm.so is installed there401// <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm.so.402//403// Otherwise exit.404//405// Important note: if the location of libjvm.so changes this406// code needs to be changed accordingly.407408// See ld(1):409// The linker uses the following search paths to locate required410// shared libraries:411// 1: ...412// ...413// 7: The default directories, normally /lib and /usr/lib.414#ifndef OVERRIDE_LIBPATH415#if defined(_LP64)416#define DEFAULT_LIBPATH "/usr/lib64:/lib64:/lib:/usr/lib"417#else418#define DEFAULT_LIBPATH "/lib:/usr/lib"419#endif420#else421#define DEFAULT_LIBPATH OVERRIDE_LIBPATH422#endif423424// Base path of extensions installed on the system.425#define SYS_EXT_DIR "/usr/java/packages"426#define EXTENSIONS_DIR "/lib/ext"427428// Buffer that fits several sprintfs.429// Note that the space for the colon and the trailing null are provided430// by the nulls included by the sizeof operator.431const size_t bufsize =432MAX2((size_t)MAXPATHLEN, // For dll_dir & friends.433(size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + sizeof(SYS_EXT_DIR) + sizeof(EXTENSIONS_DIR)); // extensions dir434char *buf = NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);435436// sysclasspath, java_home, dll_dir437{438char *pslash;439os::jvm_path(buf, bufsize);440441// Found the full path to libjvm.so.442// Now cut the path to <java_home>/jre if we can.443pslash = strrchr(buf, '/');444if (pslash != NULL) {445*pslash = '\0'; // Get rid of /libjvm.so.446}447pslash = strrchr(buf, '/');448if (pslash != NULL) {449*pslash = '\0'; // Get rid of /{client|server|hotspot}.450}451Arguments::set_dll_dir(buf);452453if (pslash != NULL) {454pslash = strrchr(buf, '/');455if (pslash != NULL) {456*pslash = '\0'; // Get rid of /lib.457}458}459Arguments::set_java_home(buf);460if (!set_boot_path('/', ':')) {461vm_exit_during_initialization("Failed setting boot class path.", NULL);462}463}464465// Where to look for native libraries.466//467// Note: Due to a legacy implementation, most of the library path468// is set in the launcher. This was to accomodate linking restrictions469// on legacy Linux implementations (which are no longer supported).470// Eventually, all the library path setting will be done here.471//472// However, to prevent the proliferation of improperly built native473// libraries, the new path component /usr/java/packages is added here.474// Eventually, all the library path setting will be done here.475{476// Get the user setting of LD_LIBRARY_PATH, and prepended it. It477// should always exist (until the legacy problem cited above is478// addressed).479const char *v = ::getenv("LD_LIBRARY_PATH");480const char *v_colon = ":";481if (v == NULL) { v = ""; v_colon = ""; }482// That's +1 for the colon and +1 for the trailing '\0'.483char *ld_library_path = NEW_C_HEAP_ARRAY(char,484strlen(v) + 1 +485sizeof(SYS_EXT_DIR) + sizeof("/lib/") + sizeof(DEFAULT_LIBPATH) + 1,486mtInternal);487sprintf(ld_library_path, "%s%s" SYS_EXT_DIR "/lib:" DEFAULT_LIBPATH, v, v_colon);488Arguments::set_library_path(ld_library_path);489FREE_C_HEAP_ARRAY(char, ld_library_path);490}491492// Extensions directories.493sprintf(buf, "%s" EXTENSIONS_DIR ":" SYS_EXT_DIR EXTENSIONS_DIR, Arguments::get_java_home());494Arguments::set_ext_dirs(buf);495496FREE_C_HEAP_ARRAY(char, buf);497498#undef DEFAULT_LIBPATH499#undef SYS_EXT_DIR500#undef EXTENSIONS_DIR501}502503////////////////////////////////////////////////////////////////////////////////504// breakpoint support505506void os::breakpoint() {507BREAKPOINT;508}509510extern "C" void breakpoint() {511// use debugger to set breakpoint here512}513514//////////////////////////////////////////////////////////////////////////////515// detecting pthread library516517void os::Linux::libpthread_init() {518// Save glibc and pthread version strings.519#if !defined(_CS_GNU_LIBC_VERSION) || \520!defined(_CS_GNU_LIBPTHREAD_VERSION)521#error "glibc too old (< 2.3.2)"522#endif523524#ifdef MUSL_LIBC525// confstr() from musl libc returns EINVAL for526// _CS_GNU_LIBC_VERSION and _CS_GNU_LIBPTHREAD_VERSION527os::Linux::set_libc_version("musl - unknown");528os::Linux::set_libpthread_version("musl - unknown");529#else530size_t n = confstr(_CS_GNU_LIBC_VERSION, NULL, 0);531assert(n > 0, "cannot retrieve glibc version");532char *str = (char *)malloc(n, mtInternal);533confstr(_CS_GNU_LIBC_VERSION, str, n);534os::Linux::set_libc_version(str);535536n = confstr(_CS_GNU_LIBPTHREAD_VERSION, NULL, 0);537assert(n > 0, "cannot retrieve pthread version");538str = (char *)malloc(n, mtInternal);539confstr(_CS_GNU_LIBPTHREAD_VERSION, str, n);540os::Linux::set_libpthread_version(str);541#endif542}543544/////////////////////////////////////////////////////////////////////////////545// thread stack expansion546547// os::Linux::manually_expand_stack() takes care of expanding the thread548// stack. Note that this is normally not needed: pthread stacks allocate549// thread stack using mmap() without MAP_NORESERVE, so the stack is already550// committed. Therefore it is not necessary to expand the stack manually.551//552// Manually expanding the stack was historically needed on LinuxThreads553// thread stacks, which were allocated with mmap(MAP_GROWSDOWN). Nowadays554// it is kept to deal with very rare corner cases:555//556// For one, user may run the VM on an own implementation of threads557// whose stacks are - like the old LinuxThreads - implemented using558// mmap(MAP_GROWSDOWN).559//560// Also, this coding may be needed if the VM is running on the primordial561// thread. Normally we avoid running on the primordial thread; however,562// user may still invoke the VM on the primordial thread.563//564// The following historical comment describes the details about running565// on a thread stack allocated with mmap(MAP_GROWSDOWN):566567568// Force Linux kernel to expand current thread stack. If "bottom" is close569// to the stack guard, caller should block all signals.570//571// MAP_GROWSDOWN:572// A special mmap() flag that is used to implement thread stacks. It tells573// kernel that the memory region should extend downwards when needed. This574// allows early versions of LinuxThreads to only mmap the first few pages575// when creating a new thread. Linux kernel will automatically expand thread576// stack as needed (on page faults).577//578// However, because the memory region of a MAP_GROWSDOWN stack can grow on579// demand, if a page fault happens outside an already mapped MAP_GROWSDOWN580// region, it's hard to tell if the fault is due to a legitimate stack581// access or because of reading/writing non-exist memory (e.g. buffer582// overrun). As a rule, if the fault happens below current stack pointer,583// Linux kernel does not expand stack, instead a SIGSEGV is sent to the584// application (see Linux kernel fault.c).585//586// This Linux feature can cause SIGSEGV when VM bangs thread stack for587// stack overflow detection.588//589// Newer version of LinuxThreads (since glibc-2.2, or, RH-7.x) and NPTL do590// not use MAP_GROWSDOWN.591//592// To get around the problem and allow stack banging on Linux, we need to593// manually expand thread stack after receiving the SIGSEGV.594//595// There are two ways to expand thread stack to address "bottom", we used596// both of them in JVM before 1.5:597// 1. adjust stack pointer first so that it is below "bottom", and then598// touch "bottom"599// 2. mmap() the page in question600//601// Now alternate signal stack is gone, it's harder to use 2. For instance,602// if current sp is already near the lower end of page 101, and we need to603// call mmap() to map page 100, it is possible that part of the mmap() frame604// will be placed in page 100. When page 100 is mapped, it is zero-filled.605// That will destroy the mmap() frame and cause VM to crash.606//607// The following code works by adjusting sp first, then accessing the "bottom"608// page to force a page fault. Linux kernel will then automatically expand the609// stack mapping.610//611// _expand_stack_to() assumes its frame size is less than page size, which612// should always be true if the function is not inlined.613614static void NOINLINE _expand_stack_to(address bottom) {615address sp;616size_t size;617volatile char *p;618619// Adjust bottom to point to the largest address within the same page, it620// gives us a one-page buffer if alloca() allocates slightly more memory.621bottom = (address)align_down((uintptr_t)bottom, os::Linux::page_size());622bottom += os::Linux::page_size() - 1;623624// sp might be slightly above current stack pointer; if that's the case, we625// will alloca() a little more space than necessary, which is OK. Don't use626// os::current_stack_pointer(), as its result can be slightly below current627// stack pointer, causing us to not alloca enough to reach "bottom".628sp = (address)&sp;629630if (sp > bottom) {631size = sp - bottom;632p = (volatile char *)alloca(size);633assert(p != NULL && p <= (volatile char *)bottom, "alloca problem?");634p[0] = '\0';635}636}637638void os::Linux::expand_stack_to(address bottom) {639_expand_stack_to(bottom);640}641642bool os::Linux::manually_expand_stack(JavaThread * t, address addr) {643assert(t!=NULL, "just checking");644assert(t->osthread()->expanding_stack(), "expand should be set");645646if (t->is_in_usable_stack(addr)) {647sigset_t mask_all, old_sigset;648sigfillset(&mask_all);649pthread_sigmask(SIG_SETMASK, &mask_all, &old_sigset);650_expand_stack_to(addr);651pthread_sigmask(SIG_SETMASK, &old_sigset, NULL);652return true;653}654return false;655}656657//////////////////////////////////////////////////////////////////////////////658// create new thread659660// Thread start routine for all newly created threads661static void *thread_native_entry(Thread *thread) {662663thread->record_stack_base_and_size();664665#ifndef __GLIBC__666// Try to randomize the cache line index of hot stack frames.667// This helps when threads of the same stack traces evict each other's668// cache lines. The threads can be either from the same JVM instance, or669// from different JVM instances. The benefit is especially true for670// processors with hyperthreading technology.671// This code is not needed anymore in glibc because it has MULTI_PAGE_ALIASING672// and we did not see any degradation in performance without `alloca()`.673static int counter = 0;674int pid = os::current_process_id();675int random = ((pid ^ counter++) & 7) * 128;676void *stackmem = alloca(random != 0 ? random : 1); // ensure we allocate > 0677// Ensure the alloca result is used in a way that prevents the compiler from eliding it.678*(char *)stackmem = 1;679#endif680681thread->initialize_thread_current();682683OSThread* osthread = thread->osthread();684Monitor* sync = osthread->startThread_lock();685686osthread->set_thread_id(os::current_thread_id());687688if (UseNUMA) {689int lgrp_id = os::numa_get_group_id();690if (lgrp_id != -1) {691thread->set_lgrp_id(lgrp_id);692}693}694// initialize signal mask for this thread695PosixSignals::hotspot_sigmask(thread);696697// initialize floating point control register698os::Linux::init_thread_fpu_state();699700// handshaking with parent thread701{702MutexLocker ml(sync, Mutex::_no_safepoint_check_flag);703704// notify parent thread705osthread->set_state(INITIALIZED);706sync->notify_all();707708// wait until os::start_thread()709while (osthread->get_state() == INITIALIZED) {710sync->wait_without_safepoint_check();711}712}713714log_info(os, thread)("Thread is alive (tid: " UINTX_FORMAT ", pthread id: " UINTX_FORMAT ").",715os::current_thread_id(), (uintx) pthread_self());716717assert(osthread->pthread_id() != 0, "pthread_id was not set as expected");718719// call one more level start routine720thread->call_run();721722// Note: at this point the thread object may already have deleted itself.723// Prevent dereferencing it from here on out.724thread = NULL;725726log_info(os, thread)("Thread finished (tid: " UINTX_FORMAT ", pthread id: " UINTX_FORMAT ").",727os::current_thread_id(), (uintx) pthread_self());728729return 0;730}731732// On Linux, glibc places static TLS blocks (for __thread variables) on733// the thread stack. This decreases the stack size actually available734// to threads.735//736// For large static TLS sizes, this may cause threads to malfunction due737// to insufficient stack space. This is a well-known issue in glibc:738// http://sourceware.org/bugzilla/show_bug.cgi?id=11787.739//740// As a workaround, we call a private but assumed-stable glibc function,741// __pthread_get_minstack() to obtain the minstack size and derive the742// static TLS size from it. We then increase the user requested stack743// size by this TLS size.744//745// Due to compatibility concerns, this size adjustment is opt-in and746// controlled via AdjustStackSizeForTLS.747typedef size_t (*GetMinStack)(const pthread_attr_t *attr);748749GetMinStack _get_minstack_func = NULL;750751static void get_minstack_init() {752_get_minstack_func =753(GetMinStack)dlsym(RTLD_DEFAULT, "__pthread_get_minstack");754log_info(os, thread)("Lookup of __pthread_get_minstack %s",755_get_minstack_func == NULL ? "failed" : "succeeded");756}757758// Returns the size of the static TLS area glibc puts on thread stacks.759// The value is cached on first use, which occurs when the first thread760// is created during VM initialization.761static size_t get_static_tls_area_size(const pthread_attr_t *attr) {762size_t tls_size = 0;763if (_get_minstack_func != NULL) {764// Obtain the pthread minstack size by calling __pthread_get_minstack.765size_t minstack_size = _get_minstack_func(attr);766767// Remove non-TLS area size included in minstack size returned768// by __pthread_get_minstack() to get the static TLS size.769// In glibc before 2.27, minstack size includes guard_size.770// In glibc 2.27 and later, guard_size is automatically added771// to the stack size by pthread_create and is no longer included772// in minstack size. In both cases, the guard_size is taken into773// account, so there is no need to adjust the result for that.774//775// Although __pthread_get_minstack() is a private glibc function,776// it is expected to have a stable behavior across future glibc777// versions while glibc still allocates the static TLS blocks off778// the stack. Following is glibc 2.28 __pthread_get_minstack():779//780// size_t781// __pthread_get_minstack (const pthread_attr_t *attr)782// {783// return GLRO(dl_pagesize) + __static_tls_size + PTHREAD_STACK_MIN;784// }785//786//787// The following 'minstack_size > os::vm_page_size() + PTHREAD_STACK_MIN'788// if check is done for precaution.789if (minstack_size > (size_t)os::vm_page_size() + PTHREAD_STACK_MIN) {790tls_size = minstack_size - os::vm_page_size() - PTHREAD_STACK_MIN;791}792}793794log_info(os, thread)("Stack size adjustment for TLS is " SIZE_FORMAT,795tls_size);796return tls_size;797}798799bool os::create_thread(Thread* thread, ThreadType thr_type,800size_t req_stack_size) {801assert(thread->osthread() == NULL, "caller responsible");802803// Allocate the OSThread object804OSThread* osthread = new OSThread(NULL, NULL);805if (osthread == NULL) {806return false;807}808809// set the correct thread state810osthread->set_thread_type(thr_type);811812// Initial state is ALLOCATED but not INITIALIZED813osthread->set_state(ALLOCATED);814815thread->set_osthread(osthread);816817// init thread attributes818pthread_attr_t attr;819pthread_attr_init(&attr);820pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);821822// Calculate stack size if it's not specified by caller.823size_t stack_size = os::Posix::get_initial_stack_size(thr_type, req_stack_size);824// In glibc versions prior to 2.7 the guard size mechanism825// is not implemented properly. The posix standard requires adding826// the size of the guard pages to the stack size, instead Linux827// takes the space out of 'stacksize'. Thus we adapt the requested828// stack_size by the size of the guard pages to mimick proper829// behaviour. However, be careful not to end up with a size830// of zero due to overflow. Don't add the guard page in that case.831size_t guard_size = os::Linux::default_guard_size(thr_type);832// Configure glibc guard page. Must happen before calling833// get_static_tls_area_size(), which uses the guard_size.834pthread_attr_setguardsize(&attr, guard_size);835836size_t stack_adjust_size = 0;837if (AdjustStackSizeForTLS) {838// Adjust the stack_size for on-stack TLS - see get_static_tls_area_size().839stack_adjust_size += get_static_tls_area_size(&attr);840} else {841stack_adjust_size += guard_size;842}843844stack_adjust_size = align_up(stack_adjust_size, os::vm_page_size());845if (stack_size <= SIZE_MAX - stack_adjust_size) {846stack_size += stack_adjust_size;847}848assert(is_aligned(stack_size, os::vm_page_size()), "stack_size not aligned");849850int status = pthread_attr_setstacksize(&attr, stack_size);851if (status != 0) {852// pthread_attr_setstacksize() function can fail853// if the stack size exceeds a system-imposed limit.854assert_status(status == EINVAL, status, "pthread_attr_setstacksize");855log_warning(os, thread)("The %sthread stack size specified is invalid: " SIZE_FORMAT "k",856(thr_type == compiler_thread) ? "compiler " : ((thr_type == java_thread) ? "" : "VM "),857stack_size / K);858thread->set_osthread(NULL);859delete osthread;860return false;861}862863ThreadState state;864865{866ResourceMark rm;867pthread_t tid;868int ret = 0;869int limit = 3;870do {871ret = pthread_create(&tid, &attr, (void* (*)(void*)) thread_native_entry, thread);872} while (ret == EAGAIN && limit-- > 0);873874char buf[64];875if (ret == 0) {876log_info(os, thread)("Thread \"%s\" started (pthread id: " UINTX_FORMAT ", attributes: %s). ",877thread->name(), (uintx) tid, os::Posix::describe_pthread_attr(buf, sizeof(buf), &attr));878} else {879log_warning(os, thread)("Failed to start thread \"%s\" - pthread_create failed (%s) for attributes: %s.",880thread->name(), os::errno_name(ret), os::Posix::describe_pthread_attr(buf, sizeof(buf), &attr));881// Log some OS information which might explain why creating the thread failed.882log_info(os, thread)("Number of threads approx. running in the VM: %d", Threads::number_of_threads());883LogStream st(Log(os, thread)::info());884os::Posix::print_rlimit_info(&st);885os::print_memory_info(&st);886os::Linux::print_proc_sys_info(&st);887os::Linux::print_container_info(&st);888}889890pthread_attr_destroy(&attr);891892if (ret != 0) {893// Need to clean up stuff we've allocated so far894thread->set_osthread(NULL);895delete osthread;896return false;897}898899// Store pthread info into the OSThread900osthread->set_pthread_id(tid);901902// Wait until child thread is either initialized or aborted903{904Monitor* sync_with_child = osthread->startThread_lock();905MutexLocker ml(sync_with_child, Mutex::_no_safepoint_check_flag);906while ((state = osthread->get_state()) == ALLOCATED) {907sync_with_child->wait_without_safepoint_check();908}909}910}911912// The thread is returned suspended (in state INITIALIZED),913// and is started higher up in the call chain914assert(state == INITIALIZED, "race condition");915return true;916}917918/////////////////////////////////////////////////////////////////////////////919// attach existing thread920921// bootstrap the main thread922bool os::create_main_thread(JavaThread* thread) {923assert(os::Linux::_main_thread == pthread_self(), "should be called inside main thread");924return create_attached_thread(thread);925}926927bool os::create_attached_thread(JavaThread* thread) {928#ifdef ASSERT929thread->verify_not_published();930#endif931932// Allocate the OSThread object933OSThread* osthread = new OSThread(NULL, NULL);934935if (osthread == NULL) {936return false;937}938939// Store pthread info into the OSThread940osthread->set_thread_id(os::Linux::gettid());941osthread->set_pthread_id(::pthread_self());942943// initialize floating point control register944os::Linux::init_thread_fpu_state();945946// Initial thread state is RUNNABLE947osthread->set_state(RUNNABLE);948949thread->set_osthread(osthread);950951if (UseNUMA) {952int lgrp_id = os::numa_get_group_id();953if (lgrp_id != -1) {954thread->set_lgrp_id(lgrp_id);955}956}957958if (os::is_primordial_thread()) {959// If current thread is primordial thread, its stack is mapped on demand,960// see notes about MAP_GROWSDOWN. Here we try to force kernel to map961// the entire stack region to avoid SEGV in stack banging.962// It is also useful to get around the heap-stack-gap problem on SuSE963// kernel (see 4821821 for details). We first expand stack to the top964// of yellow zone, then enable stack yellow zone (order is significant,965// enabling yellow zone first will crash JVM on SuSE Linux), so there966// is no gap between the last two virtual memory regions.967968StackOverflow* overflow_state = thread->stack_overflow_state();969address addr = overflow_state->stack_reserved_zone_base();970assert(addr != NULL, "initialization problem?");971assert(overflow_state->stack_available(addr) > 0, "stack guard should not be enabled");972973osthread->set_expanding_stack();974os::Linux::manually_expand_stack(thread, addr);975osthread->clear_expanding_stack();976}977978// initialize signal mask for this thread979// and save the caller's signal mask980PosixSignals::hotspot_sigmask(thread);981982log_info(os, thread)("Thread attached (tid: " UINTX_FORMAT ", pthread id: " UINTX_FORMAT ").",983os::current_thread_id(), (uintx) pthread_self());984985return true;986}987988void os::pd_start_thread(Thread* thread) {989OSThread * osthread = thread->osthread();990assert(osthread->get_state() != INITIALIZED, "just checking");991Monitor* sync_with_child = osthread->startThread_lock();992MutexLocker ml(sync_with_child, Mutex::_no_safepoint_check_flag);993sync_with_child->notify();994}995996// Free Linux resources related to the OSThread997void os::free_thread(OSThread* osthread) {998assert(osthread != NULL, "osthread not set");9991000// We are told to free resources of the argument thread,1001// but we can only really operate on the current thread.1002assert(Thread::current()->osthread() == osthread,1003"os::free_thread but not current thread");10041005#ifdef ASSERT1006sigset_t current;1007sigemptyset(¤t);1008pthread_sigmask(SIG_SETMASK, NULL, ¤t);1009assert(!sigismember(¤t, PosixSignals::SR_signum), "SR signal should not be blocked!");1010#endif10111012// Restore caller's signal mask1013sigset_t sigmask = osthread->caller_sigmask();1014pthread_sigmask(SIG_SETMASK, &sigmask, NULL);10151016delete osthread;1017}10181019//////////////////////////////////////////////////////////////////////////////1020// primordial thread10211022// Check if current thread is the primordial thread, similar to Solaris thr_main.1023bool os::is_primordial_thread(void) {1024if (suppress_primordial_thread_resolution) {1025return false;1026}1027char dummy;1028// If called before init complete, thread stack bottom will be null.1029// Can be called if fatal error occurs before initialization.1030if (os::Linux::initial_thread_stack_bottom() == NULL) return false;1031assert(os::Linux::initial_thread_stack_bottom() != NULL &&1032os::Linux::initial_thread_stack_size() != 0,1033"os::init did not locate primordial thread's stack region");1034if ((address)&dummy >= os::Linux::initial_thread_stack_bottom() &&1035(address)&dummy < os::Linux::initial_thread_stack_bottom() +1036os::Linux::initial_thread_stack_size()) {1037return true;1038} else {1039return false;1040}1041}10421043// Find the virtual memory area that contains addr1044static bool find_vma(address addr, address* vma_low, address* vma_high) {1045FILE *fp = fopen("/proc/self/maps", "r");1046if (fp) {1047address low, high;1048while (!feof(fp)) {1049if (fscanf(fp, "%p-%p", &low, &high) == 2) {1050if (low <= addr && addr < high) {1051if (vma_low) *vma_low = low;1052if (vma_high) *vma_high = high;1053fclose(fp);1054return true;1055}1056}1057for (;;) {1058int ch = fgetc(fp);1059if (ch == EOF || ch == (int)'\n') break;1060}1061}1062fclose(fp);1063}1064return false;1065}10661067// Locate primordial thread stack. This special handling of primordial thread stack1068// is needed because pthread_getattr_np() on most (all?) Linux distros returns1069// bogus value for the primordial process thread. While the launcher has created1070// the VM in a new thread since JDK 6, we still have to allow for the use of the1071// JNI invocation API from a primordial thread.1072void os::Linux::capture_initial_stack(size_t max_size) {10731074// max_size is either 0 (which means accept OS default for thread stacks) or1075// a user-specified value known to be at least the minimum needed. If we1076// are actually on the primordial thread we can make it appear that we have a1077// smaller max_size stack by inserting the guard pages at that location. But we1078// cannot do anything to emulate a larger stack than what has been provided by1079// the OS or threading library. In fact if we try to use a stack greater than1080// what is set by rlimit then we will crash the hosting process.10811082// Maximum stack size is the easy part, get it from RLIMIT_STACK.1083// If this is "unlimited" then it will be a huge value.1084struct rlimit rlim;1085getrlimit(RLIMIT_STACK, &rlim);1086size_t stack_size = rlim.rlim_cur;10871088// 6308388: a bug in ld.so will relocate its own .data section to the1089// lower end of primordial stack; reduce ulimit -s value a little bit1090// so we won't install guard page on ld.so's data section.1091// But ensure we don't underflow the stack size - allow 1 page spare1092if (stack_size >= (size_t)(3 * page_size())) {1093stack_size -= 2 * page_size();1094}10951096// Try to figure out where the stack base (top) is. This is harder.1097//1098// When an application is started, glibc saves the initial stack pointer in1099// a global variable "__libc_stack_end", which is then used by system1100// libraries. __libc_stack_end should be pretty close to stack top. The1101// variable is available since the very early days. However, because it is1102// a private interface, it could disappear in the future.1103//1104// Linux kernel saves start_stack information in /proc/<pid>/stat. Similar1105// to __libc_stack_end, it is very close to stack top, but isn't the real1106// stack top. Note that /proc may not exist if VM is running as a chroot1107// program, so reading /proc/<pid>/stat could fail. Also the contents of1108// /proc/<pid>/stat could change in the future (though unlikely).1109//1110// We try __libc_stack_end first. If that doesn't work, look for1111// /proc/<pid>/stat. If neither of them works, we use current stack pointer1112// as a hint, which should work well in most cases.11131114uintptr_t stack_start;11151116// try __libc_stack_end first1117uintptr_t *p = (uintptr_t *)dlsym(RTLD_DEFAULT, "__libc_stack_end");1118if (p && *p) {1119stack_start = *p;1120} else {1121// see if we can get the start_stack field from /proc/self/stat1122FILE *fp;1123int pid;1124char state;1125int ppid;1126int pgrp;1127int session;1128int nr;1129int tpgrp;1130unsigned long flags;1131unsigned long minflt;1132unsigned long cminflt;1133unsigned long majflt;1134unsigned long cmajflt;1135unsigned long utime;1136unsigned long stime;1137long cutime;1138long cstime;1139long prio;1140long nice;1141long junk;1142long it_real;1143uintptr_t start;1144uintptr_t vsize;1145intptr_t rss;1146uintptr_t rsslim;1147uintptr_t scodes;1148uintptr_t ecode;1149int i;11501151// Figure what the primordial thread stack base is. Code is inspired1152// by email from Hans Boehm. /proc/self/stat begins with current pid,1153// followed by command name surrounded by parentheses, state, etc.1154char stat[2048];1155int statlen;11561157fp = fopen("/proc/self/stat", "r");1158if (fp) {1159statlen = fread(stat, 1, 2047, fp);1160stat[statlen] = '\0';1161fclose(fp);11621163// Skip pid and the command string. Note that we could be dealing with1164// weird command names, e.g. user could decide to rename java launcher1165// to "java 1.4.2 :)", then the stat file would look like1166// 1234 (java 1.4.2 :)) R ... ...1167// We don't really need to know the command string, just find the last1168// occurrence of ")" and then start parsing from there. See bug 4726580.1169char * s = strrchr(stat, ')');11701171i = 0;1172if (s) {1173// Skip blank chars1174do { s++; } while (s && isspace(*s));11751176#define _UFM UINTX_FORMAT1177#define _DFM INTX_FORMAT11781179// 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 21180// 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 81181i = sscanf(s, "%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu %ld %ld %ld %ld %ld %ld " _UFM _UFM _DFM _UFM _UFM _UFM _UFM,1182&state, // 3 %c1183&ppid, // 4 %d1184&pgrp, // 5 %d1185&session, // 6 %d1186&nr, // 7 %d1187&tpgrp, // 8 %d1188&flags, // 9 %lu1189&minflt, // 10 %lu1190&cminflt, // 11 %lu1191&majflt, // 12 %lu1192&cmajflt, // 13 %lu1193&utime, // 14 %lu1194&stime, // 15 %lu1195&cutime, // 16 %ld1196&cstime, // 17 %ld1197&prio, // 18 %ld1198&nice, // 19 %ld1199&junk, // 20 %ld1200&it_real, // 21 %ld1201&start, // 22 UINTX_FORMAT1202&vsize, // 23 UINTX_FORMAT1203&rss, // 24 INTX_FORMAT1204&rsslim, // 25 UINTX_FORMAT1205&scodes, // 26 UINTX_FORMAT1206&ecode, // 27 UINTX_FORMAT1207&stack_start); // 28 UINTX_FORMAT1208}12091210#undef _UFM1211#undef _DFM12121213if (i != 28 - 2) {1214assert(false, "Bad conversion from /proc/self/stat");1215// product mode - assume we are the primordial thread, good luck in the1216// embedded case.1217warning("Can't detect primordial thread stack location - bad conversion");1218stack_start = (uintptr_t) &rlim;1219}1220} else {1221// For some reason we can't open /proc/self/stat (for example, running on1222// FreeBSD with a Linux emulator, or inside chroot), this should work for1223// most cases, so don't abort:1224warning("Can't detect primordial thread stack location - no /proc/self/stat");1225stack_start = (uintptr_t) &rlim;1226}1227}12281229// Now we have a pointer (stack_start) very close to the stack top, the1230// next thing to do is to figure out the exact location of stack top. We1231// can find out the virtual memory area that contains stack_start by1232// reading /proc/self/maps, it should be the last vma in /proc/self/maps,1233// and its upper limit is the real stack top. (again, this would fail if1234// running inside chroot, because /proc may not exist.)12351236uintptr_t stack_top;1237address low, high;1238if (find_vma((address)stack_start, &low, &high)) {1239// success, "high" is the true stack top. (ignore "low", because initial1240// thread stack grows on demand, its real bottom is high - RLIMIT_STACK.)1241stack_top = (uintptr_t)high;1242} else {1243// failed, likely because /proc/self/maps does not exist1244warning("Can't detect primordial thread stack location - find_vma failed");1245// best effort: stack_start is normally within a few pages below the real1246// stack top, use it as stack top, and reduce stack size so we won't put1247// guard page outside stack.1248stack_top = stack_start;1249stack_size -= 16 * page_size();1250}12511252// stack_top could be partially down the page so align it1253stack_top = align_up(stack_top, page_size());12541255// Allowed stack value is minimum of max_size and what we derived from rlimit1256if (max_size > 0) {1257_initial_thread_stack_size = MIN2(max_size, stack_size);1258} else {1259// Accept the rlimit max, but if stack is unlimited then it will be huge, so1260// clamp it at 8MB as we do on Solaris1261_initial_thread_stack_size = MIN2(stack_size, 8*M);1262}1263_initial_thread_stack_size = align_down(_initial_thread_stack_size, page_size());1264_initial_thread_stack_bottom = (address)stack_top - _initial_thread_stack_size;12651266assert(_initial_thread_stack_bottom < (address)stack_top, "overflow!");12671268if (log_is_enabled(Info, os, thread)) {1269// See if we seem to be on primordial process thread1270bool primordial = uintptr_t(&rlim) > uintptr_t(_initial_thread_stack_bottom) &&1271uintptr_t(&rlim) < stack_top;12721273log_info(os, thread)("Capturing initial stack in %s thread: req. size: " SIZE_FORMAT "K, actual size: "1274SIZE_FORMAT "K, top=" INTPTR_FORMAT ", bottom=" INTPTR_FORMAT,1275primordial ? "primordial" : "user", max_size / K, _initial_thread_stack_size / K,1276stack_top, intptr_t(_initial_thread_stack_bottom));1277}1278}12791280////////////////////////////////////////////////////////////////////////////////1281// time support12821283// Time since start-up in seconds to a fine granularity.1284double os::elapsedTime() {1285return ((double)os::elapsed_counter()) / os::elapsed_frequency(); // nanosecond resolution1286}12871288jlong os::elapsed_counter() {1289return javaTimeNanos() - initial_time_count;1290}12911292jlong os::elapsed_frequency() {1293return NANOSECS_PER_SEC; // nanosecond resolution1294}12951296bool os::supports_vtime() { return true; }12971298double os::elapsedVTime() {1299struct rusage usage;1300int retval = getrusage(RUSAGE_THREAD, &usage);1301if (retval == 0) {1302return (double) (usage.ru_utime.tv_sec + usage.ru_stime.tv_sec) + (double) (usage.ru_utime.tv_usec + usage.ru_stime.tv_usec) / (1000 * 1000);1303} else {1304// better than nothing, but not much1305return elapsedTime();1306}1307}13081309void os::Linux::fast_thread_clock_init() {1310if (!UseLinuxPosixThreadCPUClocks) {1311return;1312}1313clockid_t clockid;1314struct timespec tp;1315int (*pthread_getcpuclockid_func)(pthread_t, clockid_t *) =1316(int(*)(pthread_t, clockid_t *)) dlsym(RTLD_DEFAULT, "pthread_getcpuclockid");13171318// Switch to using fast clocks for thread cpu time if1319// the clock_getres() returns 0 error code.1320// Note, that some kernels may support the current thread1321// clock (CLOCK_THREAD_CPUTIME_ID) but not the clocks1322// returned by the pthread_getcpuclockid().1323// If the fast Posix clocks are supported then the clock_getres()1324// must return at least tp.tv_sec == 0 which means a resolution1325// better than 1 sec. This is extra check for reliability.13261327if (pthread_getcpuclockid_func &&1328pthread_getcpuclockid_func(_main_thread, &clockid) == 0 &&1329clock_getres(clockid, &tp) == 0 && tp.tv_sec == 0) {1330_supports_fast_thread_cpu_time = true;1331_pthread_getcpuclockid = pthread_getcpuclockid_func;1332}1333}13341335// Return the real, user, and system times in seconds from an1336// arbitrary fixed point in the past.1337bool os::getTimesSecs(double* process_real_time,1338double* process_user_time,1339double* process_system_time) {1340struct tms ticks;1341clock_t real_ticks = times(&ticks);13421343if (real_ticks == (clock_t) (-1)) {1344return false;1345} else {1346double ticks_per_second = (double) clock_tics_per_sec;1347*process_user_time = ((double) ticks.tms_utime) / ticks_per_second;1348*process_system_time = ((double) ticks.tms_stime) / ticks_per_second;1349*process_real_time = ((double) real_ticks) / ticks_per_second;13501351return true;1352}1353}135413551356char * os::local_time_string(char *buf, size_t buflen) {1357struct tm t;1358time_t long_time;1359time(&long_time);1360localtime_r(&long_time, &t);1361jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d",1362t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,1363t.tm_hour, t.tm_min, t.tm_sec);1364return buf;1365}13661367struct tm* os::localtime_pd(const time_t* clock, struct tm* res) {1368return localtime_r(clock, res);1369}13701371// thread_id is kernel thread id (similar to Solaris LWP id)1372intx os::current_thread_id() { return os::Linux::gettid(); }1373int os::current_process_id() {1374return ::getpid();1375}13761377// DLL functions13781379const char* os::dll_file_extension() { return ".so"; }13801381// This must be hard coded because it's the system's temporary1382// directory not the java application's temp directory, ala java.io.tmpdir.1383const char* os::get_temp_directory() { return "/tmp"; }13841385static bool file_exists(const char* filename) {1386struct stat statbuf;1387if (filename == NULL || strlen(filename) == 0) {1388return false;1389}1390return os::stat(filename, &statbuf) == 0;1391}13921393// check if addr is inside libjvm.so1394bool os::address_is_in_vm(address addr) {1395static address libjvm_base_addr;1396Dl_info dlinfo;13971398if (libjvm_base_addr == NULL) {1399if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) {1400libjvm_base_addr = (address)dlinfo.dli_fbase;1401}1402assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm");1403}14041405if (dladdr((void *)addr, &dlinfo) != 0) {1406if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true;1407}14081409return false;1410}14111412bool os::dll_address_to_function_name(address addr, char *buf,1413int buflen, int *offset,1414bool demangle) {1415// buf is not optional, but offset is optional1416assert(buf != NULL, "sanity check");14171418Dl_info dlinfo;14191420if (dladdr((void*)addr, &dlinfo) != 0) {1421// see if we have a matching symbol1422if (dlinfo.dli_saddr != NULL && dlinfo.dli_sname != NULL) {1423if (!(demangle && Decoder::demangle(dlinfo.dli_sname, buf, buflen))) {1424jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname);1425}1426if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;1427return true;1428}1429// no matching symbol so try for just file info1430if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) {1431if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),1432buf, buflen, offset, dlinfo.dli_fname, demangle)) {1433return true;1434}1435}1436}14371438buf[0] = '\0';1439if (offset != NULL) *offset = -1;1440return false;1441}14421443struct _address_to_library_name {1444address addr; // input : memory address1445size_t buflen; // size of fname1446char* fname; // output: library name1447address base; // library base addr1448};14491450static int address_to_library_name_callback(struct dl_phdr_info *info,1451size_t size, void *data) {1452int i;1453bool found = false;1454address libbase = NULL;1455struct _address_to_library_name * d = (struct _address_to_library_name *)data;14561457// iterate through all loadable segments1458for (i = 0; i < info->dlpi_phnum; i++) {1459address segbase = (address)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);1460if (info->dlpi_phdr[i].p_type == PT_LOAD) {1461// base address of a library is the lowest address of its loaded1462// segments.1463if (libbase == NULL || libbase > segbase) {1464libbase = segbase;1465}1466// see if 'addr' is within current segment1467if (segbase <= d->addr &&1468d->addr < segbase + info->dlpi_phdr[i].p_memsz) {1469found = true;1470}1471}1472}14731474// dlpi_name is NULL or empty if the ELF file is executable, return 01475// so dll_address_to_library_name() can fall through to use dladdr() which1476// can figure out executable name from argv[0].1477if (found && info->dlpi_name && info->dlpi_name[0]) {1478d->base = libbase;1479if (d->fname) {1480jio_snprintf(d->fname, d->buflen, "%s", info->dlpi_name);1481}1482return 1;1483}1484return 0;1485}14861487bool os::dll_address_to_library_name(address addr, char* buf,1488int buflen, int* offset) {1489// buf is not optional, but offset is optional1490assert(buf != NULL, "sanity check");14911492Dl_info dlinfo;1493struct _address_to_library_name data;14941495// There is a bug in old glibc dladdr() implementation that it could resolve1496// to wrong library name if the .so file has a base address != NULL. Here1497// we iterate through the program headers of all loaded libraries to find1498// out which library 'addr' really belongs to. This workaround can be1499// removed once the minimum requirement for glibc is moved to 2.3.x.1500data.addr = addr;1501data.fname = buf;1502data.buflen = buflen;1503data.base = NULL;1504int rslt = dl_iterate_phdr(address_to_library_name_callback, (void *)&data);15051506if (rslt) {1507// buf already contains library name1508if (offset) *offset = addr - data.base;1509return true;1510}1511if (dladdr((void*)addr, &dlinfo) != 0) {1512if (dlinfo.dli_fname != NULL) {1513jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname);1514}1515if (dlinfo.dli_fbase != NULL && offset != NULL) {1516*offset = addr - (address)dlinfo.dli_fbase;1517}1518return true;1519}15201521buf[0] = '\0';1522if (offset) *offset = -1;1523return false;1524}15251526// Loads .dll/.so and1527// in case of error it checks if .dll/.so was built for the1528// same architecture as Hotspot is running on152915301531// Remember the stack's state. The Linux dynamic linker will change1532// the stack to 'executable' at most once, so we must safepoint only once.1533bool os::Linux::_stack_is_executable = false;15341535// VM operation that loads a library. This is necessary if stack protection1536// of the Java stacks can be lost during loading the library. If we1537// do not stop the Java threads, they can stack overflow before the stacks1538// are protected again.1539class VM_LinuxDllLoad: public VM_Operation {1540private:1541const char *_filename;1542char *_ebuf;1543int _ebuflen;1544void *_lib;1545public:1546VM_LinuxDllLoad(const char *fn, char *ebuf, int ebuflen) :1547_filename(fn), _ebuf(ebuf), _ebuflen(ebuflen), _lib(NULL) {}1548VMOp_Type type() const { return VMOp_LinuxDllLoad; }1549void doit() {1550_lib = os::Linux::dll_load_in_vmthread(_filename, _ebuf, _ebuflen);1551os::Linux::_stack_is_executable = true;1552}1553void* loaded_library() { return _lib; }1554};15551556void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {1557void * result = NULL;1558bool load_attempted = false;15591560log_info(os)("attempting shared library load of %s", filename);15611562// Check whether the library to load might change execution rights1563// of the stack. If they are changed, the protection of the stack1564// guard pages will be lost. We need a safepoint to fix this.1565//1566// See Linux man page execstack(8) for more info.1567if (os::uses_stack_guard_pages() && !os::Linux::_stack_is_executable) {1568if (!ElfFile::specifies_noexecstack(filename)) {1569if (!is_init_completed()) {1570os::Linux::_stack_is_executable = true;1571// This is OK - No Java threads have been created yet, and hence no1572// stack guard pages to fix.1573//1574// Dynamic loader will make all stacks executable after1575// this function returns, and will not do that again.1576assert(Threads::number_of_threads() == 0, "no Java threads should exist yet.");1577} else {1578warning("You have loaded library %s which might have disabled stack guard. "1579"The VM will try to fix the stack guard now.\n"1580"It's highly recommended that you fix the library with "1581"'execstack -c <libfile>', or link it with '-z noexecstack'.",1582filename);15831584JavaThread *jt = JavaThread::current();1585if (jt->thread_state() != _thread_in_native) {1586// This happens when a compiler thread tries to load a hsdis-<arch>.so file1587// that requires ExecStack. Cannot enter safe point. Let's give up.1588warning("Unable to fix stack guard. Giving up.");1589} else {1590if (!LoadExecStackDllInVMThread) {1591// This is for the case where the DLL has an static1592// constructor function that executes JNI code. We cannot1593// load such DLLs in the VMThread.1594result = os::Linux::dlopen_helper(filename, ebuf, ebuflen);1595}15961597ThreadInVMfromNative tiv(jt);1598debug_only(VMNativeEntryWrapper vew;)15991600VM_LinuxDllLoad op(filename, ebuf, ebuflen);1601VMThread::execute(&op);1602if (LoadExecStackDllInVMThread) {1603result = op.loaded_library();1604}1605load_attempted = true;1606}1607}1608}1609}16101611if (!load_attempted) {1612result = os::Linux::dlopen_helper(filename, ebuf, ebuflen);1613}16141615if (result != NULL) {1616// Successful loading1617return result;1618}16191620Elf32_Ehdr elf_head;1621int diag_msg_max_length=ebuflen-strlen(ebuf);1622char* diag_msg_buf=ebuf+strlen(ebuf);16231624if (diag_msg_max_length==0) {1625// No more space in ebuf for additional diagnostics message1626return NULL;1627}162816291630int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK);16311632if (file_descriptor < 0) {1633// Can't open library, report dlerror() message1634return NULL;1635}16361637bool failed_to_read_elf_head=1638(sizeof(elf_head)!=1639(::read(file_descriptor, &elf_head,sizeof(elf_head))));16401641::close(file_descriptor);1642if (failed_to_read_elf_head) {1643// file i/o error - report dlerror() msg1644return NULL;1645}16461647if (elf_head.e_ident[EI_DATA] != LITTLE_ENDIAN_ONLY(ELFDATA2LSB) BIG_ENDIAN_ONLY(ELFDATA2MSB)) {1648// handle invalid/out of range endianness values1649if (elf_head.e_ident[EI_DATA] == 0 || elf_head.e_ident[EI_DATA] > 2) {1650return NULL;1651}16521653#if defined(VM_LITTLE_ENDIAN)1654// VM is LE, shared object BE1655elf_head.e_machine = be16toh(elf_head.e_machine);1656#else1657// VM is BE, shared object LE1658elf_head.e_machine = le16toh(elf_head.e_machine);1659#endif1660}16611662typedef struct {1663Elf32_Half code; // Actual value as defined in elf.h1664Elf32_Half compat_class; // Compatibility of archs at VM's sense1665unsigned char elf_class; // 32 or 64 bit1666unsigned char endianness; // MSB or LSB1667char* name; // String representation1668} arch_t;16691670#ifndef EM_AARCH641671#define EM_AARCH64 183 /* ARM AARCH64 */1672#endif1673#ifndef EM_RISCV1674#define EM_RISCV 243 /* RISC-V */1675#endif1676#ifndef EM_LOONGARCH1677#define EM_LOONGARCH 258 /* LoongArch */1678#endif16791680static const arch_t arch_array[]={1681{EM_386, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},1682{EM_486, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},1683{EM_IA_64, EM_IA_64, ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"},1684{EM_X86_64, EM_X86_64, ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"},1685{EM_SPARC, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},1686{EM_SPARC32PLUS, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},1687{EM_SPARCV9, EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"},1688{EM_PPC, EM_PPC, ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"},1689#if defined(VM_LITTLE_ENDIAN)1690{EM_PPC64, EM_PPC64, ELFCLASS64, ELFDATA2LSB, (char*)"Power PC 64 LE"},1691{EM_SH, EM_SH, ELFCLASS32, ELFDATA2LSB, (char*)"SuperH"},1692#else1693{EM_PPC64, EM_PPC64, ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},1694{EM_SH, EM_SH, ELFCLASS32, ELFDATA2MSB, (char*)"SuperH BE"},1695#endif1696{EM_ARM, EM_ARM, ELFCLASS32, ELFDATA2LSB, (char*)"ARM"},1697// we only support 64 bit z architecture1698{EM_S390, EM_S390, ELFCLASS64, ELFDATA2MSB, (char*)"IBM System/390"},1699{EM_ALPHA, EM_ALPHA, ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"},1700{EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"},1701{EM_MIPS, EM_MIPS, ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"},1702{EM_PARISC, EM_PARISC, ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"},1703{EM_68K, EM_68K, ELFCLASS32, ELFDATA2MSB, (char*)"M68k"},1704{EM_AARCH64, EM_AARCH64, ELFCLASS64, ELFDATA2LSB, (char*)"AARCH64"},1705{EM_RISCV, EM_RISCV, ELFCLASS64, ELFDATA2LSB, (char*)"RISC-V"},1706{EM_LOONGARCH, EM_LOONGARCH, ELFCLASS64, ELFDATA2LSB, (char*)"LoongArch"},1707};17081709#if (defined IA32)1710static Elf32_Half running_arch_code=EM_386;1711#elif (defined AMD64) || (defined X32)1712static Elf32_Half running_arch_code=EM_X86_64;1713#elif (defined IA64)1714static Elf32_Half running_arch_code=EM_IA_64;1715#elif (defined __sparc) && (defined _LP64)1716static Elf32_Half running_arch_code=EM_SPARCV9;1717#elif (defined __sparc) && (!defined _LP64)1718static Elf32_Half running_arch_code=EM_SPARC;1719#elif (defined __powerpc64__)1720static Elf32_Half running_arch_code=EM_PPC64;1721#elif (defined __powerpc__)1722static Elf32_Half running_arch_code=EM_PPC;1723#elif (defined AARCH64)1724static Elf32_Half running_arch_code=EM_AARCH64;1725#elif (defined ARM)1726static Elf32_Half running_arch_code=EM_ARM;1727#elif (defined S390)1728static Elf32_Half running_arch_code=EM_S390;1729#elif (defined ALPHA)1730static Elf32_Half running_arch_code=EM_ALPHA;1731#elif (defined MIPSEL)1732static Elf32_Half running_arch_code=EM_MIPS_RS3_LE;1733#elif (defined PARISC)1734static Elf32_Half running_arch_code=EM_PARISC;1735#elif (defined MIPS)1736static Elf32_Half running_arch_code=EM_MIPS;1737#elif (defined M68K)1738static Elf32_Half running_arch_code=EM_68K;1739#elif (defined SH)1740static Elf32_Half running_arch_code=EM_SH;1741#elif (defined RISCV)1742static Elf32_Half running_arch_code=EM_RISCV;1743#elif (defined LOONGARCH)1744static Elf32_Half running_arch_code=EM_LOONGARCH;1745#else1746#error Method os::dll_load requires that one of following is defined:\1747AARCH64, ALPHA, ARM, AMD64, IA32, IA64, LOONGARCH, M68K, MIPS, MIPSEL, PARISC, __powerpc__, __powerpc64__, RISCV, S390, SH, __sparc1748#endif17491750// Identify compatibility class for VM's architecture and library's architecture1751// Obtain string descriptions for architectures17521753arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL};1754int running_arch_index=-1;17551756for (unsigned int i=0; i < ARRAY_SIZE(arch_array); i++) {1757if (running_arch_code == arch_array[i].code) {1758running_arch_index = i;1759}1760if (lib_arch.code == arch_array[i].code) {1761lib_arch.compat_class = arch_array[i].compat_class;1762lib_arch.name = arch_array[i].name;1763}1764}17651766assert(running_arch_index != -1,1767"Didn't find running architecture code (running_arch_code) in arch_array");1768if (running_arch_index == -1) {1769// Even though running architecture detection failed1770// we may still continue with reporting dlerror() message1771return NULL;1772}17731774if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {1775if (lib_arch.name != NULL) {1776::snprintf(diag_msg_buf, diag_msg_max_length-1,1777" (Possible cause: can't load %s .so on a %s platform)",1778lib_arch.name, arch_array[running_arch_index].name);1779} else {1780::snprintf(diag_msg_buf, diag_msg_max_length-1,1781" (Possible cause: can't load this .so (machine code=0x%x) on a %s platform)",1782lib_arch.code, arch_array[running_arch_index].name);1783}1784return NULL;1785}17861787if (lib_arch.endianness != arch_array[running_arch_index].endianness) {1788::snprintf(diag_msg_buf, diag_msg_max_length-1, " (Possible cause: endianness mismatch)");1789return NULL;1790}17911792// ELF file class/capacity : 0 - invalid, 1 - 32bit, 2 - 64bit1793if (lib_arch.elf_class > 2 || lib_arch.elf_class < 1) {1794::snprintf(diag_msg_buf, diag_msg_max_length-1, " (Possible cause: invalid ELF file class)");1795return NULL;1796}17971798if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) {1799::snprintf(diag_msg_buf, diag_msg_max_length-1,1800" (Possible cause: architecture word width mismatch, can't load %d-bit .so on a %d-bit platform)",1801(int) lib_arch.elf_class * 32, arch_array[running_arch_index].elf_class * 32);1802return NULL;1803}18041805return NULL;1806}18071808void * os::Linux::dlopen_helper(const char *filename, char *ebuf,1809int ebuflen) {1810void * result = ::dlopen(filename, RTLD_LAZY);1811if (result == NULL) {1812const char* error_report = ::dlerror();1813if (error_report == NULL) {1814error_report = "dlerror returned no error description";1815}1816if (ebuf != NULL && ebuflen > 0) {1817::strncpy(ebuf, error_report, ebuflen-1);1818ebuf[ebuflen-1]='\0';1819}1820Events::log_dll_message(NULL, "Loading shared library %s failed, %s", filename, error_report);1821log_info(os)("shared library load of %s failed, %s", filename, error_report);1822} else {1823Events::log_dll_message(NULL, "Loaded shared library %s", filename);1824log_info(os)("shared library load of %s was successful", filename);1825}1826return result;1827}18281829void * os::Linux::dll_load_in_vmthread(const char *filename, char *ebuf,1830int ebuflen) {1831void * result = NULL;1832if (LoadExecStackDllInVMThread) {1833result = dlopen_helper(filename, ebuf, ebuflen);1834}18351836// Since 7019808, libjvm.so is linked with -noexecstack. If the VM loads a1837// library that requires an executable stack, or which does not have this1838// stack attribute set, dlopen changes the stack attribute to executable. The1839// read protection of the guard pages gets lost.1840//1841// Need to check _stack_is_executable again as multiple VM_LinuxDllLoad1842// may have been queued at the same time.18431844if (!_stack_is_executable) {1845for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) {1846StackOverflow* overflow_state = jt->stack_overflow_state();1847if (!overflow_state->stack_guard_zone_unused() && // Stack not yet fully initialized1848overflow_state->stack_guards_enabled()) { // No pending stack overflow exceptions1849if (!os::guard_memory((char *)jt->stack_end(), StackOverflow::stack_guard_zone_size())) {1850warning("Attempt to reguard stack yellow zone failed.");1851}1852}1853}1854}18551856return result;1857}18581859const char* os::Linux::dll_path(void* lib) {1860struct link_map *lmap;1861const char* l_path = NULL;1862assert(lib != NULL, "dll_path parameter must not be NULL");18631864int res_dli = ::dlinfo(lib, RTLD_DI_LINKMAP, &lmap);1865if (res_dli == 0) {1866l_path = lmap->l_name;1867}1868return l_path;1869}18701871static bool _print_ascii_file(const char* filename, outputStream* st, const char* hdr = NULL) {1872int fd = ::open(filename, O_RDONLY);1873if (fd == -1) {1874return false;1875}18761877if (hdr != NULL) {1878st->print_cr("%s", hdr);1879}18801881char buf[33];1882int bytes;1883buf[32] = '\0';1884while ((bytes = ::read(fd, buf, sizeof(buf)-1)) > 0) {1885st->print_raw(buf, bytes);1886}18871888::close(fd);18891890return true;1891}18921893static void _print_ascii_file_h(const char* header, const char* filename, outputStream* st, bool same_line = true) {1894st->print("%s:%c", header, same_line ? ' ' : '\n');1895if (!_print_ascii_file(filename, st)) {1896st->print_cr("<Not Available>");1897}1898}18991900void os::print_dll_info(outputStream *st) {1901st->print_cr("Dynamic libraries:");19021903char fname[32];1904pid_t pid = os::Linux::gettid();19051906jio_snprintf(fname, sizeof(fname), "/proc/%d/maps", pid);19071908if (!_print_ascii_file(fname, st)) {1909st->print_cr("Can not get library information for pid = %d", pid);1910}1911}19121913struct loaded_modules_info_param {1914os::LoadedModulesCallbackFunc callback;1915void *param;1916};19171918static int dl_iterate_callback(struct dl_phdr_info *info, size_t size, void *data) {1919if ((info->dlpi_name == NULL) || (*info->dlpi_name == '\0')) {1920return 0;1921}19221923struct loaded_modules_info_param *callback_param = reinterpret_cast<struct loaded_modules_info_param *>(data);1924address base = NULL;1925address top = NULL;1926for (int idx = 0; idx < info->dlpi_phnum; idx++) {1927const ElfW(Phdr) *phdr = info->dlpi_phdr + idx;1928if (phdr->p_type == PT_LOAD) {1929address raw_phdr_base = reinterpret_cast<address>(info->dlpi_addr + phdr->p_vaddr);19301931address phdr_base = align_down(raw_phdr_base, phdr->p_align);1932if ((base == NULL) || (base > phdr_base)) {1933base = phdr_base;1934}19351936address phdr_top = align_up(raw_phdr_base + phdr->p_memsz, phdr->p_align);1937if ((top == NULL) || (top < phdr_top)) {1938top = phdr_top;1939}1940}1941}19421943return callback_param->callback(info->dlpi_name, base, top, callback_param->param);1944}19451946int os::get_loaded_modules_info(os::LoadedModulesCallbackFunc callback, void *param) {1947struct loaded_modules_info_param callback_param = {callback, param};1948return dl_iterate_phdr(&dl_iterate_callback, &callback_param);1949}19501951void os::print_os_info_brief(outputStream* st) {1952os::Linux::print_distro_info(st);19531954os::Posix::print_uname_info(st);19551956os::Linux::print_libversion_info(st);19571958}19591960void os::print_os_info(outputStream* st) {1961st->print_cr("OS:");19621963os::Linux::print_distro_info(st);19641965os::Posix::print_uname_info(st);19661967os::Linux::print_uptime_info(st);19681969// Print warning if unsafe chroot environment detected1970if (unsafe_chroot_detected) {1971st->print_cr("WARNING!! %s", unstable_chroot_error);1972}19731974os::Linux::print_libversion_info(st);19751976os::Posix::print_rlimit_info(st);19771978os::Posix::print_load_average(st);1979st->cr();19801981os::Linux::print_system_memory_info(st);1982st->cr();19831984os::Linux::print_process_memory_info(st);1985st->cr();19861987os::Linux::print_proc_sys_info(st);1988st->cr();19891990if (os::Linux::print_ld_preload_file(st)) {1991st->cr();1992}19931994if (os::Linux::print_container_info(st)) {1995st->cr();1996}19971998VM_Version::print_platform_virtualization_info(st);19992000os::Linux::print_steal_info(st);2001}20022003// Try to identify popular distros.2004// Most Linux distributions have a /etc/XXX-release file, which contains2005// the OS version string. Newer Linux distributions have a /etc/lsb-release2006// file that also contains the OS version string. Some have more than one2007// /etc/XXX-release file (e.g. Mandrake has both /etc/mandrake-release and2008// /etc/redhat-release.), so the order is important.2009// Any Linux that is based on Redhat (i.e. Oracle, Mandrake, Sun JDS...) have2010// their own specific XXX-release file as well as a redhat-release file.2011// Because of this the XXX-release file needs to be searched for before the2012// redhat-release file.2013// Since Red Hat and SuSE have an lsb-release file that is not very descriptive the2014// search for redhat-release / SuSE-release needs to be before lsb-release.2015// Since the lsb-release file is the new standard it needs to be searched2016// before the older style release files.2017// Searching system-release (Red Hat) and os-release (other Linuxes) are a2018// next to last resort. The os-release file is a new standard that contains2019// distribution information and the system-release file seems to be an old2020// standard that has been replaced by the lsb-release and os-release files.2021// Searching for the debian_version file is the last resort. It contains2022// an informative string like "6.0.6" or "wheezy/sid". Because of this2023// "Debian " is printed before the contents of the debian_version file.20242025const char* distro_files[] = {2026"/etc/oracle-release",2027"/etc/mandriva-release",2028"/etc/mandrake-release",2029"/etc/sun-release",2030"/etc/redhat-release",2031"/etc/SuSE-release",2032"/etc/lsb-release",2033"/etc/turbolinux-release",2034"/etc/gentoo-release",2035"/etc/ltib-release",2036"/etc/angstrom-version",2037"/etc/system-release",2038"/etc/os-release",2039NULL };20402041void os::Linux::print_distro_info(outputStream* st) {2042for (int i = 0;; i++) {2043const char* file = distro_files[i];2044if (file == NULL) {2045break; // done2046}2047// If file prints, we found it.2048if (_print_ascii_file(file, st)) {2049return;2050}2051}20522053if (file_exists("/etc/debian_version")) {2054st->print("Debian ");2055_print_ascii_file("/etc/debian_version", st);2056} else {2057st->print_cr("Linux");2058}2059}20602061static void parse_os_info_helper(FILE* fp, char* distro, size_t length, bool get_first_line) {2062char buf[256];2063while (fgets(buf, sizeof(buf), fp)) {2064// Edit out extra stuff in expected format2065if (strstr(buf, "DISTRIB_DESCRIPTION=") != NULL || strstr(buf, "PRETTY_NAME=") != NULL) {2066char* ptr = strstr(buf, "\""); // the name is in quotes2067if (ptr != NULL) {2068ptr++; // go beyond first quote2069char* nl = strchr(ptr, '\"');2070if (nl != NULL) *nl = '\0';2071strncpy(distro, ptr, length);2072} else {2073ptr = strstr(buf, "=");2074ptr++; // go beyond equals then2075char* nl = strchr(ptr, '\n');2076if (nl != NULL) *nl = '\0';2077strncpy(distro, ptr, length);2078}2079return;2080} else if (get_first_line) {2081char* nl = strchr(buf, '\n');2082if (nl != NULL) *nl = '\0';2083strncpy(distro, buf, length);2084return;2085}2086}2087// print last line and close2088char* nl = strchr(buf, '\n');2089if (nl != NULL) *nl = '\0';2090strncpy(distro, buf, length);2091}20922093static void parse_os_info(char* distro, size_t length, const char* file) {2094FILE* fp = fopen(file, "r");2095if (fp != NULL) {2096// if suse format, print out first line2097bool get_first_line = (strcmp(file, "/etc/SuSE-release") == 0);2098parse_os_info_helper(fp, distro, length, get_first_line);2099fclose(fp);2100}2101}21022103void os::get_summary_os_info(char* buf, size_t buflen) {2104for (int i = 0;; i++) {2105const char* file = distro_files[i];2106if (file == NULL) {2107break; // ran out of distro_files2108}2109if (file_exists(file)) {2110parse_os_info(buf, buflen, file);2111return;2112}2113}2114// special case for debian2115if (file_exists("/etc/debian_version")) {2116strncpy(buf, "Debian ", buflen);2117if (buflen > 7) {2118parse_os_info(&buf[7], buflen-7, "/etc/debian_version");2119}2120} else {2121strncpy(buf, "Linux", buflen);2122}2123}21242125void os::Linux::print_libversion_info(outputStream* st) {2126// libc, pthread2127st->print("libc: ");2128st->print("%s ", os::Linux::libc_version());2129st->print("%s ", os::Linux::libpthread_version());2130st->cr();2131}21322133void os::Linux::print_proc_sys_info(outputStream* st) {2134_print_ascii_file_h("/proc/sys/kernel/threads-max (system-wide limit on the number of threads)",2135"/proc/sys/kernel/threads-max", st);2136_print_ascii_file_h("/proc/sys/vm/max_map_count (maximum number of memory map areas a process may have)",2137"/proc/sys/vm/max_map_count", st);2138_print_ascii_file_h("/proc/sys/kernel/pid_max (system-wide limit on number of process identifiers)",2139"/proc/sys/kernel/pid_max", st);2140}21412142void os::Linux::print_system_memory_info(outputStream* st) {2143_print_ascii_file_h("/proc/meminfo", "/proc/meminfo", st, false);2144st->cr();21452146// some information regarding THPs; for details see2147// https://www.kernel.org/doc/Documentation/vm/transhuge.txt2148_print_ascii_file_h("/sys/kernel/mm/transparent_hugepage/enabled",2149"/sys/kernel/mm/transparent_hugepage/enabled", st);2150_print_ascii_file_h("/sys/kernel/mm/transparent_hugepage/defrag (defrag/compaction efforts parameter)",2151"/sys/kernel/mm/transparent_hugepage/defrag", st);2152}21532154bool os::Linux::query_process_memory_info(os::Linux::meminfo_t* info) {2155FILE* f = ::fopen("/proc/self/status", "r");2156const int num_values = sizeof(os::Linux::meminfo_t) / sizeof(size_t);2157int num_found = 0;2158char buf[256];2159info->vmsize = info->vmpeak = info->vmrss = info->vmhwm = info->vmswap =2160info->rssanon = info->rssfile = info->rssshmem = -1;2161if (f != NULL) {2162while (::fgets(buf, sizeof(buf), f) != NULL && num_found < num_values) {2163if ( (info->vmsize == -1 && sscanf(buf, "VmSize: " SSIZE_FORMAT " kB", &info->vmsize) == 1) ||2164(info->vmpeak == -1 && sscanf(buf, "VmPeak: " SSIZE_FORMAT " kB", &info->vmpeak) == 1) ||2165(info->vmswap == -1 && sscanf(buf, "VmSwap: " SSIZE_FORMAT " kB", &info->vmswap) == 1) ||2166(info->vmhwm == -1 && sscanf(buf, "VmHWM: " SSIZE_FORMAT " kB", &info->vmhwm) == 1) ||2167(info->vmrss == -1 && sscanf(buf, "VmRSS: " SSIZE_FORMAT " kB", &info->vmrss) == 1) ||2168(info->rssanon == -1 && sscanf(buf, "RssAnon: " SSIZE_FORMAT " kB", &info->rssanon) == 1) || // Needs Linux 4.52169(info->rssfile == -1 && sscanf(buf, "RssFile: " SSIZE_FORMAT " kB", &info->rssfile) == 1) || // Needs Linux 4.52170(info->rssshmem == -1 && sscanf(buf, "RssShmem: " SSIZE_FORMAT " kB", &info->rssshmem) == 1) // Needs Linux 4.52171)2172{2173num_found ++;2174}2175}2176fclose(f);2177return true;2178}2179return false;2180}21812182#ifdef __GLIBC__2183// For Glibc, print a one-liner with the malloc tunables.2184// Most important and popular is MALLOC_ARENA_MAX, but we are2185// thorough and print them all.2186static void print_glibc_malloc_tunables(outputStream* st) {2187static const char* var[] = {2188// the new variant2189"GLIBC_TUNABLES",2190// legacy variants2191"MALLOC_CHECK_", "MALLOC_TOP_PAD_", "MALLOC_PERTURB_",2192"MALLOC_MMAP_THRESHOLD_", "MALLOC_TRIM_THRESHOLD_",2193"MALLOC_MMAP_MAX_", "MALLOC_ARENA_TEST", "MALLOC_ARENA_MAX",2194NULL};2195st->print("glibc malloc tunables: ");2196bool printed = false;2197for (int i = 0; var[i] != NULL; i ++) {2198const char* const val = ::getenv(var[i]);2199if (val != NULL) {2200st->print("%s%s=%s", (printed ? ", " : ""), var[i], val);2201printed = true;2202}2203}2204if (!printed) {2205st->print("(default)");2206}2207}2208#endif // __GLIBC__22092210void os::Linux::print_process_memory_info(outputStream* st) {22112212st->print_cr("Process Memory:");22132214// Print virtual and resident set size; peak values; swap; and for2215// rss its components if the kernel is recent enough.2216meminfo_t info;2217if (query_process_memory_info(&info)) {2218st->print_cr("Virtual Size: " SSIZE_FORMAT "K (peak: " SSIZE_FORMAT "K)", info.vmsize, info.vmpeak);2219st->print("Resident Set Size: " SSIZE_FORMAT "K (peak: " SSIZE_FORMAT "K)", info.vmrss, info.vmhwm);2220if (info.rssanon != -1) { // requires kernel >= 4.52221st->print(" (anon: " SSIZE_FORMAT "K, file: " SSIZE_FORMAT "K, shmem: " SSIZE_FORMAT "K)",2222info.rssanon, info.rssfile, info.rssshmem);2223}2224st->cr();2225if (info.vmswap != -1) { // requires kernel >= 2.6.342226st->print_cr("Swapped out: " SSIZE_FORMAT "K", info.vmswap);2227}2228} else {2229st->print_cr("Could not open /proc/self/status to get process memory related information");2230}22312232// glibc only:2233// - Print outstanding allocations using mallinfo2234// - Print glibc tunables2235#ifdef __GLIBC__2236size_t total_allocated = 0;2237size_t free_retained = 0;2238bool might_have_wrapped = false;2239if (_mallinfo2 != NULL) {2240struct glibc_mallinfo2 mi = _mallinfo2();2241total_allocated = mi.uordblks + mi.hblkhd;2242free_retained = mi.fordblks;2243} else if (_mallinfo != NULL) {2244// mallinfo is an old API. Member names mean next to nothing and, beyond that, are 32-bit signed.2245// So for larger footprints the values may have wrapped around. We try to detect this here: if the2246// process whole resident set size is smaller than 4G, malloc footprint has to be less than that2247// and the numbers are reliable.2248struct glibc_mallinfo mi = _mallinfo();2249total_allocated = (size_t)(unsigned)mi.uordblks + (size_t)(unsigned)mi.hblkhd;2250free_retained = (size_t)(unsigned)mi.fordblks;2251// Since mallinfo members are int, glibc values may have wrapped. Warn about this.2252might_have_wrapped = (info.vmrss * K) > UINT_MAX && (info.vmrss * K) > (total_allocated + UINT_MAX);2253}2254if (_mallinfo2 != NULL || _mallinfo != NULL) {2255st->print_cr("C-Heap outstanding allocations: " SIZE_FORMAT "K, retained: " SIZE_FORMAT "K%s",2256total_allocated / K, free_retained / K,2257might_have_wrapped ? " (may have wrapped)" : "");2258}2259// Tunables2260print_glibc_malloc_tunables(st);2261st->cr();2262#endif2263}22642265bool os::Linux::print_ld_preload_file(outputStream* st) {2266return _print_ascii_file("/etc/ld.so.preload", st, "/etc/ld.so.preload:");2267}22682269void os::Linux::print_uptime_info(outputStream* st) {2270struct sysinfo sinfo;2271int ret = sysinfo(&sinfo);2272if (ret == 0) {2273os::print_dhm(st, "OS uptime:", (long) sinfo.uptime);2274}2275}22762277static void print_container_helper(outputStream* st, jlong j, const char* metrics) {2278st->print("%s: ", metrics);2279if (j > 0) {2280if (j >= 1024) {2281st->print_cr(UINT64_FORMAT " k", uint64_t(j) / 1024);2282} else {2283st->print_cr(UINT64_FORMAT, uint64_t(j));2284}2285} else {2286st->print_cr("%s", j == OSCONTAINER_ERROR ? "not supported" : "unlimited");2287}2288}22892290bool os::Linux::print_container_info(outputStream* st) {2291if (!OSContainer::is_containerized()) {2292st->print_cr("container information not found.");2293return false;2294}22952296st->print_cr("container (cgroup) information:");22972298const char *p_ct = OSContainer::container_type();2299st->print_cr("container_type: %s", p_ct != NULL ? p_ct : "not supported");23002301char *p = OSContainer::cpu_cpuset_cpus();2302st->print_cr("cpu_cpuset_cpus: %s", p != NULL ? p : "not supported");2303free(p);23042305p = OSContainer::cpu_cpuset_memory_nodes();2306st->print_cr("cpu_memory_nodes: %s", p != NULL ? p : "not supported");2307free(p);23082309int i = OSContainer::active_processor_count();2310st->print("active_processor_count: ");2311if (i > 0) {2312if (ActiveProcessorCount > 0) {2313st->print_cr("%d, but overridden by -XX:ActiveProcessorCount %d", i, ActiveProcessorCount);2314} else {2315st->print_cr("%d", i);2316}2317} else {2318st->print_cr("not supported");2319}23202321i = OSContainer::cpu_quota();2322st->print("cpu_quota: ");2323if (i > 0) {2324st->print_cr("%d", i);2325} else {2326st->print_cr("%s", i == OSCONTAINER_ERROR ? "not supported" : "no quota");2327}23282329i = OSContainer::cpu_period();2330st->print("cpu_period: ");2331if (i > 0) {2332st->print_cr("%d", i);2333} else {2334st->print_cr("%s", i == OSCONTAINER_ERROR ? "not supported" : "no period");2335}23362337i = OSContainer::cpu_shares();2338st->print("cpu_shares: ");2339if (i > 0) {2340st->print_cr("%d", i);2341} else {2342st->print_cr("%s", i == OSCONTAINER_ERROR ? "not supported" : "no shares");2343}23442345print_container_helper(st, OSContainer::memory_limit_in_bytes(), "memory_limit_in_bytes");2346print_container_helper(st, OSContainer::memory_and_swap_limit_in_bytes(), "memory_and_swap_limit_in_bytes");2347print_container_helper(st, OSContainer::memory_soft_limit_in_bytes(), "memory_soft_limit_in_bytes");2348print_container_helper(st, OSContainer::memory_usage_in_bytes(), "memory_usage_in_bytes");2349print_container_helper(st, OSContainer::memory_max_usage_in_bytes(), "memory_max_usage_in_bytes");23502351jlong j = OSContainer::pids_max();2352st->print("maximum number of tasks: ");2353if (j > 0) {2354st->print_cr(JLONG_FORMAT, j);2355} else {2356st->print_cr("%s", j == OSCONTAINER_ERROR ? "not supported" : "unlimited");2357}23582359j = OSContainer::pids_current();2360st->print("current number of tasks: ");2361if (j > 0) {2362st->print_cr(JLONG_FORMAT, j);2363} else {2364if (j == OSCONTAINER_ERROR) {2365st->print_cr("not supported");2366}2367}23682369return true;2370}23712372void os::Linux::print_steal_info(outputStream* st) {2373if (has_initial_tick_info) {2374CPUPerfTicks pticks;2375bool res = os::Linux::get_tick_information(&pticks, -1);23762377if (res && pticks.has_steal_ticks) {2378uint64_t steal_ticks_difference = pticks.steal - initial_steal_ticks;2379uint64_t total_ticks_difference = pticks.total - initial_total_ticks;2380double steal_ticks_perc = 0.0;2381if (total_ticks_difference != 0) {2382steal_ticks_perc = (double) steal_ticks_difference / total_ticks_difference;2383}2384st->print_cr("Steal ticks since vm start: " UINT64_FORMAT, steal_ticks_difference);2385st->print_cr("Steal ticks percentage since vm start:%7.3f", steal_ticks_perc);2386}2387}2388}23892390void os::print_memory_info(outputStream* st) {23912392st->print("Memory:");2393st->print(" %dk page", os::vm_page_size()>>10);23942395// values in struct sysinfo are "unsigned long"2396struct sysinfo si;2397sysinfo(&si);23982399st->print(", physical " UINT64_FORMAT "k",2400os::physical_memory() >> 10);2401st->print("(" UINT64_FORMAT "k free)",2402os::available_memory() >> 10);2403st->print(", swap " UINT64_FORMAT "k",2404((jlong)si.totalswap * si.mem_unit) >> 10);2405st->print("(" UINT64_FORMAT "k free)",2406((jlong)si.freeswap * si.mem_unit) >> 10);2407st->cr();2408st->print("Page Sizes: ");2409_page_sizes.print_on(st);2410st->cr();2411}24122413// Print the first "model name" line and the first "flags" line2414// that we find and nothing more. We assume "model name" comes2415// before "flags" so if we find a second "model name", then the2416// "flags" field is considered missing.2417static bool print_model_name_and_flags(outputStream* st, char* buf, size_t buflen) {2418#if defined(IA32) || defined(AMD64)2419// Other platforms have less repetitive cpuinfo files2420FILE *fp = fopen("/proc/cpuinfo", "r");2421if (fp) {2422bool model_name_printed = false;2423while (!feof(fp)) {2424if (fgets(buf, buflen, fp)) {2425// Assume model name comes before flags2426if (strstr(buf, "model name") != NULL) {2427if (!model_name_printed) {2428st->print_raw("CPU Model and flags from /proc/cpuinfo:\n");2429st->print_raw(buf);2430model_name_printed = true;2431} else {2432// model name printed but not flags? Odd, just return2433fclose(fp);2434return true;2435}2436}2437// print the flags line too2438if (strstr(buf, "flags") != NULL) {2439st->print_raw(buf);2440fclose(fp);2441return true;2442}2443}2444}2445fclose(fp);2446}2447#endif // x86 platforms2448return false;2449}24502451// additional information about CPU e.g. available frequency ranges2452static void print_sys_devices_cpu_info(outputStream* st, char* buf, size_t buflen) {2453_print_ascii_file_h("Online cpus", "/sys/devices/system/cpu/online", st);2454_print_ascii_file_h("Offline cpus", "/sys/devices/system/cpu/offline", st);24552456if (ExtensiveErrorReports) {2457// cache related info (cpu 0, should be similar for other CPUs)2458for (unsigned int i=0; i < 10; i++) { // handle max. 10 cache entries2459char hbuf_level[60];2460char hbuf_type[60];2461char hbuf_size[60];2462char hbuf_coherency_line_size[80];2463snprintf(hbuf_level, 60, "/sys/devices/system/cpu/cpu0/cache/index%u/level", i);2464snprintf(hbuf_type, 60, "/sys/devices/system/cpu/cpu0/cache/index%u/type", i);2465snprintf(hbuf_size, 60, "/sys/devices/system/cpu/cpu0/cache/index%u/size", i);2466snprintf(hbuf_coherency_line_size, 80, "/sys/devices/system/cpu/cpu0/cache/index%u/coherency_line_size", i);2467if (file_exists(hbuf_level)) {2468_print_ascii_file_h("cache level", hbuf_level, st);2469_print_ascii_file_h("cache type", hbuf_type, st);2470_print_ascii_file_h("cache size", hbuf_size, st);2471_print_ascii_file_h("cache coherency line size", hbuf_coherency_line_size, st);2472}2473}2474}24752476// we miss the cpufreq entries on Power and s390x2477#if defined(IA32) || defined(AMD64)2478_print_ascii_file_h("BIOS frequency limitation", "/sys/devices/system/cpu/cpu0/cpufreq/bios_limit", st);2479_print_ascii_file_h("Frequency switch latency (ns)", "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_transition_latency", st);2480_print_ascii_file_h("Available cpu frequencies", "/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies", st);2481// min and max should be in the Available range but still print them (not all info might be available for all kernels)2482if (ExtensiveErrorReports) {2483_print_ascii_file_h("Maximum cpu frequency", "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq", st);2484_print_ascii_file_h("Minimum cpu frequency", "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq", st);2485_print_ascii_file_h("Current cpu frequency", "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq", st);2486}2487// governors are power schemes, see https://wiki.archlinux.org/index.php/CPU_frequency_scaling2488if (ExtensiveErrorReports) {2489_print_ascii_file_h("Available governors", "/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors", st);2490}2491_print_ascii_file_h("Current governor", "/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor", st);2492// Core performance boost, see https://www.kernel.org/doc/Documentation/cpu-freq/boost.txt2493// Raise operating frequency of some cores in a multi-core package if certain conditions apply, e.g.2494// whole chip is not fully utilized2495_print_ascii_file_h("Core performance/turbo boost", "/sys/devices/system/cpu/cpufreq/boost", st);2496#endif2497}24982499void os::pd_print_cpu_info(outputStream* st, char* buf, size_t buflen) {2500// Only print the model name if the platform provides this as a summary2501if (!print_model_name_and_flags(st, buf, buflen)) {2502_print_ascii_file_h("/proc/cpuinfo", "/proc/cpuinfo", st, false);2503}2504st->cr();2505print_sys_devices_cpu_info(st, buf, buflen);2506}25072508#if defined(AMD64) || defined(IA32) || defined(X32)2509const char* search_string = "model name";2510#elif defined(M68K)2511const char* search_string = "CPU";2512#elif defined(PPC64)2513const char* search_string = "cpu";2514#elif defined(S390)2515const char* search_string = "machine =";2516#elif defined(SPARC)2517const char* search_string = "cpu";2518#else2519const char* search_string = "Processor";2520#endif25212522// Parses the cpuinfo file for string representing the model name.2523void os::get_summary_cpu_info(char* cpuinfo, size_t length) {2524FILE* fp = fopen("/proc/cpuinfo", "r");2525if (fp != NULL) {2526while (!feof(fp)) {2527char buf[256];2528if (fgets(buf, sizeof(buf), fp)) {2529char* start = strstr(buf, search_string);2530if (start != NULL) {2531char *ptr = start + strlen(search_string);2532char *end = buf + strlen(buf);2533while (ptr != end) {2534// skip whitespace and colon for the rest of the name.2535if (*ptr != ' ' && *ptr != '\t' && *ptr != ':') {2536break;2537}2538ptr++;2539}2540if (ptr != end) {2541// reasonable string, get rid of newline and keep the rest2542char* nl = strchr(buf, '\n');2543if (nl != NULL) *nl = '\0';2544strncpy(cpuinfo, ptr, length);2545fclose(fp);2546return;2547}2548}2549}2550}2551fclose(fp);2552}2553// cpuinfo not found or parsing failed, just print generic string. The entire2554// /proc/cpuinfo file will be printed later in the file (or enough of it for x86)2555#if defined(AARCH64)2556strncpy(cpuinfo, "AArch64", length);2557#elif defined(AMD64)2558strncpy(cpuinfo, "x86_64", length);2559#elif defined(ARM) // Order wrt. AARCH64 is relevant!2560strncpy(cpuinfo, "ARM", length);2561#elif defined(IA32)2562strncpy(cpuinfo, "x86_32", length);2563#elif defined(IA64)2564strncpy(cpuinfo, "IA64", length);2565#elif defined(PPC)2566strncpy(cpuinfo, "PPC64", length);2567#elif defined(S390)2568strncpy(cpuinfo, "S390", length);2569#elif defined(SPARC)2570strncpy(cpuinfo, "sparcv9", length);2571#elif defined(ZERO_LIBARCH)2572strncpy(cpuinfo, ZERO_LIBARCH, length);2573#else2574strncpy(cpuinfo, "unknown", length);2575#endif2576}25772578static char saved_jvm_path[MAXPATHLEN] = {0};25792580// Find the full path to the current module, libjvm.so2581void os::jvm_path(char *buf, jint buflen) {2582// Error checking.2583if (buflen < MAXPATHLEN) {2584assert(false, "must use a large-enough buffer");2585buf[0] = '\0';2586return;2587}2588// Lazy resolve the path to current module.2589if (saved_jvm_path[0] != 0) {2590strcpy(buf, saved_jvm_path);2591return;2592}25932594char dli_fname[MAXPATHLEN];2595dli_fname[0] = '\0';2596bool ret = dll_address_to_library_name(2597CAST_FROM_FN_PTR(address, os::jvm_path),2598dli_fname, sizeof(dli_fname), NULL);2599assert(ret, "cannot locate libjvm");2600char *rp = NULL;2601if (ret && dli_fname[0] != '\0') {2602rp = os::Posix::realpath(dli_fname, buf, buflen);2603}2604if (rp == NULL) {2605return;2606}26072608if (Arguments::sun_java_launcher_is_altjvm()) {2609// Support for the java launcher's '-XXaltjvm=<path>' option. Typical2610// value for buf is "<JAVA_HOME>/jre/lib/<vmtype>/libjvm.so".2611// If "/jre/lib/" appears at the right place in the string, then2612// assume we are installed in a JDK and we're done. Otherwise, check2613// for a JAVA_HOME environment variable and fix up the path so it2614// looks like libjvm.so is installed there (append a fake suffix2615// hotspot/libjvm.so).2616const char *p = buf + strlen(buf) - 1;2617for (int count = 0; p > buf && count < 5; ++count) {2618for (--p; p > buf && *p != '/'; --p)2619/* empty */ ;2620}26212622if (strncmp(p, "/jre/lib/", 9) != 0) {2623// Look for JAVA_HOME in the environment.2624char* java_home_var = ::getenv("JAVA_HOME");2625if (java_home_var != NULL && java_home_var[0] != 0) {2626char* jrelib_p;2627int len;26282629// Check the current module name "libjvm.so".2630p = strrchr(buf, '/');2631if (p == NULL) {2632return;2633}2634assert(strstr(p, "/libjvm") == p, "invalid library name");26352636rp = os::Posix::realpath(java_home_var, buf, buflen);2637if (rp == NULL) {2638return;2639}26402641// determine if this is a legacy image or modules image2642// modules image doesn't have "jre" subdirectory2643len = strlen(buf);2644assert(len < buflen, "Ran out of buffer room");2645jrelib_p = buf + len;2646snprintf(jrelib_p, buflen-len, "/jre/lib");2647if (0 != access(buf, F_OK)) {2648snprintf(jrelib_p, buflen-len, "/lib");2649}26502651if (0 == access(buf, F_OK)) {2652// Use current module name "libjvm.so"2653len = strlen(buf);2654snprintf(buf + len, buflen-len, "/hotspot/libjvm.so");2655} else {2656// Go back to path of .so2657rp = os::Posix::realpath(dli_fname, buf, buflen);2658if (rp == NULL) {2659return;2660}2661}2662}2663}2664}26652666strncpy(saved_jvm_path, buf, MAXPATHLEN);2667saved_jvm_path[MAXPATHLEN - 1] = '\0';2668}26692670void os::print_jni_name_prefix_on(outputStream* st, int args_size) {2671// no prefix required, not even "_"2672}26732674void os::print_jni_name_suffix_on(outputStream* st, int args_size) {2675// no suffix required2676}26772678////////////////////////////////////////////////////////////////////////////////2679// Virtual Memory26802681int os::vm_page_size() {2682// Seems redundant as all get out2683assert(os::Linux::page_size() != -1, "must call os::init");2684return os::Linux::page_size();2685}26862687// Solaris allocates memory by pages.2688int os::vm_allocation_granularity() {2689assert(os::Linux::page_size() != -1, "must call os::init");2690return os::Linux::page_size();2691}26922693// Rationale behind this function:2694// current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable2695// mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get2696// samples for JITted code. Here we create private executable mapping over the code cache2697// and then we can use standard (well, almost, as mapping can change) way to provide2698// info for the reporting script by storing timestamp and location of symbol2699void linux_wrap_code(char* base, size_t size) {2700static volatile jint cnt = 0;27012702if (!UseOprofile) {2703return;2704}27052706char buf[PATH_MAX+1];2707int num = Atomic::add(&cnt, 1);27082709snprintf(buf, sizeof(buf), "%s/hs-vm-%d-%d",2710os::get_temp_directory(), os::current_process_id(), num);2711unlink(buf);27122713int fd = ::open(buf, O_CREAT | O_RDWR, S_IRWXU);27142715if (fd != -1) {2716off_t rv = ::lseek(fd, size-2, SEEK_SET);2717if (rv != (off_t)-1) {2718if (::write(fd, "", 1) == 1) {2719mmap(base, size,2720PROT_READ|PROT_WRITE|PROT_EXEC,2721MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0);2722}2723}2724::close(fd);2725unlink(buf);2726}2727}27282729static bool recoverable_mmap_error(int err) {2730// See if the error is one we can let the caller handle. This2731// list of errno values comes from JBS-6843484. I can't find a2732// Linux man page that documents this specific set of errno2733// values so while this list currently matches Solaris, it may2734// change as we gain experience with this failure mode.2735switch (err) {2736case EBADF:2737case EINVAL:2738case ENOTSUP:2739// let the caller deal with these errors2740return true;27412742default:2743// Any remaining errors on this OS can cause our reserved mapping2744// to be lost. That can cause confusion where different data2745// structures think they have the same memory mapped. The worst2746// scenario is if both the VM and a library think they have the2747// same memory mapped.2748return false;2749}2750}27512752static void warn_fail_commit_memory(char* addr, size_t size, bool exec,2753int err) {2754warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT2755", %d) failed; error='%s' (errno=%d)", p2i(addr), size, exec,2756os::strerror(err), err);2757}27582759static void warn_fail_commit_memory(char* addr, size_t size,2760size_t alignment_hint, bool exec,2761int err) {2762warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT2763", " SIZE_FORMAT ", %d) failed; error='%s' (errno=%d)", p2i(addr), size,2764alignment_hint, exec, os::strerror(err), err);2765}27662767// NOTE: Linux kernel does not really reserve the pages for us.2768// All it does is to check if there are enough free pages2769// left at the time of mmap(). This could be a potential2770// problem.2771int os::Linux::commit_memory_impl(char* addr, size_t size, bool exec) {2772int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;2773uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,2774MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);2775if (res != (uintptr_t) MAP_FAILED) {2776if (UseNUMAInterleaving) {2777numa_make_global(addr, size);2778}2779return 0;2780}27812782int err = errno; // save errno from mmap() call above27832784if (!recoverable_mmap_error(err)) {2785warn_fail_commit_memory(addr, size, exec, err);2786vm_exit_out_of_memory(size, OOM_MMAP_ERROR, "committing reserved memory.");2787}27882789return err;2790}27912792bool os::pd_commit_memory(char* addr, size_t size, bool exec) {2793return os::Linux::commit_memory_impl(addr, size, exec) == 0;2794}27952796void os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec,2797const char* mesg) {2798assert(mesg != NULL, "mesg must be specified");2799int err = os::Linux::commit_memory_impl(addr, size, exec);2800if (err != 0) {2801// the caller wants all commit errors to exit with the specified mesg:2802warn_fail_commit_memory(addr, size, exec, err);2803vm_exit_out_of_memory(size, OOM_MMAP_ERROR, "%s", mesg);2804}2805}28062807// Define MAP_HUGETLB here so we can build HotSpot on old systems.2808#ifndef MAP_HUGETLB2809#define MAP_HUGETLB 0x400002810#endif28112812// If mmap flags are set with MAP_HUGETLB and the system supports multiple2813// huge page sizes, flag bits [26:31] can be used to encode the log2 of the2814// desired huge page size. Otherwise, the system's default huge page size will be used.2815// See mmap(2) man page for more info (since Linux 3.8).2816// https://lwn.net/Articles/533499/2817#ifndef MAP_HUGE_SHIFT2818#define MAP_HUGE_SHIFT 262819#endif28202821// Define MADV_HUGEPAGE here so we can build HotSpot on old systems.2822#ifndef MADV_HUGEPAGE2823#define MADV_HUGEPAGE 142824#endif28252826int os::Linux::commit_memory_impl(char* addr, size_t size,2827size_t alignment_hint, bool exec) {2828int err = os::Linux::commit_memory_impl(addr, size, exec);2829if (err == 0) {2830realign_memory(addr, size, alignment_hint);2831}2832return err;2833}28342835bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,2836bool exec) {2837return os::Linux::commit_memory_impl(addr, size, alignment_hint, exec) == 0;2838}28392840void os::pd_commit_memory_or_exit(char* addr, size_t size,2841size_t alignment_hint, bool exec,2842const char* mesg) {2843assert(mesg != NULL, "mesg must be specified");2844int err = os::Linux::commit_memory_impl(addr, size, alignment_hint, exec);2845if (err != 0) {2846// the caller wants all commit errors to exit with the specified mesg:2847warn_fail_commit_memory(addr, size, alignment_hint, exec, err);2848vm_exit_out_of_memory(size, OOM_MMAP_ERROR, "%s", mesg);2849}2850}28512852void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {2853if (UseTransparentHugePages && alignment_hint > (size_t)vm_page_size()) {2854// We don't check the return value: madvise(MADV_HUGEPAGE) may not2855// be supported or the memory may already be backed by huge pages.2856::madvise(addr, bytes, MADV_HUGEPAGE);2857}2858}28592860void os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) {2861// This method works by doing an mmap over an existing mmaping and effectively discarding2862// the existing pages. However it won't work for SHM-based large pages that cannot be2863// uncommitted at all. We don't do anything in this case to avoid creating a segment with2864// small pages on top of the SHM segment. This method always works for small pages, so we2865// allow that in any case.2866if (alignment_hint <= (size_t)os::vm_page_size() || can_commit_large_page_memory()) {2867commit_memory(addr, bytes, alignment_hint, !ExecMem);2868}2869}28702871void os::numa_make_global(char *addr, size_t bytes) {2872Linux::numa_interleave_memory(addr, bytes);2873}28742875// Define for numa_set_bind_policy(int). Setting the argument to 0 will set the2876// bind policy to MPOL_PREFERRED for the current thread.2877#define USE_MPOL_PREFERRED 028782879void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {2880// To make NUMA and large pages more robust when both enabled, we need to ease2881// the requirements on where the memory should be allocated. MPOL_BIND is the2882// default policy and it will force memory to be allocated on the specified2883// node. Changing this to MPOL_PREFERRED will prefer to allocate the memory on2884// the specified node, but will not force it. Using this policy will prevent2885// getting SIGBUS when trying to allocate large pages on NUMA nodes with no2886// free large pages.2887Linux::numa_set_bind_policy(USE_MPOL_PREFERRED);2888Linux::numa_tonode_memory(addr, bytes, lgrp_hint);2889}28902891bool os::numa_topology_changed() { return false; }28922893size_t os::numa_get_groups_num() {2894// Return just the number of nodes in which it's possible to allocate memory2895// (in numa terminology, configured nodes).2896return Linux::numa_num_configured_nodes();2897}28982899int os::numa_get_group_id() {2900int cpu_id = Linux::sched_getcpu();2901if (cpu_id != -1) {2902int lgrp_id = Linux::get_node_by_cpu(cpu_id);2903if (lgrp_id != -1) {2904return lgrp_id;2905}2906}2907return 0;2908}29092910int os::numa_get_group_id_for_address(const void* address) {2911void** pages = const_cast<void**>(&address);2912int id = -1;29132914if (os::Linux::numa_move_pages(0, 1, pages, NULL, &id, 0) == -1) {2915return -1;2916}2917if (id < 0) {2918return -1;2919}2920return id;2921}29222923int os::Linux::get_existing_num_nodes() {2924int node;2925int highest_node_number = Linux::numa_max_node();2926int num_nodes = 0;29272928// Get the total number of nodes in the system including nodes without memory.2929for (node = 0; node <= highest_node_number; node++) {2930if (is_node_in_existing_nodes(node)) {2931num_nodes++;2932}2933}2934return num_nodes;2935}29362937size_t os::numa_get_leaf_groups(int *ids, size_t size) {2938int highest_node_number = Linux::numa_max_node();2939size_t i = 0;29402941// Map all node ids in which it is possible to allocate memory. Also nodes are2942// not always consecutively available, i.e. available from 0 to the highest2943// node number. If the nodes have been bound explicitly using numactl membind,2944// then allocate memory from those nodes only.2945for (int node = 0; node <= highest_node_number; node++) {2946if (Linux::is_node_in_bound_nodes((unsigned int)node)) {2947ids[i++] = node;2948}2949}2950return i;2951}29522953bool os::get_page_info(char *start, page_info* info) {2954return false;2955}29562957char *os::scan_pages(char *start, char* end, page_info* page_expected,2958page_info* page_found) {2959return end;2960}296129622963int os::Linux::sched_getcpu_syscall(void) {2964unsigned int cpu = 0;2965int retval = -1;29662967#if defined(IA32)2968#ifndef SYS_getcpu2969#define SYS_getcpu 3182970#endif2971retval = syscall(SYS_getcpu, &cpu, NULL, NULL);2972#elif defined(AMD64)2973// Unfortunately we have to bring all these macros here from vsyscall.h2974// to be able to compile on old linuxes.2975#define __NR_vgetcpu 22976#define VSYSCALL_START (-10UL << 20)2977#define VSYSCALL_SIZE 10242978#define VSYSCALL_ADDR(vsyscall_nr) (VSYSCALL_START+VSYSCALL_SIZE*(vsyscall_nr))2979typedef long (*vgetcpu_t)(unsigned int *cpu, unsigned int *node, unsigned long *tcache);2980vgetcpu_t vgetcpu = (vgetcpu_t)VSYSCALL_ADDR(__NR_vgetcpu);2981retval = vgetcpu(&cpu, NULL, NULL);2982#endif29832984return (retval == -1) ? retval : cpu;2985}29862987void os::Linux::sched_getcpu_init() {2988// sched_getcpu() should be in libc.2989set_sched_getcpu(CAST_TO_FN_PTR(sched_getcpu_func_t,2990dlsym(RTLD_DEFAULT, "sched_getcpu")));29912992// If it's not, try a direct syscall.2993if (sched_getcpu() == -1) {2994set_sched_getcpu(CAST_TO_FN_PTR(sched_getcpu_func_t,2995(void*)&sched_getcpu_syscall));2996}29972998if (sched_getcpu() == -1) {2999vm_exit_during_initialization("getcpu(2) system call not supported by kernel");3000}3001}30023003// Something to do with the numa-aware allocator needs these symbols3004extern "C" JNIEXPORT void numa_warn(int number, char *where, ...) { }3005extern "C" JNIEXPORT void numa_error(char *where) { }30063007// Handle request to load libnuma symbol version 1.1 (API v1). If it fails3008// load symbol from base version instead.3009void* os::Linux::libnuma_dlsym(void* handle, const char *name) {3010void *f = dlvsym(handle, name, "libnuma_1.1");3011if (f == NULL) {3012f = dlsym(handle, name);3013}3014return f;3015}30163017// Handle request to load libnuma symbol version 1.2 (API v2) only.3018// Return NULL if the symbol is not defined in this particular version.3019void* os::Linux::libnuma_v2_dlsym(void* handle, const char* name) {3020return dlvsym(handle, name, "libnuma_1.2");3021}30223023// Check numa dependent syscalls3024static bool numa_syscall_check() {3025// NUMA APIs depend on several syscalls. E.g., get_mempolicy is required for numa_get_membind and3026// numa_get_interleave_mask. But these dependent syscalls can be unsupported for various reasons.3027// Especially in dockers, get_mempolicy is not allowed with the default configuration. So it's necessary3028// to check whether the syscalls are available. Currently, only get_mempolicy is checked since checking3029// others like mbind would cause unexpected side effects.3030#ifdef SYS_get_mempolicy3031int dummy = 0;3032if (syscall(SYS_get_mempolicy, &dummy, NULL, 0, (void*)&dummy, 3) == -1) {3033return false;3034}3035#endif30363037return true;3038}30393040bool os::Linux::libnuma_init() {3041// Requires sched_getcpu() and numa dependent syscalls support3042if ((sched_getcpu() != -1) && numa_syscall_check()) {3043void *handle = dlopen("libnuma.so.1", RTLD_LAZY);3044if (handle != NULL) {3045set_numa_node_to_cpus(CAST_TO_FN_PTR(numa_node_to_cpus_func_t,3046libnuma_dlsym(handle, "numa_node_to_cpus")));3047set_numa_node_to_cpus_v2(CAST_TO_FN_PTR(numa_node_to_cpus_v2_func_t,3048libnuma_v2_dlsym(handle, "numa_node_to_cpus")));3049set_numa_max_node(CAST_TO_FN_PTR(numa_max_node_func_t,3050libnuma_dlsym(handle, "numa_max_node")));3051set_numa_num_configured_nodes(CAST_TO_FN_PTR(numa_num_configured_nodes_func_t,3052libnuma_dlsym(handle, "numa_num_configured_nodes")));3053set_numa_available(CAST_TO_FN_PTR(numa_available_func_t,3054libnuma_dlsym(handle, "numa_available")));3055set_numa_tonode_memory(CAST_TO_FN_PTR(numa_tonode_memory_func_t,3056libnuma_dlsym(handle, "numa_tonode_memory")));3057set_numa_interleave_memory(CAST_TO_FN_PTR(numa_interleave_memory_func_t,3058libnuma_dlsym(handle, "numa_interleave_memory")));3059set_numa_interleave_memory_v2(CAST_TO_FN_PTR(numa_interleave_memory_v2_func_t,3060libnuma_v2_dlsym(handle, "numa_interleave_memory")));3061set_numa_set_bind_policy(CAST_TO_FN_PTR(numa_set_bind_policy_func_t,3062libnuma_dlsym(handle, "numa_set_bind_policy")));3063set_numa_bitmask_isbitset(CAST_TO_FN_PTR(numa_bitmask_isbitset_func_t,3064libnuma_dlsym(handle, "numa_bitmask_isbitset")));3065set_numa_distance(CAST_TO_FN_PTR(numa_distance_func_t,3066libnuma_dlsym(handle, "numa_distance")));3067set_numa_get_membind(CAST_TO_FN_PTR(numa_get_membind_func_t,3068libnuma_v2_dlsym(handle, "numa_get_membind")));3069set_numa_get_interleave_mask(CAST_TO_FN_PTR(numa_get_interleave_mask_func_t,3070libnuma_v2_dlsym(handle, "numa_get_interleave_mask")));3071set_numa_move_pages(CAST_TO_FN_PTR(numa_move_pages_func_t,3072libnuma_dlsym(handle, "numa_move_pages")));3073set_numa_set_preferred(CAST_TO_FN_PTR(numa_set_preferred_func_t,3074libnuma_dlsym(handle, "numa_set_preferred")));30753076if (numa_available() != -1) {3077set_numa_all_nodes((unsigned long*)libnuma_dlsym(handle, "numa_all_nodes"));3078set_numa_all_nodes_ptr((struct bitmask **)libnuma_dlsym(handle, "numa_all_nodes_ptr"));3079set_numa_nodes_ptr((struct bitmask **)libnuma_dlsym(handle, "numa_nodes_ptr"));3080set_numa_interleave_bitmask(_numa_get_interleave_mask());3081set_numa_membind_bitmask(_numa_get_membind());3082// Create an index -> node mapping, since nodes are not always consecutive3083_nindex_to_node = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<int>(0, mtInternal);3084rebuild_nindex_to_node_map();3085// Create a cpu -> node mapping3086_cpu_to_node = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<int>(0, mtInternal);3087rebuild_cpu_to_node_map();3088return true;3089}3090}3091}3092return false;3093}30943095size_t os::Linux::default_guard_size(os::ThreadType thr_type) {3096// Creating guard page is very expensive. Java thread has HotSpot3097// guard pages, only enable glibc guard page for non-Java threads.3098// (Remember: compiler thread is a Java thread, too!)3099return ((thr_type == java_thread || thr_type == compiler_thread) ? 0 : page_size());3100}31013102void os::Linux::rebuild_nindex_to_node_map() {3103int highest_node_number = Linux::numa_max_node();31043105nindex_to_node()->clear();3106for (int node = 0; node <= highest_node_number; node++) {3107if (Linux::is_node_in_existing_nodes(node)) {3108nindex_to_node()->append(node);3109}3110}3111}31123113// rebuild_cpu_to_node_map() constructs a table mapping cpud id to node id.3114// The table is later used in get_node_by_cpu().3115void os::Linux::rebuild_cpu_to_node_map() {3116const size_t NCPUS = 32768; // Since the buffer size computation is very obscure3117// in libnuma (possible values are starting from 16,3118// and continuing up with every other power of 2, but less3119// than the maximum number of CPUs supported by kernel), and3120// is a subject to change (in libnuma version 2 the requirements3121// are more reasonable) we'll just hardcode the number they use3122// in the library.3123const size_t BitsPerCLong = sizeof(long) * CHAR_BIT;31243125size_t cpu_num = processor_count();3126size_t cpu_map_size = NCPUS / BitsPerCLong;3127size_t cpu_map_valid_size =3128MIN2((cpu_num + BitsPerCLong - 1) / BitsPerCLong, cpu_map_size);31293130cpu_to_node()->clear();3131cpu_to_node()->at_grow(cpu_num - 1);31323133size_t node_num = get_existing_num_nodes();31343135int distance = 0;3136int closest_distance = INT_MAX;3137int closest_node = 0;3138unsigned long *cpu_map = NEW_C_HEAP_ARRAY(unsigned long, cpu_map_size, mtInternal);3139for (size_t i = 0; i < node_num; i++) {3140// Check if node is configured (not a memory-less node). If it is not, find3141// the closest configured node. Check also if node is bound, i.e. it's allowed3142// to allocate memory from the node. If it's not allowed, map cpus in that node3143// to the closest node from which memory allocation is allowed.3144if (!is_node_in_configured_nodes(nindex_to_node()->at(i)) ||3145!is_node_in_bound_nodes(nindex_to_node()->at(i))) {3146closest_distance = INT_MAX;3147// Check distance from all remaining nodes in the system. Ignore distance3148// from itself, from another non-configured node, and from another non-bound3149// node.3150for (size_t m = 0; m < node_num; m++) {3151if (m != i &&3152is_node_in_configured_nodes(nindex_to_node()->at(m)) &&3153is_node_in_bound_nodes(nindex_to_node()->at(m))) {3154distance = numa_distance(nindex_to_node()->at(i), nindex_to_node()->at(m));3155// If a closest node is found, update. There is always at least one3156// configured and bound node in the system so there is always at least3157// one node close.3158if (distance != 0 && distance < closest_distance) {3159closest_distance = distance;3160closest_node = nindex_to_node()->at(m);3161}3162}3163}3164} else {3165// Current node is already a configured node.3166closest_node = nindex_to_node()->at(i);3167}31683169// Get cpus from the original node and map them to the closest node. If node3170// is a configured node (not a memory-less node), then original node and3171// closest node are the same.3172if (numa_node_to_cpus(nindex_to_node()->at(i), cpu_map, cpu_map_size * sizeof(unsigned long)) != -1) {3173for (size_t j = 0; j < cpu_map_valid_size; j++) {3174if (cpu_map[j] != 0) {3175for (size_t k = 0; k < BitsPerCLong; k++) {3176if (cpu_map[j] & (1UL << k)) {3177int cpu_index = j * BitsPerCLong + k;31783179#ifndef PRODUCT3180if (UseDebuggerErgo1 && cpu_index >= (int)cpu_num) {3181// Some debuggers limit the processor count without3182// intercepting the NUMA APIs. Just fake the values.3183cpu_index = 0;3184}3185#endif31863187cpu_to_node()->at_put(cpu_index, closest_node);3188}3189}3190}3191}3192}3193}3194FREE_C_HEAP_ARRAY(unsigned long, cpu_map);3195}31963197int os::Linux::numa_node_to_cpus(int node, unsigned long *buffer, int bufferlen) {3198// use the latest version of numa_node_to_cpus if available3199if (_numa_node_to_cpus_v2 != NULL) {32003201// libnuma bitmask struct3202struct bitmask {3203unsigned long size; /* number of bits in the map */3204unsigned long *maskp;3205};32063207struct bitmask mask;3208mask.maskp = (unsigned long *)buffer;3209mask.size = bufferlen * 8;3210return _numa_node_to_cpus_v2(node, &mask);3211} else if (_numa_node_to_cpus != NULL) {3212return _numa_node_to_cpus(node, buffer, bufferlen);3213}3214return -1;3215}32163217int os::Linux::get_node_by_cpu(int cpu_id) {3218if (cpu_to_node() != NULL && cpu_id >= 0 && cpu_id < cpu_to_node()->length()) {3219return cpu_to_node()->at(cpu_id);3220}3221return -1;3222}32233224GrowableArray<int>* os::Linux::_cpu_to_node;3225GrowableArray<int>* os::Linux::_nindex_to_node;3226os::Linux::sched_getcpu_func_t os::Linux::_sched_getcpu;3227os::Linux::numa_node_to_cpus_func_t os::Linux::_numa_node_to_cpus;3228os::Linux::numa_node_to_cpus_v2_func_t os::Linux::_numa_node_to_cpus_v2;3229os::Linux::numa_max_node_func_t os::Linux::_numa_max_node;3230os::Linux::numa_num_configured_nodes_func_t os::Linux::_numa_num_configured_nodes;3231os::Linux::numa_available_func_t os::Linux::_numa_available;3232os::Linux::numa_tonode_memory_func_t os::Linux::_numa_tonode_memory;3233os::Linux::numa_interleave_memory_func_t os::Linux::_numa_interleave_memory;3234os::Linux::numa_interleave_memory_v2_func_t os::Linux::_numa_interleave_memory_v2;3235os::Linux::numa_set_bind_policy_func_t os::Linux::_numa_set_bind_policy;3236os::Linux::numa_bitmask_isbitset_func_t os::Linux::_numa_bitmask_isbitset;3237os::Linux::numa_distance_func_t os::Linux::_numa_distance;3238os::Linux::numa_get_membind_func_t os::Linux::_numa_get_membind;3239os::Linux::numa_get_interleave_mask_func_t os::Linux::_numa_get_interleave_mask;3240os::Linux::numa_move_pages_func_t os::Linux::_numa_move_pages;3241os::Linux::numa_set_preferred_func_t os::Linux::_numa_set_preferred;3242os::Linux::NumaAllocationPolicy os::Linux::_current_numa_policy;3243unsigned long* os::Linux::_numa_all_nodes;3244struct bitmask* os::Linux::_numa_all_nodes_ptr;3245struct bitmask* os::Linux::_numa_nodes_ptr;3246struct bitmask* os::Linux::_numa_interleave_bitmask;3247struct bitmask* os::Linux::_numa_membind_bitmask;32483249bool os::pd_uncommit_memory(char* addr, size_t size, bool exec) {3250uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE,3251MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0);3252return res != (uintptr_t) MAP_FAILED;3253}32543255static address get_stack_commited_bottom(address bottom, size_t size) {3256address nbot = bottom;3257address ntop = bottom + size;32583259size_t page_sz = os::vm_page_size();3260unsigned pages = size / page_sz;32613262unsigned char vec[1];3263unsigned imin = 1, imax = pages + 1, imid;3264int mincore_return_value = 0;32653266assert(imin <= imax, "Unexpected page size");32673268while (imin < imax) {3269imid = (imax + imin) / 2;3270nbot = ntop - (imid * page_sz);32713272// Use a trick with mincore to check whether the page is mapped or not.3273// mincore sets vec to 1 if page resides in memory and to 0 if page3274// is swapped output but if page we are asking for is unmapped3275// it returns -1,ENOMEM3276mincore_return_value = mincore(nbot, page_sz, vec);32773278if (mincore_return_value == -1) {3279// Page is not mapped go up3280// to find first mapped page3281if (errno != EAGAIN) {3282assert(errno == ENOMEM, "Unexpected mincore errno");3283imax = imid;3284}3285} else {3286// Page is mapped go down3287// to find first not mapped page3288imin = imid + 1;3289}3290}32913292nbot = nbot + page_sz;32933294// Adjust stack bottom one page up if last checked page is not mapped3295if (mincore_return_value == -1) {3296nbot = nbot + page_sz;3297}32983299return nbot;3300}33013302bool os::committed_in_range(address start, size_t size, address& committed_start, size_t& committed_size) {3303int mincore_return_value;3304const size_t stripe = 1024; // query this many pages each time3305unsigned char vec[stripe + 1];3306// set a guard3307vec[stripe] = 'X';33083309const size_t page_sz = os::vm_page_size();3310size_t pages = size / page_sz;33113312assert(is_aligned(start, page_sz), "Start address must be page aligned");3313assert(is_aligned(size, page_sz), "Size must be page aligned");33143315committed_start = NULL;33163317int loops = (pages + stripe - 1) / stripe;3318int committed_pages = 0;3319address loop_base = start;3320bool found_range = false;33213322for (int index = 0; index < loops && !found_range; index ++) {3323assert(pages > 0, "Nothing to do");3324int pages_to_query = (pages >= stripe) ? stripe : pages;3325pages -= pages_to_query;33263327// Get stable read3328while ((mincore_return_value = mincore(loop_base, pages_to_query * page_sz, vec)) == -1 && errno == EAGAIN);33293330// During shutdown, some memory goes away without properly notifying NMT,3331// E.g. ConcurrentGCThread/WatcherThread can exit without deleting thread object.3332// Bailout and return as not committed for now.3333if (mincore_return_value == -1 && errno == ENOMEM) {3334return false;3335}33363337assert(vec[stripe] == 'X', "overflow guard");3338assert(mincore_return_value == 0, "Range must be valid");3339// Process this stripe3340for (int vecIdx = 0; vecIdx < pages_to_query; vecIdx ++) {3341if ((vec[vecIdx] & 0x01) == 0) { // not committed3342// End of current contiguous region3343if (committed_start != NULL) {3344found_range = true;3345break;3346}3347} else { // committed3348// Start of region3349if (committed_start == NULL) {3350committed_start = loop_base + page_sz * vecIdx;3351}3352committed_pages ++;3353}3354}33553356loop_base += pages_to_query * page_sz;3357}33583359if (committed_start != NULL) {3360assert(committed_pages > 0, "Must have committed region");3361assert(committed_pages <= int(size / page_sz), "Can not commit more than it has");3362assert(committed_start >= start && committed_start < start + size, "Out of range");3363committed_size = page_sz * committed_pages;3364return true;3365} else {3366assert(committed_pages == 0, "Should not have committed region");3367return false;3368}3369}337033713372// Linux uses a growable mapping for the stack, and if the mapping for3373// the stack guard pages is not removed when we detach a thread the3374// stack cannot grow beyond the pages where the stack guard was3375// mapped. If at some point later in the process the stack expands to3376// that point, the Linux kernel cannot expand the stack any further3377// because the guard pages are in the way, and a segfault occurs.3378//3379// However, it's essential not to split the stack region by unmapping3380// a region (leaving a hole) that's already part of the stack mapping,3381// so if the stack mapping has already grown beyond the guard pages at3382// the time we create them, we have to truncate the stack mapping.3383// So, we need to know the extent of the stack mapping when3384// create_stack_guard_pages() is called.33853386// We only need this for stacks that are growable: at the time of3387// writing thread stacks don't use growable mappings (i.e. those3388// creeated with MAP_GROWSDOWN), and aren't marked "[stack]", so this3389// only applies to the main thread.33903391// If the (growable) stack mapping already extends beyond the point3392// where we're going to put our guard pages, truncate the mapping at3393// that point by munmap()ping it. This ensures that when we later3394// munmap() the guard pages we don't leave a hole in the stack3395// mapping. This only affects the main/primordial thread33963397bool os::pd_create_stack_guard_pages(char* addr, size_t size) {3398if (os::is_primordial_thread()) {3399// As we manually grow stack up to bottom inside create_attached_thread(),3400// it's likely that os::Linux::initial_thread_stack_bottom is mapped and3401// we don't need to do anything special.3402// Check it first, before calling heavy function.3403uintptr_t stack_extent = (uintptr_t) os::Linux::initial_thread_stack_bottom();3404unsigned char vec[1];34053406if (mincore((address)stack_extent, os::vm_page_size(), vec) == -1) {3407// Fallback to slow path on all errors, including EAGAIN3408assert((uintptr_t)addr >= stack_extent,3409"Sanity: addr should be larger than extent, " PTR_FORMAT " >= " PTR_FORMAT,3410p2i(addr), stack_extent);3411stack_extent = (uintptr_t) get_stack_commited_bottom(3412os::Linux::initial_thread_stack_bottom(),3413(size_t)addr - stack_extent);3414}34153416if (stack_extent < (uintptr_t)addr) {3417::munmap((void*)stack_extent, (uintptr_t)(addr - stack_extent));3418}3419}34203421return os::commit_memory(addr, size, !ExecMem);3422}34233424// If this is a growable mapping, remove the guard pages entirely by3425// munmap()ping them. If not, just call uncommit_memory(). This only3426// affects the main/primordial thread, but guard against future OS changes.3427// It's safe to always unmap guard pages for primordial thread because we3428// always place it right after end of the mapped region.34293430bool os::remove_stack_guard_pages(char* addr, size_t size) {3431uintptr_t stack_extent, stack_base;34323433if (os::is_primordial_thread()) {3434return ::munmap(addr, size) == 0;3435}34363437return os::uncommit_memory(addr, size);3438}34393440// 'requested_addr' is only treated as a hint, the return value may or3441// may not start from the requested address. Unlike Linux mmap(), this3442// function returns NULL to indicate failure.3443static char* anon_mmap(char* requested_addr, size_t bytes) {3444// MAP_FIXED is intentionally left out, to leave existing mappings intact.3445const int flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS;34463447// Map reserved/uncommitted pages PROT_NONE so we fail early if we3448// touch an uncommitted page. Otherwise, the read/write might3449// succeed if we have enough swap space to back the physical page.3450char* addr = (char*)::mmap(requested_addr, bytes, PROT_NONE, flags, -1, 0);34513452return addr == MAP_FAILED ? NULL : addr;3453}34543455// Allocate (using mmap, NO_RESERVE, with small pages) at either a given request address3456// (req_addr != NULL) or with a given alignment.3457// - bytes shall be a multiple of alignment.3458// - req_addr can be NULL. If not NULL, it must be a multiple of alignment.3459// - alignment sets the alignment at which memory shall be allocated.3460// It must be a multiple of allocation granularity.3461// Returns address of memory or NULL. If req_addr was not NULL, will only return3462// req_addr or NULL.3463static char* anon_mmap_aligned(char* req_addr, size_t bytes, size_t alignment) {3464size_t extra_size = bytes;3465if (req_addr == NULL && alignment > 0) {3466extra_size += alignment;3467}34683469char* start = anon_mmap(req_addr, extra_size);3470if (start != NULL) {3471if (req_addr != NULL) {3472if (start != req_addr) {3473::munmap(start, extra_size);3474start = NULL;3475}3476} else {3477char* const start_aligned = align_up(start, alignment);3478char* const end_aligned = start_aligned + bytes;3479char* const end = start + extra_size;3480if (start_aligned > start) {3481::munmap(start, start_aligned - start);3482}3483if (end_aligned < end) {3484::munmap(end_aligned, end - end_aligned);3485}3486start = start_aligned;3487}3488}3489return start;3490}34913492static int anon_munmap(char * addr, size_t size) {3493return ::munmap(addr, size) == 0;3494}34953496char* os::pd_reserve_memory(size_t bytes, bool exec) {3497return anon_mmap(NULL, bytes);3498}34993500bool os::pd_release_memory(char* addr, size_t size) {3501return anon_munmap(addr, size);3502}35033504#ifdef CAN_SHOW_REGISTERS_ON_ASSERT3505extern char* g_assert_poison; // assertion poison page address3506#endif35073508static bool linux_mprotect(char* addr, size_t size, int prot) {3509// Linux wants the mprotect address argument to be page aligned.3510char* bottom = (char*)align_down((intptr_t)addr, os::Linux::page_size());35113512// According to SUSv3, mprotect() should only be used with mappings3513// established by mmap(), and mmap() always maps whole pages. Unaligned3514// 'addr' likely indicates problem in the VM (e.g. trying to change3515// protection of malloc'ed or statically allocated memory). Check the3516// caller if you hit this assert.3517assert(addr == bottom, "sanity check");35183519size = align_up(pointer_delta(addr, bottom, 1) + size, os::Linux::page_size());3520// Don't log anything if we're executing in the poison page signal handling3521// context. It can lead to reentrant use of other parts of the VM code.3522#ifdef CAN_SHOW_REGISTERS_ON_ASSERT3523if (addr != g_assert_poison)3524#endif3525Events::log(NULL, "Protecting memory [" INTPTR_FORMAT "," INTPTR_FORMAT "] with protection modes %x", p2i(bottom), p2i(bottom+size), prot);3526return ::mprotect(bottom, size, prot) == 0;3527}35283529// Set protections specified3530bool os::protect_memory(char* addr, size_t bytes, ProtType prot,3531bool is_committed) {3532unsigned int p = 0;3533switch (prot) {3534case MEM_PROT_NONE: p = PROT_NONE; break;3535case MEM_PROT_READ: p = PROT_READ; break;3536case MEM_PROT_RW: p = PROT_READ|PROT_WRITE; break;3537case MEM_PROT_RWX: p = PROT_READ|PROT_WRITE|PROT_EXEC; break;3538default:3539ShouldNotReachHere();3540}3541// is_committed is unused.3542return linux_mprotect(addr, bytes, p);3543}35443545bool os::guard_memory(char* addr, size_t size) {3546return linux_mprotect(addr, size, PROT_NONE);3547}35483549bool os::unguard_memory(char* addr, size_t size) {3550return linux_mprotect(addr, size, PROT_READ|PROT_WRITE);3551}35523553bool os::Linux::transparent_huge_pages_sanity_check(bool warn,3554size_t page_size) {3555bool result = false;3556void *p = mmap(NULL, page_size * 2, PROT_READ|PROT_WRITE,3557MAP_ANONYMOUS|MAP_PRIVATE,3558-1, 0);3559if (p != MAP_FAILED) {3560void *aligned_p = align_up(p, page_size);35613562result = madvise(aligned_p, page_size, MADV_HUGEPAGE) == 0;35633564munmap(p, page_size * 2);3565}35663567if (warn && !result) {3568warning("TransparentHugePages is not supported by the operating system.");3569}35703571return result;3572}35733574int os::Linux::hugetlbfs_page_size_flag(size_t page_size) {3575if (page_size != default_large_page_size()) {3576return (exact_log2(page_size) << MAP_HUGE_SHIFT);3577}3578return 0;3579}35803581bool os::Linux::hugetlbfs_sanity_check(bool warn, size_t page_size) {3582// Include the page size flag to ensure we sanity check the correct page size.3583int flags = MAP_ANONYMOUS | MAP_PRIVATE | MAP_HUGETLB | hugetlbfs_page_size_flag(page_size);3584void *p = mmap(NULL, page_size, PROT_READ|PROT_WRITE, flags, -1, 0);35853586if (p != MAP_FAILED) {3587// Mapping succeeded, sanity check passed.3588munmap(p, page_size);3589return true;3590} else {3591log_info(pagesize)("Large page size (" SIZE_FORMAT "%s) failed sanity check, "3592"checking if smaller large page sizes are usable",3593byte_size_in_exact_unit(page_size),3594exact_unit_for_byte_size(page_size));3595for (size_t page_size_ = _page_sizes.next_smaller(page_size);3596page_size_ != (size_t)os::vm_page_size();3597page_size_ = _page_sizes.next_smaller(page_size_)) {3598flags = MAP_ANONYMOUS | MAP_PRIVATE | MAP_HUGETLB | hugetlbfs_page_size_flag(page_size_);3599p = mmap(NULL, page_size_, PROT_READ|PROT_WRITE, flags, -1, 0);3600if (p != MAP_FAILED) {3601// Mapping succeeded, sanity check passed.3602munmap(p, page_size_);3603log_info(pagesize)("Large page size (" SIZE_FORMAT "%s) passed sanity check",3604byte_size_in_exact_unit(page_size_),3605exact_unit_for_byte_size(page_size_));3606return true;3607}3608}3609}36103611if (warn) {3612warning("HugeTLBFS is not configured or not supported by the operating system.");3613}36143615return false;3616}36173618bool os::Linux::shm_hugetlbfs_sanity_check(bool warn, size_t page_size) {3619// Try to create a large shared memory segment.3620int shmid = shmget(IPC_PRIVATE, page_size, SHM_HUGETLB|IPC_CREAT|SHM_R|SHM_W);3621if (shmid == -1) {3622// Possible reasons for shmget failure:3623// 1. shmmax is too small for the request.3624// > check shmmax value: cat /proc/sys/kernel/shmmax3625// > increase shmmax value: echo "new_value" > /proc/sys/kernel/shmmax3626// 2. not enough large page memory.3627// > check available large pages: cat /proc/meminfo3628// > increase amount of large pages:3629// sysctl -w vm.nr_hugepages=new_value3630// > For more information regarding large pages please refer to:3631// https://www.kernel.org/doc/Documentation/vm/hugetlbpage.txt3632if (warn) {3633warning("Large pages using UseSHM are not configured on this system.");3634}3635return false;3636}3637// Managed to create a segment, now delete it.3638shmctl(shmid, IPC_RMID, NULL);3639return true;3640}36413642// From the coredump_filter documentation:3643//3644// - (bit 0) anonymous private memory3645// - (bit 1) anonymous shared memory3646// - (bit 2) file-backed private memory3647// - (bit 3) file-backed shared memory3648// - (bit 4) ELF header pages in file-backed private memory areas (it is3649// effective only if the bit 2 is cleared)3650// - (bit 5) hugetlb private memory3651// - (bit 6) hugetlb shared memory3652// - (bit 7) dax private memory3653// - (bit 8) dax shared memory3654//3655static void set_coredump_filter(CoredumpFilterBit bit) {3656FILE *f;3657long cdm;36583659if ((f = fopen("/proc/self/coredump_filter", "r+")) == NULL) {3660return;3661}36623663if (fscanf(f, "%lx", &cdm) != 1) {3664fclose(f);3665return;3666}36673668long saved_cdm = cdm;3669rewind(f);3670cdm |= bit;36713672if (cdm != saved_cdm) {3673fprintf(f, "%#lx", cdm);3674}36753676fclose(f);3677}36783679// Large page support36803681static size_t _large_page_size = 0;36823683static size_t scan_default_large_page_size() {3684size_t default_large_page_size = 0;36853686// large_page_size on Linux is used to round up heap size. x86 uses either3687// 2M or 4M page, depending on whether PAE (Physical Address Extensions)3688// mode is enabled. AMD64/EM64T uses 2M page in 64bit mode. IA64 can use3689// page as large as 1G.3690//3691// Here we try to figure out page size by parsing /proc/meminfo and looking3692// for a line with the following format:3693// Hugepagesize: 2048 kB3694//3695// If we can't determine the value (e.g. /proc is not mounted, or the text3696// format has been changed), we'll set largest page size to 036973698FILE *fp = fopen("/proc/meminfo", "r");3699if (fp) {3700while (!feof(fp)) {3701int x = 0;3702char buf[16];3703if (fscanf(fp, "Hugepagesize: %d", &x) == 1) {3704if (x && fgets(buf, sizeof(buf), fp) && strcmp(buf, " kB\n") == 0) {3705default_large_page_size = x * K;3706break;3707}3708} else {3709// skip to next line3710for (;;) {3711int ch = fgetc(fp);3712if (ch == EOF || ch == (int)'\n') break;3713}3714}3715}3716fclose(fp);3717}37183719return default_large_page_size;3720}37213722static os::PageSizes scan_multiple_page_support() {3723// Scan /sys/kernel/mm/hugepages3724// to discover the available page sizes3725const char* sys_hugepages = "/sys/kernel/mm/hugepages";3726os::PageSizes page_sizes;37273728DIR *dir = opendir(sys_hugepages);37293730struct dirent *entry;3731size_t page_size;3732while ((entry = readdir(dir)) != NULL) {3733if (entry->d_type == DT_DIR &&3734sscanf(entry->d_name, "hugepages-%zukB", &page_size) == 1) {3735// The kernel is using kB, hotspot uses bytes3736// Add each found Large Page Size to page_sizes3737page_sizes.add(page_size * K);3738}3739}3740closedir(dir);37413742LogTarget(Debug, pagesize) lt;3743if (lt.is_enabled()) {3744LogStream ls(lt);3745ls.print("Large Page sizes: ");3746page_sizes.print_on(&ls);3747}37483749return page_sizes;3750}37513752size_t os::Linux::default_large_page_size() {3753return _default_large_page_size;3754}37553756void warn_no_large_pages_configured() {3757if (!FLAG_IS_DEFAULT(UseLargePages)) {3758log_warning(pagesize)("UseLargePages disabled, no large pages configured and available on the system.");3759}3760}37613762bool os::Linux::setup_large_page_type(size_t page_size) {3763if (FLAG_IS_DEFAULT(UseHugeTLBFS) &&3764FLAG_IS_DEFAULT(UseSHM) &&3765FLAG_IS_DEFAULT(UseTransparentHugePages)) {37663767// The type of large pages has not been specified by the user.37683769// Try UseHugeTLBFS and then UseSHM.3770UseHugeTLBFS = UseSHM = true;37713772// Don't try UseTransparentHugePages since there are known3773// performance issues with it turned on. This might change in the future.3774UseTransparentHugePages = false;3775}37763777if (UseTransparentHugePages) {3778bool warn_on_failure = !FLAG_IS_DEFAULT(UseTransparentHugePages);3779if (transparent_huge_pages_sanity_check(warn_on_failure, page_size)) {3780UseHugeTLBFS = false;3781UseSHM = false;3782return true;3783}3784UseTransparentHugePages = false;3785}37863787if (UseHugeTLBFS) {3788bool warn_on_failure = !FLAG_IS_DEFAULT(UseHugeTLBFS);3789if (hugetlbfs_sanity_check(warn_on_failure, page_size)) {3790UseSHM = false;3791return true;3792}3793UseHugeTLBFS = false;3794}37953796if (UseSHM) {3797bool warn_on_failure = !FLAG_IS_DEFAULT(UseSHM);3798if (shm_hugetlbfs_sanity_check(warn_on_failure, page_size)) {3799return true;3800}3801UseSHM = false;3802}38033804warn_no_large_pages_configured();3805return false;3806}38073808void os::large_page_init() {3809// 1) Handle the case where we do not want to use huge pages and hence3810// there is no need to scan the OS for related info3811if (!UseLargePages &&3812!UseTransparentHugePages &&3813!UseHugeTLBFS &&3814!UseSHM) {3815// Not using large pages.3816return;3817}38183819if (!FLAG_IS_DEFAULT(UseLargePages) && !UseLargePages) {3820// The user explicitly turned off large pages.3821// Ignore the rest of the large pages flags.3822UseTransparentHugePages = false;3823UseHugeTLBFS = false;3824UseSHM = false;3825return;3826}38273828// 2) Scan OS info3829size_t default_large_page_size = scan_default_large_page_size();3830os::Linux::_default_large_page_size = default_large_page_size;3831if (default_large_page_size == 0) {3832// No large pages configured, return.3833warn_no_large_pages_configured();3834UseLargePages = false;3835UseTransparentHugePages = false;3836UseHugeTLBFS = false;3837UseSHM = false;3838return;3839}3840os::PageSizes all_large_pages = scan_multiple_page_support();38413842// 3) Consistency check and post-processing38433844// It is unclear if /sys/kernel/mm/hugepages/ and /proc/meminfo could disagree. Manually3845// re-add the default page size to the list of page sizes to be sure.3846all_large_pages.add(default_large_page_size);38473848// Check LargePageSizeInBytes matches an available page size and if so set _large_page_size3849// using LargePageSizeInBytes as the maximum allowed large page size. If LargePageSizeInBytes3850// doesn't match an available page size set _large_page_size to default_large_page_size3851// and use it as the maximum.3852if (FLAG_IS_DEFAULT(LargePageSizeInBytes) ||3853LargePageSizeInBytes == 0 ||3854LargePageSizeInBytes == default_large_page_size) {3855_large_page_size = default_large_page_size;3856log_info(pagesize)("Using the default large page size: " SIZE_FORMAT "%s",3857byte_size_in_exact_unit(_large_page_size),3858exact_unit_for_byte_size(_large_page_size));3859} else {3860if (all_large_pages.contains(LargePageSizeInBytes)) {3861_large_page_size = LargePageSizeInBytes;3862log_info(pagesize)("Overriding default large page size (" SIZE_FORMAT "%s) "3863"using LargePageSizeInBytes: " SIZE_FORMAT "%s",3864byte_size_in_exact_unit(default_large_page_size),3865exact_unit_for_byte_size(default_large_page_size),3866byte_size_in_exact_unit(_large_page_size),3867exact_unit_for_byte_size(_large_page_size));3868} else {3869_large_page_size = default_large_page_size;3870log_info(pagesize)("LargePageSizeInBytes is not a valid large page size (" SIZE_FORMAT "%s) "3871"using the default large page size: " SIZE_FORMAT "%s",3872byte_size_in_exact_unit(LargePageSizeInBytes),3873exact_unit_for_byte_size(LargePageSizeInBytes),3874byte_size_in_exact_unit(_large_page_size),3875exact_unit_for_byte_size(_large_page_size));3876}3877}38783879// Populate _page_sizes with large page sizes less than or equal to3880// _large_page_size.3881for (size_t page_size = _large_page_size; page_size != 0;3882page_size = all_large_pages.next_smaller(page_size)) {3883_page_sizes.add(page_size);3884}38853886LogTarget(Info, pagesize) lt;3887if (lt.is_enabled()) {3888LogStream ls(lt);3889ls.print("Usable page sizes: ");3890_page_sizes.print_on(&ls);3891}38923893// Now determine the type of large pages to use:3894UseLargePages = os::Linux::setup_large_page_type(_large_page_size);38953896set_coredump_filter(LARGEPAGES_BIT);3897}38983899#ifndef SHM_HUGETLB3900#define SHM_HUGETLB 040003901#endif39023903#define shm_warning_format(format, ...) \3904do { \3905if (UseLargePages && \3906(!FLAG_IS_DEFAULT(UseLargePages) || \3907!FLAG_IS_DEFAULT(UseSHM) || \3908!FLAG_IS_DEFAULT(LargePageSizeInBytes))) { \3909warning(format, __VA_ARGS__); \3910} \3911} while (0)39123913#define shm_warning(str) shm_warning_format("%s", str)39143915#define shm_warning_with_errno(str) \3916do { \3917int err = errno; \3918shm_warning_format(str " (error = %d)", err); \3919} while (0)39203921static char* shmat_with_alignment(int shmid, size_t bytes, size_t alignment) {3922assert(is_aligned(bytes, alignment), "Must be divisible by the alignment");39233924if (!is_aligned(alignment, SHMLBA)) {3925assert(false, "Code below assumes that alignment is at least SHMLBA aligned");3926return NULL;3927}39283929// To ensure that we get 'alignment' aligned memory from shmat,3930// we pre-reserve aligned virtual memory and then attach to that.39313932char* pre_reserved_addr = anon_mmap_aligned(NULL /* req_addr */, bytes, alignment);3933if (pre_reserved_addr == NULL) {3934// Couldn't pre-reserve aligned memory.3935shm_warning("Failed to pre-reserve aligned memory for shmat.");3936return NULL;3937}39383939// SHM_REMAP is needed to allow shmat to map over an existing mapping.3940char* addr = (char*)shmat(shmid, pre_reserved_addr, SHM_REMAP);39413942if ((intptr_t)addr == -1) {3943int err = errno;3944shm_warning_with_errno("Failed to attach shared memory.");39453946assert(err != EACCES, "Unexpected error");3947assert(err != EIDRM, "Unexpected error");3948assert(err != EINVAL, "Unexpected error");39493950// Since we don't know if the kernel unmapped the pre-reserved memory area3951// we can't unmap it, since that would potentially unmap memory that was3952// mapped from other threads.3953return NULL;3954}39553956return addr;3957}39583959static char* shmat_at_address(int shmid, char* req_addr) {3960if (!is_aligned(req_addr, SHMLBA)) {3961assert(false, "Requested address needs to be SHMLBA aligned");3962return NULL;3963}39643965char* addr = (char*)shmat(shmid, req_addr, 0);39663967if ((intptr_t)addr == -1) {3968shm_warning_with_errno("Failed to attach shared memory.");3969return NULL;3970}39713972return addr;3973}39743975static char* shmat_large_pages(int shmid, size_t bytes, size_t alignment, char* req_addr) {3976// If a req_addr has been provided, we assume that the caller has already aligned the address.3977if (req_addr != NULL) {3978assert(is_aligned(req_addr, os::large_page_size()), "Must be divisible by the large page size");3979assert(is_aligned(req_addr, alignment), "Must be divisible by given alignment");3980return shmat_at_address(shmid, req_addr);3981}39823983// Since shmid has been setup with SHM_HUGETLB, shmat will automatically3984// return large page size aligned memory addresses when req_addr == NULL.3985// However, if the alignment is larger than the large page size, we have3986// to manually ensure that the memory returned is 'alignment' aligned.3987if (alignment > os::large_page_size()) {3988assert(is_aligned(alignment, os::large_page_size()), "Must be divisible by the large page size");3989return shmat_with_alignment(shmid, bytes, alignment);3990} else {3991return shmat_at_address(shmid, NULL);3992}3993}39943995char* os::Linux::reserve_memory_special_shm(size_t bytes, size_t alignment,3996char* req_addr, bool exec) {3997// "exec" is passed in but not used. Creating the shared image for3998// the code cache doesn't have an SHM_X executable permission to check.3999assert(UseLargePages && UseSHM, "only for SHM large pages");4000assert(is_aligned(req_addr, os::large_page_size()), "Unaligned address");4001assert(is_aligned(req_addr, alignment), "Unaligned address");40024003if (!is_aligned(bytes, os::large_page_size())) {4004return NULL; // Fallback to small pages.4005}40064007// Create a large shared memory region to attach to based on size.4008// Currently, size is the total size of the heap.4009int shmid = shmget(IPC_PRIVATE, bytes, SHM_HUGETLB|IPC_CREAT|SHM_R|SHM_W);4010if (shmid == -1) {4011// Possible reasons for shmget failure:4012// 1. shmmax is too small for the request.4013// > check shmmax value: cat /proc/sys/kernel/shmmax4014// > increase shmmax value: echo "new_value" > /proc/sys/kernel/shmmax4015// 2. not enough large page memory.4016// > check available large pages: cat /proc/meminfo4017// > increase amount of large pages:4018// sysctl -w vm.nr_hugepages=new_value4019// > For more information regarding large pages please refer to:4020// https://www.kernel.org/doc/Documentation/vm/hugetlbpage.txt4021// Note 1: different Linux may use different name for this property,4022// e.g. on Redhat AS-3 it is "hugetlb_pool".4023// Note 2: it's possible there's enough physical memory available but4024// they are so fragmented after a long run that they can't4025// coalesce into large pages. Try to reserve large pages when4026// the system is still "fresh".4027shm_warning_with_errno("Failed to reserve shared memory.");4028return NULL;4029}40304031// Attach to the region.4032char* addr = shmat_large_pages(shmid, bytes, alignment, req_addr);40334034// Remove shmid. If shmat() is successful, the actual shared memory segment4035// will be deleted when it's detached by shmdt() or when the process4036// terminates. If shmat() is not successful this will remove the shared4037// segment immediately.4038shmctl(shmid, IPC_RMID, NULL);40394040return addr;4041}40424043static void warn_on_commit_special_failure(char* req_addr, size_t bytes,4044size_t page_size, int error) {4045assert(error == ENOMEM, "Only expect to fail if no memory is available");40464047bool warn_on_failure = UseLargePages &&4048(!FLAG_IS_DEFAULT(UseLargePages) ||4049!FLAG_IS_DEFAULT(UseHugeTLBFS) ||4050!FLAG_IS_DEFAULT(LargePageSizeInBytes));40514052if (warn_on_failure) {4053char msg[128];4054jio_snprintf(msg, sizeof(msg), "Failed to reserve and commit memory. req_addr: "4055PTR_FORMAT " bytes: " SIZE_FORMAT " page size: "4056SIZE_FORMAT " (errno = %d).",4057req_addr, bytes, page_size, error);4058warning("%s", msg);4059}4060}40614062bool os::Linux::commit_memory_special(size_t bytes,4063size_t page_size,4064char* req_addr,4065bool exec) {4066assert(UseLargePages && UseHugeTLBFS, "Should only get here when HugeTLBFS large pages are used");4067assert(is_aligned(bytes, page_size), "Unaligned size");4068assert(is_aligned(req_addr, page_size), "Unaligned address");4069assert(req_addr != NULL, "Must have a requested address for special mappings");40704071int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;4072int flags = MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED;40734074// For large pages additional flags are required.4075if (page_size > (size_t) os::vm_page_size()) {4076flags |= MAP_HUGETLB | hugetlbfs_page_size_flag(page_size);4077}4078char* addr = (char*)::mmap(req_addr, bytes, prot, flags, -1, 0);40794080if (addr == MAP_FAILED) {4081warn_on_commit_special_failure(req_addr, bytes, page_size, errno);4082return false;4083}40844085log_debug(pagesize)("Commit special mapping: " PTR_FORMAT ", size=" SIZE_FORMAT "%s, page size="4086SIZE_FORMAT "%s",4087p2i(addr), byte_size_in_exact_unit(bytes),4088exact_unit_for_byte_size(bytes),4089byte_size_in_exact_unit(page_size),4090exact_unit_for_byte_size(page_size));4091assert(is_aligned(addr, page_size), "Must be");4092return true;4093}40944095char* os::Linux::reserve_memory_special_huge_tlbfs(size_t bytes,4096size_t alignment,4097size_t page_size,4098char* req_addr,4099bool exec) {4100assert(UseLargePages && UseHugeTLBFS, "only for Huge TLBFS large pages");4101assert(is_aligned(req_addr, alignment), "Must be");4102assert(is_aligned(req_addr, page_size), "Must be");4103assert(is_aligned(alignment, os::vm_allocation_granularity()), "Must be");4104assert(_page_sizes.contains(page_size), "Must be a valid page size");4105assert(page_size > (size_t)os::vm_page_size(), "Must be a large page size");4106assert(bytes >= page_size, "Shouldn't allocate large pages for small sizes");41074108// We only end up here when at least 1 large page can be used.4109// If the size is not a multiple of the large page size, we4110// will mix the type of pages used, but in a decending order.4111// Start off by reserving a range of the given size that is4112// properly aligned. At this point no pages are committed. If4113// a requested address is given it will be used and it must be4114// aligned to both the large page size and the given alignment.4115// The larger of the two will be used.4116size_t required_alignment = MAX(page_size, alignment);4117char* const aligned_start = anon_mmap_aligned(req_addr, bytes, required_alignment);4118if (aligned_start == NULL) {4119return NULL;4120}41214122// First commit using large pages.4123size_t large_bytes = align_down(bytes, page_size);4124bool large_committed = commit_memory_special(large_bytes, page_size, aligned_start, exec);41254126if (large_committed && bytes == large_bytes) {4127// The size was large page aligned so no additional work is4128// needed even if the commit failed.4129return aligned_start;4130}41314132// The requested size requires some small pages as well.4133char* small_start = aligned_start + large_bytes;4134size_t small_size = bytes - large_bytes;4135if (!large_committed) {4136// Failed to commit large pages, so we need to unmap the4137// reminder of the orinal reservation.4138::munmap(small_start, small_size);4139return NULL;4140}41414142// Commit the remaining bytes using small pages.4143bool small_committed = commit_memory_special(small_size, os::vm_page_size(), small_start, exec);4144if (!small_committed) {4145// Failed to commit the remaining size, need to unmap4146// the large pages part of the reservation.4147::munmap(aligned_start, large_bytes);4148return NULL;4149}4150return aligned_start;4151}41524153char* os::pd_reserve_memory_special(size_t bytes, size_t alignment, size_t page_size,4154char* req_addr, bool exec) {4155assert(UseLargePages, "only for large pages");41564157char* addr;4158if (UseSHM) {4159// No support for using specific page sizes with SHM.4160addr = os::Linux::reserve_memory_special_shm(bytes, alignment, req_addr, exec);4161} else {4162assert(UseHugeTLBFS, "must be");4163addr = os::Linux::reserve_memory_special_huge_tlbfs(bytes, alignment, page_size, req_addr, exec);4164}41654166if (addr != NULL) {4167if (UseNUMAInterleaving) {4168numa_make_global(addr, bytes);4169}4170}41714172return addr;4173}41744175bool os::Linux::release_memory_special_shm(char* base, size_t bytes) {4176// detaching the SHM segment will also delete it, see reserve_memory_special_shm()4177return shmdt(base) == 0;4178}41794180bool os::Linux::release_memory_special_huge_tlbfs(char* base, size_t bytes) {4181return pd_release_memory(base, bytes);4182}41834184bool os::pd_release_memory_special(char* base, size_t bytes) {4185assert(UseLargePages, "only for large pages");4186bool res;41874188if (UseSHM) {4189res = os::Linux::release_memory_special_shm(base, bytes);4190} else {4191assert(UseHugeTLBFS, "must be");4192res = os::Linux::release_memory_special_huge_tlbfs(base, bytes);4193}4194return res;4195}41964197size_t os::large_page_size() {4198return _large_page_size;4199}42004201// With SysV SHM the entire memory region must be allocated as shared4202// memory.4203// HugeTLBFS allows application to commit large page memory on demand.4204// However, when committing memory with HugeTLBFS fails, the region4205// that was supposed to be committed will lose the old reservation4206// and allow other threads to steal that memory region. Because of this4207// behavior we can't commit HugeTLBFS memory.4208bool os::can_commit_large_page_memory() {4209return UseTransparentHugePages;4210}42114212bool os::can_execute_large_page_memory() {4213return UseTransparentHugePages || UseHugeTLBFS;4214}42154216char* os::pd_attempt_map_memory_to_file_at(char* requested_addr, size_t bytes, int file_desc) {4217assert(file_desc >= 0, "file_desc is not valid");4218char* result = pd_attempt_reserve_memory_at(requested_addr, bytes, !ExecMem);4219if (result != NULL) {4220if (replace_existing_mapping_with_file_mapping(result, bytes, file_desc) == NULL) {4221vm_exit_during_initialization(err_msg("Error in mapping Java heap at the given filesystem directory"));4222}4223}4224return result;4225}42264227// Reserve memory at an arbitrary address, only if that area is4228// available (and not reserved for something else).42294230char* os::pd_attempt_reserve_memory_at(char* requested_addr, size_t bytes, bool exec) {4231// Assert only that the size is a multiple of the page size, since4232// that's all that mmap requires, and since that's all we really know4233// about at this low abstraction level. If we need higher alignment,4234// we can either pass an alignment to this method or verify alignment4235// in one of the methods further up the call chain. See bug 5044738.4236assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");42374238// Repeatedly allocate blocks until the block is allocated at the4239// right spot.42404241// Linux mmap allows caller to pass an address as hint; give it a try first,4242// if kernel honors the hint then we can return immediately.4243char * addr = anon_mmap(requested_addr, bytes);4244if (addr == requested_addr) {4245return requested_addr;4246}42474248if (addr != NULL) {4249// mmap() is successful but it fails to reserve at the requested address4250anon_munmap(addr, bytes);4251}42524253return NULL;4254}42554256// Used to convert frequent JVM_Yield() to nops4257bool os::dont_yield() {4258return DontYieldALot;4259}42604261// Linux CFS scheduler (since 2.6.23) does not guarantee sched_yield(2) will4262// actually give up the CPU. Since skip buddy (v2.6.28):4263//4264// * Sets the yielding task as skip buddy for current CPU's run queue.4265// * Picks next from run queue, if empty, picks a skip buddy (can be the yielding task).4266// * Clears skip buddies for this run queue (yielding task no longer a skip buddy).4267//4268// An alternative is calling os::naked_short_nanosleep with a small number to avoid4269// getting re-scheduled immediately.4270//4271void os::naked_yield() {4272sched_yield();4273}42744275////////////////////////////////////////////////////////////////////////////////4276// thread priority support42774278// Note: Normal Linux applications are run with SCHED_OTHER policy. SCHED_OTHER4279// only supports dynamic priority, static priority must be zero. For real-time4280// applications, Linux supports SCHED_RR which allows static priority (1-99).4281// However, for large multi-threaded applications, SCHED_RR is not only slower4282// than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out4283// of 5 runs - Sep 2005).4284//4285// The following code actually changes the niceness of kernel-thread/LWP. It4286// has an assumption that setpriority() only modifies one kernel-thread/LWP,4287// not the entire user process, and user level threads are 1:1 mapped to kernel4288// threads. It has always been the case, but could change in the future. For4289// this reason, the code should not be used as default (ThreadPriorityPolicy=0).4290// It is only used when ThreadPriorityPolicy=1 and may require system level permission4291// (e.g., root privilege or CAP_SYS_NICE capability).42924293int os::java_to_os_priority[CriticalPriority + 1] = {429419, // 0 Entry should never be used429542964, // 1 MinPriority42973, // 242982, // 3429943001, // 443010, // 5 NormPriority4302-1, // 643034304-2, // 74305-3, // 84306-4, // 9 NearMaxPriority43074308-5, // 10 MaxPriority43094310-5 // 11 CriticalPriority4311};43124313static int prio_init() {4314if (ThreadPriorityPolicy == 1) {4315if (geteuid() != 0) {4316if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy) && !FLAG_IS_JIMAGE_RESOURCE(ThreadPriorityPolicy)) {4317warning("-XX:ThreadPriorityPolicy=1 may require system level permission, " \4318"e.g., being the root user. If the necessary permission is not " \4319"possessed, changes to priority will be silently ignored.");4320}4321}4322}4323if (UseCriticalJavaThreadPriority) {4324os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority];4325}4326return 0;4327}43284329OSReturn os::set_native_priority(Thread* thread, int newpri) {4330if (!UseThreadPriorities || ThreadPriorityPolicy == 0) return OS_OK;43314332int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri);4333return (ret == 0) ? OS_OK : OS_ERR;4334}43354336OSReturn os::get_native_priority(const Thread* const thread,4337int *priority_ptr) {4338if (!UseThreadPriorities || ThreadPriorityPolicy == 0) {4339*priority_ptr = java_to_os_priority[NormPriority];4340return OS_OK;4341}43424343errno = 0;4344*priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id());4345return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR);4346}43474348// This is the fastest way to get thread cpu time on Linux.4349// Returns cpu time (user+sys) for any thread, not only for current.4350// POSIX compliant clocks are implemented in the kernels 2.6.16+.4351// It might work on 2.6.10+ with a special kernel/glibc patch.4352// For reference, please, see IEEE Std 1003.1-2004:4353// http://www.unix.org/single_unix_specification43544355jlong os::Linux::fast_thread_cpu_time(clockid_t clockid) {4356struct timespec tp;4357int status = clock_gettime(clockid, &tp);4358assert(status == 0, "clock_gettime error: %s", os::strerror(errno));4359return (tp.tv_sec * NANOSECS_PER_SEC) + tp.tv_nsec;4360}43614362// Determine if the vmid is the parent pid for a child in a PID namespace.4363// Return the namespace pid if so, otherwise -1.4364int os::Linux::get_namespace_pid(int vmid) {4365char fname[24];4366int retpid = -1;43674368snprintf(fname, sizeof(fname), "/proc/%d/status", vmid);4369FILE *fp = fopen(fname, "r");43704371if (fp) {4372int pid, nspid;4373int ret;4374while (!feof(fp) && !ferror(fp)) {4375ret = fscanf(fp, "NSpid: %d %d", &pid, &nspid);4376if (ret == 1) {4377break;4378}4379if (ret == 2) {4380retpid = nspid;4381break;4382}4383for (;;) {4384int ch = fgetc(fp);4385if (ch == EOF || ch == (int)'\n') break;4386}4387}4388fclose(fp);4389}4390return retpid;4391}43924393extern void report_error(char* file_name, int line_no, char* title,4394char* format, ...);43954396// Some linux distributions (notably: Alpine Linux) include the4397// grsecurity in the kernel. Of particular interest from a JVM perspective4398// is PaX (https://pax.grsecurity.net/), which adds some security features4399// related to page attributes. Specifically, the MPROTECT PaX functionality4400// (https://pax.grsecurity.net/docs/mprotect.txt) prevents dynamic4401// code generation by disallowing a (previously) writable page to be4402// marked as executable. This is, of course, exactly what HotSpot does4403// for both JIT compiled method, as well as for stubs, adapters, etc.4404//4405// Instead of crashing "lazily" when trying to make a page executable,4406// this code probes for the presence of PaX and reports the failure4407// eagerly.4408static void check_pax(void) {4409// Zero doesn't generate code dynamically, so no need to perform the PaX check4410#ifndef ZERO4411size_t size = os::Linux::page_size();44124413void* p = ::mmap(NULL, size, PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);4414if (p == MAP_FAILED) {4415log_debug(os)("os_linux.cpp: check_pax: mmap failed (%s)" , os::strerror(errno));4416vm_exit_out_of_memory(size, OOM_MMAP_ERROR, "failed to allocate memory for PaX check.");4417}44184419int res = ::mprotect(p, size, PROT_WRITE|PROT_EXEC);4420if (res == -1) {4421log_debug(os)("os_linux.cpp: check_pax: mprotect failed (%s)" , os::strerror(errno));4422vm_exit_during_initialization(4423"Failed to mark memory page as executable - check if grsecurity/PaX is enabled");4424}44254426::munmap(p, size);4427#endif4428}44294430// this is called _before_ most of the global arguments have been parsed4431void os::init(void) {4432char dummy; // used to get a guess on initial stack address44334434clock_tics_per_sec = sysconf(_SC_CLK_TCK);44354436Linux::set_page_size(sysconf(_SC_PAGESIZE));4437if (Linux::page_size() == -1) {4438fatal("os_linux.cpp: os::init: sysconf failed (%s)",4439os::strerror(errno));4440}4441_page_sizes.add(Linux::page_size());44424443Linux::initialize_system_info();44444445#ifdef __GLIBC__4446Linux::_mallinfo = CAST_TO_FN_PTR(Linux::mallinfo_func_t, dlsym(RTLD_DEFAULT, "mallinfo"));4447Linux::_mallinfo2 = CAST_TO_FN_PTR(Linux::mallinfo2_func_t, dlsym(RTLD_DEFAULT, "mallinfo2"));4448#endif // __GLIBC__44494450os::Linux::CPUPerfTicks pticks;4451bool res = os::Linux::get_tick_information(&pticks, -1);44524453if (res && pticks.has_steal_ticks) {4454has_initial_tick_info = true;4455initial_total_ticks = pticks.total;4456initial_steal_ticks = pticks.steal;4457}44584459// _main_thread points to the thread that created/loaded the JVM.4460Linux::_main_thread = pthread_self();44614462// retrieve entry point for pthread_setname_np4463Linux::_pthread_setname_np =4464(int(*)(pthread_t, const char*))dlsym(RTLD_DEFAULT, "pthread_setname_np");44654466check_pax();44674468os::Posix::init();44694470initial_time_count = javaTimeNanos();4471}44724473// To install functions for atexit system call4474extern "C" {4475static void perfMemory_exit_helper() {4476perfMemory_exit();4477}4478}44794480void os::pd_init_container_support() {4481OSContainer::init();4482}44834484void os::Linux::numa_init() {44854486// Java can be invoked as4487// 1. Without numactl and heap will be allocated/configured on all nodes as4488// per the system policy.4489// 2. With numactl --interleave:4490// Use numa_get_interleave_mask(v2) API to get nodes bitmask. The same4491// API for membind case bitmask is reset.4492// Interleave is only hint and Kernel can fallback to other nodes if4493// no memory is available on the target nodes.4494// 3. With numactl --membind:4495// Use numa_get_membind(v2) API to get nodes bitmask. The same API for4496// interleave case returns bitmask of all nodes.4497// numa_all_nodes_ptr holds bitmask of all nodes.4498// numa_get_interleave_mask(v2) and numa_get_membind(v2) APIs returns correct4499// bitmask when externally configured to run on all or fewer nodes.45004501if (!Linux::libnuma_init()) {4502FLAG_SET_ERGO(UseNUMA, false);4503FLAG_SET_ERGO(UseNUMAInterleaving, false); // Also depends on libnuma.4504} else {4505if ((Linux::numa_max_node() < 1) || Linux::is_bound_to_single_node()) {4506// If there's only one node (they start from 0) or if the process4507// is bound explicitly to a single node using membind, disable NUMA4508UseNUMA = false;4509} else {4510LogTarget(Info,os) log;4511LogStream ls(log);45124513Linux::set_configured_numa_policy(Linux::identify_numa_policy());45144515struct bitmask* bmp = Linux::_numa_membind_bitmask;4516const char* numa_mode = "membind";45174518if (Linux::is_running_in_interleave_mode()) {4519bmp = Linux::_numa_interleave_bitmask;4520numa_mode = "interleave";4521}45224523ls.print("UseNUMA is enabled and invoked in '%s' mode."4524" Heap will be configured using NUMA memory nodes:", numa_mode);45254526for (int node = 0; node <= Linux::numa_max_node(); node++) {4527if (Linux::_numa_bitmask_isbitset(bmp, node)) {4528ls.print(" %d", node);4529}4530}4531}4532}45334534// When NUMA requested, not-NUMA-aware allocations default to interleaving.4535if (UseNUMA && !UseNUMAInterleaving) {4536FLAG_SET_ERGO_IF_DEFAULT(UseNUMAInterleaving, true);4537}45384539if (UseParallelGC && UseNUMA && UseLargePages && !can_commit_large_page_memory()) {4540// With SHM and HugeTLBFS large pages we cannot uncommit a page, so there's no way4541// we can make the adaptive lgrp chunk resizing work. If the user specified both4542// UseNUMA and UseLargePages (or UseSHM/UseHugeTLBFS) on the command line - warn4543// and disable adaptive resizing.4544if (UseAdaptiveSizePolicy || UseAdaptiveNUMAChunkSizing) {4545warning("UseNUMA is not fully compatible with SHM/HugeTLBFS large pages, "4546"disabling adaptive resizing (-XX:-UseAdaptiveSizePolicy -XX:-UseAdaptiveNUMAChunkSizing)");4547UseAdaptiveSizePolicy = false;4548UseAdaptiveNUMAChunkSizing = false;4549}4550}4551}45524553// this is called _after_ the global arguments have been parsed4554jint os::init_2(void) {45554556// This could be set after os::Posix::init() but all platforms4557// have to set it the same so we have to mirror Solaris.4558DEBUG_ONLY(os::set_mutex_init_done();)45594560os::Posix::init_2();45614562Linux::fast_thread_clock_init();45634564if (PosixSignals::init() == JNI_ERR) {4565return JNI_ERR;4566}45674568if (AdjustStackSizeForTLS) {4569get_minstack_init();4570}45714572// Check and sets minimum stack sizes against command line options4573if (Posix::set_minimum_stack_sizes() == JNI_ERR) {4574return JNI_ERR;4575}45764577#if defined(IA32) && !defined(ZERO)4578// Need to ensure we've determined the process's initial stack to4579// perform the workaround4580Linux::capture_initial_stack(JavaThread::stack_size_at_create());4581workaround_expand_exec_shield_cs_limit();4582#else4583suppress_primordial_thread_resolution = Arguments::created_by_java_launcher();4584if (!suppress_primordial_thread_resolution) {4585Linux::capture_initial_stack(JavaThread::stack_size_at_create());4586}4587#endif45884589Linux::libpthread_init();4590Linux::sched_getcpu_init();4591log_info(os)("HotSpot is running with %s, %s",4592Linux::libc_version(), Linux::libpthread_version());45934594if (UseNUMA || UseNUMAInterleaving) {4595Linux::numa_init();4596}45974598if (MaxFDLimit) {4599// set the number of file descriptors to max. print out error4600// if getrlimit/setrlimit fails but continue regardless.4601struct rlimit nbr_files;4602int status = getrlimit(RLIMIT_NOFILE, &nbr_files);4603if (status != 0) {4604log_info(os)("os::init_2 getrlimit failed: %s", os::strerror(errno));4605} else {4606nbr_files.rlim_cur = nbr_files.rlim_max;4607status = setrlimit(RLIMIT_NOFILE, &nbr_files);4608if (status != 0) {4609log_info(os)("os::init_2 setrlimit failed: %s", os::strerror(errno));4610}4611}4612}46134614// at-exit methods are called in the reverse order of their registration.4615// atexit functions are called on return from main or as a result of a4616// call to exit(3C). There can be only 32 of these functions registered4617// and atexit() does not set errno.46184619if (PerfAllowAtExitRegistration) {4620// only register atexit functions if PerfAllowAtExitRegistration is set.4621// atexit functions can be delayed until process exit time, which4622// can be problematic for embedded VM situations. Embedded VMs should4623// call DestroyJavaVM() to assure that VM resources are released.46244625// note: perfMemory_exit_helper atexit function may be removed in4626// the future if the appropriate cleanup code can be added to the4627// VM_Exit VMOperation's doit method.4628if (atexit(perfMemory_exit_helper) != 0) {4629warning("os::init_2 atexit(perfMemory_exit_helper) failed");4630}4631}46324633// initialize thread priority policy4634prio_init();46354636if (!FLAG_IS_DEFAULT(AllocateHeapAt)) {4637set_coredump_filter(DAX_SHARED_BIT);4638}46394640if (DumpPrivateMappingsInCore) {4641set_coredump_filter(FILE_BACKED_PVT_BIT);4642}46434644if (DumpSharedMappingsInCore) {4645set_coredump_filter(FILE_BACKED_SHARED_BIT);4646}46474648if (DumpPerfMapAtExit && FLAG_IS_DEFAULT(UseCodeCacheFlushing)) {4649// Disable code cache flushing to ensure the map file written at4650// exit contains all nmethods generated during execution.4651FLAG_SET_DEFAULT(UseCodeCacheFlushing, false);4652}46534654return JNI_OK;4655}46564657// older glibc versions don't have this macro (which expands to4658// an optimized bit-counting function) so we have to roll our own4659#ifndef CPU_COUNT46604661static int _cpu_count(const cpu_set_t* cpus) {4662int count = 0;4663// only look up to the number of configured processors4664for (int i = 0; i < os::processor_count(); i++) {4665if (CPU_ISSET(i, cpus)) {4666count++;4667}4668}4669return count;4670}46714672#define CPU_COUNT(cpus) _cpu_count(cpus)46734674#endif // CPU_COUNT46754676// Get the current number of available processors for this process.4677// This value can change at any time during a process's lifetime.4678// sched_getaffinity gives an accurate answer as it accounts for cpusets.4679// If it appears there may be more than 1024 processors then we do a4680// dynamic check - see 6515172 for details.4681// If anything goes wrong we fallback to returning the number of online4682// processors - which can be greater than the number available to the process.4683static int get_active_processor_count() {4684// Note: keep this function, with its CPU_xx macros, *outside* the os namespace (see JDK-8289477).4685cpu_set_t cpus; // can represent at most 1024 (CPU_SETSIZE) processors4686cpu_set_t* cpus_p = &cpus;4687int cpus_size = sizeof(cpu_set_t);46884689int configured_cpus = os::processor_count(); // upper bound on available cpus4690int cpu_count = 0;46914692// old build platforms may not support dynamic cpu sets4693#ifdef CPU_ALLOC46944695// To enable easy testing of the dynamic path on different platforms we4696// introduce a diagnostic flag: UseCpuAllocPath4697if (configured_cpus >= CPU_SETSIZE || UseCpuAllocPath) {4698// kernel may use a mask bigger than cpu_set_t4699log_trace(os)("active_processor_count: using dynamic path %s"4700"- configured processors: %d",4701UseCpuAllocPath ? "(forced) " : "",4702configured_cpus);4703cpus_p = CPU_ALLOC(configured_cpus);4704if (cpus_p != NULL) {4705cpus_size = CPU_ALLOC_SIZE(configured_cpus);4706// zero it just to be safe4707CPU_ZERO_S(cpus_size, cpus_p);4708}4709else {4710// failed to allocate so fallback to online cpus4711int online_cpus = ::sysconf(_SC_NPROCESSORS_ONLN);4712log_trace(os)("active_processor_count: "4713"CPU_ALLOC failed (%s) - using "4714"online processor count: %d",4715os::strerror(errno), online_cpus);4716return online_cpus;4717}4718}4719else {4720log_trace(os)("active_processor_count: using static path - configured processors: %d",4721configured_cpus);4722}4723#else // CPU_ALLOC4724// these stubs won't be executed4725#define CPU_COUNT_S(size, cpus) -14726#define CPU_FREE(cpus)47274728log_trace(os)("active_processor_count: only static path available - configured processors: %d",4729configured_cpus);4730#endif // CPU_ALLOC47314732// pid 0 means the current thread - which we have to assume represents the process4733if (sched_getaffinity(0, cpus_size, cpus_p) == 0) {4734if (cpus_p != &cpus) { // can only be true when CPU_ALLOC used4735cpu_count = CPU_COUNT_S(cpus_size, cpus_p);4736}4737else {4738cpu_count = CPU_COUNT(cpus_p);4739}4740log_trace(os)("active_processor_count: sched_getaffinity processor count: %d", cpu_count);4741}4742else {4743cpu_count = ::sysconf(_SC_NPROCESSORS_ONLN);4744warning("sched_getaffinity failed (%s)- using online processor count (%d) "4745"which may exceed available processors", os::strerror(errno), cpu_count);4746}47474748if (cpus_p != &cpus) { // can only be true when CPU_ALLOC used4749CPU_FREE(cpus_p);4750}47514752assert(cpu_count > 0 && cpu_count <= os::processor_count(), "sanity check");4753return cpu_count;4754}47554756int os::Linux::active_processor_count() {4757return get_active_processor_count();4758}47594760// Determine the active processor count from one of4761// three different sources:4762//4763// 1. User option -XX:ActiveProcessorCount4764// 2. kernel os calls (sched_getaffinity or sysconf(_SC_NPROCESSORS_ONLN)4765// 3. extracted from cgroup cpu subsystem (shares and quotas)4766//4767// Option 1, if specified, will always override.4768// If the cgroup subsystem is active and configured, we4769// will return the min of the cgroup and option 2 results.4770// This is required since tools, such as numactl, that4771// alter cpu affinity do not update cgroup subsystem4772// cpuset configuration files.4773int os::active_processor_count() {4774// User has overridden the number of active processors4775if (ActiveProcessorCount > 0) {4776log_trace(os)("active_processor_count: "4777"active processor count set by user : %d",4778ActiveProcessorCount);4779return ActiveProcessorCount;4780}47814782int active_cpus;4783if (OSContainer::is_containerized()) {4784active_cpus = OSContainer::active_processor_count();4785log_trace(os)("active_processor_count: determined by OSContainer: %d",4786active_cpus);4787} else {4788active_cpus = os::Linux::active_processor_count();4789}47904791return active_cpus;4792}47934794static bool should_warn_invalid_processor_id() {4795if (os::processor_count() == 1) {4796// Don't warn if we only have one processor4797return false;4798}47994800static volatile int warn_once = 1;48014802if (Atomic::load(&warn_once) == 0 ||4803Atomic::xchg(&warn_once, 0) == 0) {4804// Don't warn more than once4805return false;4806}48074808return true;4809}48104811uint os::processor_id() {4812const int id = Linux::sched_getcpu();48134814if (id < processor_count()) {4815return (uint)id;4816}48174818// Some environments (e.g. openvz containers and the rr debugger) incorrectly4819// report a processor id that is higher than the number of processors available.4820// This is problematic, for example, when implementing CPU-local data structures,4821// where the processor id is used to index into an array of length processor_count().4822// If this happens we return 0 here. This is is safe since we always have at least4823// one processor, but it's not optimal for performance if we're actually executing4824// in an environment with more than one processor.4825if (should_warn_invalid_processor_id()) {4826log_warning(os)("Invalid processor id reported by the operating system "4827"(got processor id %d, valid processor id range is 0-%d)",4828id, processor_count() - 1);4829log_warning(os)("Falling back to assuming processor id is 0. "4830"This could have a negative impact on performance.");4831}48324833return 0;4834}48354836void os::set_native_thread_name(const char *name) {4837if (Linux::_pthread_setname_np) {4838char buf [16]; // according to glibc manpage, 16 chars incl. '/0'4839snprintf(buf, sizeof(buf), "%s", name);4840buf[sizeof(buf) - 1] = '\0';4841const int rc = Linux::_pthread_setname_np(pthread_self(), buf);4842// ERANGE should not happen; all other errors should just be ignored.4843assert(rc != ERANGE, "pthread_setname_np failed");4844}4845}48464847bool os::bind_to_processor(uint processor_id) {4848// Not yet implemented.4849return false;4850}48514852////////////////////////////////////////////////////////////////////////////////4853// debug support48544855bool os::find(address addr, outputStream* st) {4856Dl_info dlinfo;4857memset(&dlinfo, 0, sizeof(dlinfo));4858if (dladdr(addr, &dlinfo) != 0) {4859st->print(PTR_FORMAT ": ", p2i(addr));4860if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) {4861st->print("%s+" PTR_FORMAT, dlinfo.dli_sname,4862p2i(addr) - p2i(dlinfo.dli_saddr));4863} else if (dlinfo.dli_fbase != NULL) {4864st->print("<offset " PTR_FORMAT ">", p2i(addr) - p2i(dlinfo.dli_fbase));4865} else {4866st->print("<absolute address>");4867}4868if (dlinfo.dli_fname != NULL) {4869st->print(" in %s", dlinfo.dli_fname);4870}4871if (dlinfo.dli_fbase != NULL) {4872st->print(" at " PTR_FORMAT, p2i(dlinfo.dli_fbase));4873}4874st->cr();48754876if (Verbose) {4877// decode some bytes around the PC4878address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size());4879address end = clamp_address_in_page(addr+40, addr, os::vm_page_size());4880address lowest = (address) dlinfo.dli_sname;4881if (!lowest) lowest = (address) dlinfo.dli_fbase;4882if (begin < lowest) begin = lowest;4883Dl_info dlinfo2;4884if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr4885&& end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin) {4886end = (address) dlinfo2.dli_saddr;4887}4888Disassembler::decode(begin, end, st);4889}4890return true;4891}4892return false;4893}48944895////////////////////////////////////////////////////////////////////////////////4896// misc48974898// This does not do anything on Linux. This is basically a hook for being4899// able to use structured exception handling (thread-local exception filters)4900// on, e.g., Win32.4901void4902os::os_exception_wrapper(java_call_t f, JavaValue* value, const methodHandle& method,4903JavaCallArguments* args, JavaThread* thread) {4904f(value, method, args, thread);4905}49064907void os::print_statistics() {4908}49094910bool os::message_box(const char* title, const char* message) {4911int i;4912fdStream err(defaultStream::error_fd());4913for (i = 0; i < 78; i++) err.print_raw("=");4914err.cr();4915err.print_raw_cr(title);4916for (i = 0; i < 78; i++) err.print_raw("-");4917err.cr();4918err.print_raw_cr(message);4919for (i = 0; i < 78; i++) err.print_raw("=");4920err.cr();49214922char buf[16];4923// Prevent process from exiting upon "read error" without consuming all CPU4924while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }49254926return buf[0] == 'y' || buf[0] == 'Y';4927}49284929// This code originates from JDK's sysOpen and open64_w4930// from src/solaris/hpi/src/system_md.c49314932int os::open(const char *path, int oflag, int mode) {4933if (strlen(path) > MAX_PATH - 1) {4934errno = ENAMETOOLONG;4935return -1;4936}49374938// All file descriptors that are opened in the Java process and not4939// specifically destined for a subprocess should have the close-on-exec4940// flag set. If we don't set it, then careless 3rd party native code4941// might fork and exec without closing all appropriate file descriptors4942// (e.g. as we do in closeDescriptors in UNIXProcess.c), and this in4943// turn might:4944//4945// - cause end-of-file to fail to be detected on some file4946// descriptors, resulting in mysterious hangs, or4947//4948// - might cause an fopen in the subprocess to fail on a system4949// suffering from bug 1085341.4950//4951// (Yes, the default setting of the close-on-exec flag is a Unix4952// design flaw)4953//4954// See:4955// 1085341: 32-bit stdio routines should support file descriptors >2554956// 4843136: (process) pipe file descriptor from Runtime.exec not being closed4957// 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 94958//4959// Modern Linux kernels (after 2.6.23 2007) support O_CLOEXEC with open().4960// O_CLOEXEC is preferable to using FD_CLOEXEC on an open file descriptor4961// because it saves a system call and removes a small window where the flag4962// is unset. On ancient Linux kernels the O_CLOEXEC flag will be ignored4963// and we fall back to using FD_CLOEXEC (see below).4964#ifdef O_CLOEXEC4965oflag |= O_CLOEXEC;4966#endif49674968int fd = ::open64(path, oflag, mode);4969if (fd == -1) return -1;49704971//If the open succeeded, the file might still be a directory4972{4973struct stat64 buf64;4974int ret = ::fstat64(fd, &buf64);4975int st_mode = buf64.st_mode;49764977if (ret != -1) {4978if ((st_mode & S_IFMT) == S_IFDIR) {4979errno = EISDIR;4980::close(fd);4981return -1;4982}4983} else {4984::close(fd);4985return -1;4986}4987}49884989#ifdef FD_CLOEXEC4990// Validate that the use of the O_CLOEXEC flag on open above worked.4991// With recent kernels, we will perform this check exactly once.4992static sig_atomic_t O_CLOEXEC_is_known_to_work = 0;4993if (!O_CLOEXEC_is_known_to_work) {4994int flags = ::fcntl(fd, F_GETFD);4995if (flags != -1) {4996if ((flags & FD_CLOEXEC) != 0)4997O_CLOEXEC_is_known_to_work = 1;4998else4999::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);5000}5001}5002#endif50035004return fd;5005}500650075008// create binary file, rewriting existing file if required5009int os::create_binary_file(const char* path, bool rewrite_existing) {5010int oflags = O_WRONLY | O_CREAT;5011oflags |= rewrite_existing ? O_TRUNC : O_EXCL;5012return ::open64(path, oflags, S_IREAD | S_IWRITE);5013}50145015// return current position of file pointer5016jlong os::current_file_offset(int fd) {5017return (jlong)::lseek64(fd, (off64_t)0, SEEK_CUR);5018}50195020// move file pointer to the specified offset5021jlong os::seek_to_file_offset(int fd, jlong offset) {5022return (jlong)::lseek64(fd, (off64_t)offset, SEEK_SET);5023}50245025// This code originates from JDK's sysAvailable5026// from src/solaris/hpi/src/native_threads/src/sys_api_td.c50275028int os::available(int fd, jlong *bytes) {5029jlong cur, end;5030int mode;5031struct stat64 buf64;50325033if (::fstat64(fd, &buf64) >= 0) {5034mode = buf64.st_mode;5035if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {5036int n;5037if (::ioctl(fd, FIONREAD, &n) >= 0) {5038*bytes = n;5039return 1;5040}5041}5042}5043if ((cur = ::lseek64(fd, 0L, SEEK_CUR)) == -1) {5044return 0;5045} else if ((end = ::lseek64(fd, 0L, SEEK_END)) == -1) {5046return 0;5047} else if (::lseek64(fd, cur, SEEK_SET) == -1) {5048return 0;5049}5050*bytes = end - cur;5051return 1;5052}50535054// Map a block of memory.5055char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,5056char *addr, size_t bytes, bool read_only,5057bool allow_exec) {5058int prot;5059int flags = MAP_PRIVATE;50605061if (read_only) {5062prot = PROT_READ;5063} else {5064prot = PROT_READ | PROT_WRITE;5065}50665067if (allow_exec) {5068prot |= PROT_EXEC;5069}50705071if (addr != NULL) {5072flags |= MAP_FIXED;5073}50745075char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,5076fd, file_offset);5077if (mapped_address == MAP_FAILED) {5078return NULL;5079}5080return mapped_address;5081}508250835084// Remap a block of memory.5085char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,5086char *addr, size_t bytes, bool read_only,5087bool allow_exec) {5088// same as map_memory() on this OS5089return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,5090allow_exec);5091}509250935094// Unmap a block of memory.5095bool os::pd_unmap_memory(char* addr, size_t bytes) {5096return munmap(addr, bytes) == 0;5097}50985099static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time);51005101static jlong fast_cpu_time(Thread *thread) {5102clockid_t clockid;5103int rc = os::Linux::pthread_getcpuclockid(thread->osthread()->pthread_id(),5104&clockid);5105if (rc == 0) {5106return os::Linux::fast_thread_cpu_time(clockid);5107} else {5108// It's possible to encounter a terminated native thread that failed5109// to detach itself from the VM - which should result in ESRCH.5110assert_status(rc == ESRCH, rc, "pthread_getcpuclockid failed");5111return -1;5112}5113}51145115// current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)5116// are used by JVM M&M and JVMTI to get user+sys or user CPU time5117// of a thread.5118//5119// current_thread_cpu_time() and thread_cpu_time(Thread*) returns5120// the fast estimate available on the platform.51215122jlong os::current_thread_cpu_time() {5123if (os::Linux::supports_fast_thread_cpu_time()) {5124return os::Linux::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID);5125} else {5126// return user + sys since the cost is the same5127return slow_thread_cpu_time(Thread::current(), true /* user + sys */);5128}5129}51305131jlong os::thread_cpu_time(Thread* thread) {5132// consistent with what current_thread_cpu_time() returns5133if (os::Linux::supports_fast_thread_cpu_time()) {5134return fast_cpu_time(thread);5135} else {5136return slow_thread_cpu_time(thread, true /* user + sys */);5137}5138}51395140jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {5141if (user_sys_cpu_time && os::Linux::supports_fast_thread_cpu_time()) {5142return os::Linux::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID);5143} else {5144return slow_thread_cpu_time(Thread::current(), user_sys_cpu_time);5145}5146}51475148jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {5149if (user_sys_cpu_time && os::Linux::supports_fast_thread_cpu_time()) {5150return fast_cpu_time(thread);5151} else {5152return slow_thread_cpu_time(thread, user_sys_cpu_time);5153}5154}51555156// -1 on error.5157static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {5158pid_t tid = thread->osthread()->thread_id();5159char *s;5160char stat[2048];5161int statlen;5162char proc_name[64];5163int count;5164long sys_time, user_time;5165char cdummy;5166int idummy;5167long ldummy;5168FILE *fp;51695170snprintf(proc_name, 64, "/proc/self/task/%d/stat", tid);5171fp = fopen(proc_name, "r");5172if (fp == NULL) return -1;5173statlen = fread(stat, 1, 2047, fp);5174stat[statlen] = '\0';5175fclose(fp);51765177// Skip pid and the command string. Note that we could be dealing with5178// weird command names, e.g. user could decide to rename java launcher5179// to "java 1.4.2 :)", then the stat file would look like5180// 1234 (java 1.4.2 :)) R ... ...5181// We don't really need to know the command string, just find the last5182// occurrence of ")" and then start parsing from there. See bug 4726580.5183s = strrchr(stat, ')');5184if (s == NULL) return -1;51855186// Skip blank chars5187do { s++; } while (s && isspace(*s));51885189count = sscanf(s,"%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu",5190&cdummy, &idummy, &idummy, &idummy, &idummy, &idummy,5191&ldummy, &ldummy, &ldummy, &ldummy, &ldummy,5192&user_time, &sys_time);5193if (count != 13) return -1;5194if (user_sys_cpu_time) {5195return ((jlong)sys_time + (jlong)user_time) * (1000000000 / clock_tics_per_sec);5196} else {5197return (jlong)user_time * (1000000000 / clock_tics_per_sec);5198}5199}52005201void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {5202info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits5203info_ptr->may_skip_backward = false; // elapsed time not wall time5204info_ptr->may_skip_forward = false; // elapsed time not wall time5205info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned5206}52075208void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {5209info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits5210info_ptr->may_skip_backward = false; // elapsed time not wall time5211info_ptr->may_skip_forward = false; // elapsed time not wall time5212info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned5213}52145215bool os::is_thread_cpu_time_supported() {5216return true;5217}52185219// System loadavg support. Returns -1 if load average cannot be obtained.5220// Linux doesn't yet have a (official) notion of processor sets,5221// so just return the system wide load average.5222int os::loadavg(double loadavg[], int nelem) {5223return ::getloadavg(loadavg, nelem);5224}52255226void os::pause() {5227char filename[MAX_PATH];5228if (PauseAtStartupFile && PauseAtStartupFile[0]) {5229jio_snprintf(filename, MAX_PATH, "%s", PauseAtStartupFile);5230} else {5231jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());5232}52335234int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);5235if (fd != -1) {5236struct stat buf;5237::close(fd);5238while (::stat(filename, &buf) == 0) {5239(void)::poll(NULL, 0, 100);5240}5241} else {5242jio_fprintf(stderr,5243"Could not open pause file '%s', continuing immediately.\n", filename);5244}5245}52465247// Get the default path to the core file5248// Returns the length of the string5249int os::get_core_path(char* buffer, size_t bufferSize) {5250/*5251* Max length of /proc/sys/kernel/core_pattern is 128 characters.5252* See https://www.kernel.org/doc/Documentation/sysctl/kernel.txt5253*/5254const int core_pattern_len = 129;5255char core_pattern[core_pattern_len] = {0};52565257int core_pattern_file = ::open("/proc/sys/kernel/core_pattern", O_RDONLY);5258if (core_pattern_file == -1) {5259return -1;5260}52615262ssize_t ret = ::read(core_pattern_file, core_pattern, core_pattern_len);5263::close(core_pattern_file);5264if (ret <= 0 || ret >= core_pattern_len || core_pattern[0] == '\n') {5265return -1;5266}5267if (core_pattern[ret-1] == '\n') {5268core_pattern[ret-1] = '\0';5269} else {5270core_pattern[ret] = '\0';5271}52725273// Replace the %p in the core pattern with the process id. NOTE: we do this5274// only if the pattern doesn't start with "|", and we support only one %p in5275// the pattern.5276char *pid_pos = strstr(core_pattern, "%p");5277const char* tail = (pid_pos != NULL) ? (pid_pos + 2) : ""; // skip over the "%p"5278int written;52795280if (core_pattern[0] == '/') {5281if (pid_pos != NULL) {5282*pid_pos = '\0';5283written = jio_snprintf(buffer, bufferSize, "%s%d%s", core_pattern,5284current_process_id(), tail);5285} else {5286written = jio_snprintf(buffer, bufferSize, "%s", core_pattern);5287}5288} else {5289char cwd[PATH_MAX];52905291const char* p = get_current_directory(cwd, PATH_MAX);5292if (p == NULL) {5293return -1;5294}52955296if (core_pattern[0] == '|') {5297written = jio_snprintf(buffer, bufferSize,5298"\"%s\" (or dumping to %s/core.%d)",5299&core_pattern[1], p, current_process_id());5300} else if (pid_pos != NULL) {5301*pid_pos = '\0';5302written = jio_snprintf(buffer, bufferSize, "%s/%s%d%s", p, core_pattern,5303current_process_id(), tail);5304} else {5305written = jio_snprintf(buffer, bufferSize, "%s/%s", p, core_pattern);5306}5307}53085309if (written < 0) {5310return -1;5311}53125313if (((size_t)written < bufferSize) && (pid_pos == NULL) && (core_pattern[0] != '|')) {5314int core_uses_pid_file = ::open("/proc/sys/kernel/core_uses_pid", O_RDONLY);53155316if (core_uses_pid_file != -1) {5317char core_uses_pid = 0;5318ssize_t ret = ::read(core_uses_pid_file, &core_uses_pid, 1);5319::close(core_uses_pid_file);53205321if (core_uses_pid == '1') {5322jio_snprintf(buffer + written, bufferSize - written,5323".%d", current_process_id());5324}5325}5326}53275328return strlen(buffer);5329}53305331bool os::start_debugging(char *buf, int buflen) {5332int len = (int)strlen(buf);5333char *p = &buf[len];53345335jio_snprintf(p, buflen-len,5336"\n\n"5337"Do you want to debug the problem?\n\n"5338"To debug, run 'gdb /proc/%d/exe %d'; then switch to thread " UINTX_FORMAT " (" INTPTR_FORMAT ")\n"5339"Enter 'yes' to launch gdb automatically (PATH must include gdb)\n"5340"Otherwise, press RETURN to abort...",5341os::current_process_id(), os::current_process_id(),5342os::current_thread_id(), os::current_thread_id());53435344bool yes = os::message_box("Unexpected Error", buf);53455346if (yes) {5347// yes, user asked VM to launch debugger5348jio_snprintf(buf, sizeof(char)*buflen, "gdb /proc/%d/exe %d",5349os::current_process_id(), os::current_process_id());53505351os::fork_and_exec(buf);5352yes = false;5353}5354return yes;5355}535653575358// Java/Compiler thread:5359//5360// Low memory addresses5361// P0 +------------------------+5362// | |\ Java thread created by VM does not have glibc5363// | glibc guard page | - guard page, attached Java thread usually has5364// | |/ 1 glibc guard page.5365// P1 +------------------------+ Thread::stack_base() - Thread::stack_size()5366// | |\5367// | HotSpot Guard Pages | - red, yellow and reserved pages5368// | |/5369// +------------------------+ StackOverflow::stack_reserved_zone_base()5370// | |\5371// | Normal Stack | -5372// | |/5373// P2 +------------------------+ Thread::stack_base()5374//5375// Non-Java thread:5376//5377// Low memory addresses5378// P0 +------------------------+5379// | |\5380// | glibc guard page | - usually 1 page5381// | |/5382// P1 +------------------------+ Thread::stack_base() - Thread::stack_size()5383// | |\5384// | Normal Stack | -5385// | |/5386// P2 +------------------------+ Thread::stack_base()5387//5388// ** P1 (aka bottom) and size (P2 = P1 - size) are the address and stack size5389// returned from pthread_attr_getstack().5390// ** Due to NPTL implementation error, linux takes the glibc guard page out5391// of the stack size given in pthread_attr. We work around this for5392// threads created by the VM. (We adapt bottom to be P1 and size accordingly.)5393//5394#ifndef ZERO5395static void current_stack_region(address * bottom, size_t * size) {5396if (os::is_primordial_thread()) {5397// primordial thread needs special handling because pthread_getattr_np()5398// may return bogus value.5399*bottom = os::Linux::initial_thread_stack_bottom();5400*size = os::Linux::initial_thread_stack_size();5401} else {5402pthread_attr_t attr;54035404int rslt = pthread_getattr_np(pthread_self(), &attr);54055406// JVM needs to know exact stack location, abort if it fails5407if (rslt != 0) {5408if (rslt == ENOMEM) {5409vm_exit_out_of_memory(0, OOM_MMAP_ERROR, "pthread_getattr_np");5410} else {5411fatal("pthread_getattr_np failed with error = %d", rslt);5412}5413}54145415if (pthread_attr_getstack(&attr, (void **)bottom, size) != 0) {5416fatal("Cannot locate current stack attributes!");5417}54185419// Work around NPTL stack guard error.5420size_t guard_size = 0;5421rslt = pthread_attr_getguardsize(&attr, &guard_size);5422if (rslt != 0) {5423fatal("pthread_attr_getguardsize failed with error = %d", rslt);5424}5425*bottom += guard_size;5426*size -= guard_size;54275428pthread_attr_destroy(&attr);54295430}5431assert(os::current_stack_pointer() >= *bottom &&5432os::current_stack_pointer() < *bottom + *size, "just checking");5433}54345435address os::current_stack_base() {5436address bottom;5437size_t size;5438current_stack_region(&bottom, &size);5439return (bottom + size);5440}54415442size_t os::current_stack_size() {5443// This stack size includes the usable stack and HotSpot guard pages5444// (for the threads that have Hotspot guard pages).5445address bottom;5446size_t size;5447current_stack_region(&bottom, &size);5448return size;5449}5450#endif54515452static inline struct timespec get_mtime(const char* filename) {5453struct stat st;5454int ret = os::stat(filename, &st);5455assert(ret == 0, "failed to stat() file '%s': %s", filename, os::strerror(errno));5456return st.st_mtim;5457}54585459int os::compare_file_modified_times(const char* file1, const char* file2) {5460struct timespec filetime1 = get_mtime(file1);5461struct timespec filetime2 = get_mtime(file2);5462int diff = filetime1.tv_sec - filetime2.tv_sec;5463if (diff == 0) {5464return filetime1.tv_nsec - filetime2.tv_nsec;5465}5466return diff;5467}54685469bool os::supports_map_sync() {5470return true;5471}54725473void os::print_memory_mappings(char* addr, size_t bytes, outputStream* st) {5474// Note: all ranges are "[..)"5475unsigned long long start = (unsigned long long)addr;5476unsigned long long end = start + bytes;5477FILE* f = ::fopen("/proc/self/maps", "r");5478int num_found = 0;5479if (f != NULL) {5480st->print_cr("Range [%llx-%llx) contains: ", start, end);5481char line[512];5482while(fgets(line, sizeof(line), f) == line) {5483unsigned long long segment_start = 0;5484unsigned long long segment_end = 0;5485if (::sscanf(line, "%llx-%llx", &segment_start, &segment_end) == 2) {5486// Lets print out every range which touches ours.5487if (segment_start < end && segment_end > start) {5488num_found ++;5489st->print("%s", line); // line includes \n5490}5491}5492}5493::fclose(f);5494if (num_found == 0) {5495st->print_cr("nothing.");5496}5497st->cr();5498}5499}550055015502